sharepoint 2007 Force SharePoint Document Unlocked / Checked In
来源:互联网 发布:淘宝密令红包不中 编辑:程序博客网 时间:2024/06/07 14:59
Introduction
SharePoint places locks on files in document libraries when you check them out or open them. Sometimes the user's PC crashes, or they lose their internet connection, or solar flares hit the server room, and the lock cannot be released no matter how hard an admin tries. SharePoint calls this the CheckOutStatus which, for this article, I will call a lock since that is effectively what the status is describing.
Some have already written code in a console application to force a check-in of the document. But it only works for long-term locks (check outs). A short-term lock is placed on the document when it's not checked out but the client application is locking it. If, for reasons explained in the Background section, the short-term lock isn't released, you either have to reboot the server or wait until the lock's expiration.
The client application might renew the checkout's expiration time; for example, Office programs renew locks in 10 minute intervals. If the client program doesn't renew the lock, SharePoint is supposed to release it. However, if the client application crashes or a couple other scenarios play out, people end up waiting hours or even days for their document to be unlocked. And to my knowledge, there is no way to unlock a short-term lock through the API (probably by design).
Using this application, you can unlock long-term and short-term locks quickly and easily.
Background
You may want to read this blog post on SharePoint lock types. It does a great job of describing checkout statuses and when they're applied.
A word on short-term locks:
Sometimes when trying to check out a document, they will get an error saying "The file [filename] is checked out or locked for editing by [username]"; if your authentication cookie expired, sometimes [username] is you! This error is well documented by Microsoft here, but the only workaround is to sit and wait for SharePoint to unlock it, which is supposed to take 10 minutes, but sometimes takes hours or days!
As explained in the KB article, this happens when you try to edit the document in the client program and then the program crashes. Also, I've found that this happens when using WebDAV (Explorer) view to open documents without checking them out. It can also happen through the web site if you don't check out the document before editing it.
Normally, you can close the client application and the short-term lock gets released, but sometimes, especially if authentication cookies expire or the application crashes, there are problems, and the lock isn't released. Or maybe that naughty user opened the document without checking it out and then went to lunch, then there's no way to force it free if you can't get into their computer! Even powering off the computer doesn't work sometimes.
I've seen this cause strange things. When you try to check out a document, you might get an error saying "The file [filename] is not checked out."!! Well duh, that's why I'm trying to check it out...I don't fully understand that one, but I think SharePoint is trying to check out the document, realizes it has a CheckOutStatus of ShortTerm, and instead tries to check it in (speculation).
Using the Code
You must run this code from the SharePoint server since it uses the SharePoint object model and not Web Services. When you open the program, you just enter the URL of the site, including the site collection, the name of the document library (as shown in the URL, not the display name), the full file name of the document, and click "Find" to find the document and get the checkout status information on it.
Here's the code:
Collapse | Copy Code
private void FindButton_Click(object sender, EventArgs e)
{
this.StatusField.Text = "Searching..." + Environment.NewLine;
this.StatusField.Refresh();
this.LockStatusField.Text = string.Empty;
try
{
Uri siteUri = new Uri(this.SiteUrlField.Text.Trim());
using (SPWeb web = new SPSite(siteUri.ToString()).OpenWeb(siteUri.AbsolutePath))
{
bool libraryFound = false;
foreach (SPList list in web.Lists)
{
if (list.BaseType == SPBaseType.DocumentLibrary && string.Equals(
list.RootFolder.Url, this.libraryField.Text.Trim(),
StringComparison.OrdinalIgnoreCase))
{
libraryFound = true;
this.statusField.Text += "Found library. Searching for document..." +
Environment.NewLine;
this.statusField.Refresh();
SPQuery NameQuery = new SPQuery();
NameQuery.Query =
"<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='File'>" +
this.filenameField.Text.Trim() + "</Value></Eq></Where>";
NameQuery.RowLimit = 1;
if (recursiveField.Checked)
NameQuery.ViewAttributes = @"Scope=""Recursive""";
if (recursiveAllField.Checked)
NameQuery.ViewAttributes = @"Scope=""RecursiveAll""";
if (!string.IsNullOrEmpty(folderNameField.Text.Trim()))
{
try
{
SPFolder parentFolder = list.ParentWeb.GetFolder(
siteUri.ToString() + "/" + list.RootFolder.Url + "/" +
folderNameField.Text.Trim());
this.statusField.Text += "Found folder." + Environment.NewLine;
NameQuery.Folder = parentFolder;
}
catch (Exception)
{
this.statusField.Text += "Could not find folder: '" +
siteUri.ToString() + "/" + list.RootFolder.Url + "/" +
folderNameField.Text.Trim();
}
}
SPListItemCollection documents = list.GetItems(NameQuery);
if (documents.Count > 0 && documents[0].Name.ToLower() ==
filenameField.Text.Trim().ToLower())
{
SPListItem item = documents[0];
this.statusField.Text += "Found document at: '" + item.Url + "'" +
Environment.NewLine;
ReportItemCheckoutStatus(item);
if (item.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
this.unlockButton.Enabled = true;
else
this.unlockButton.Enabled = false;
itemToUnlock = item;
}
else
{
statusField.Text += "Could not find document: '" +
this.filenameField.Text.Trim() + "'.";
}
break;
}
}
if (libraryFound == false)
StatusField.Text += "Could not find library: '" +
this.LibraryField.Text.Trim() + "'.";
}
}
catch (Exception ex)
{
StatusField.Text += Environment.NewLine + "Error occurred. Details: " +
Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
}
}
It finds the SPWeb from the URL, loops through all the lists in the web (I've found looping is faster than using GetList()), builds a CAML query to find the document, and if the document is found, it reports the checkout status information on it.
The "Unlock" button does different things depending on whether it's a long-term or short-term lock. If it's a long-term lock, it just forces the document to be checked back in. If it's a short-term lock, it has to go to the content database.
Disclaimer: Directly modifying the SharePoint content database is not recommended or supported by Microsoft (but works well in this case).
If the file has a short-term lock, the only solution I could find to release it is by directly modifying the content database. It does a simple update to the CheckoutExpires column in the AllDocs table for the SharePoint document:
Collapse | Copy Code
private void UnlockButton_Click(object sender, EventArgs e)
{
if (itemToUnlock == null)
{
this.StatusField.Text += "No file to unlock!" + Environment.NewLine;
return;
}
this.StatusField.Text = "Unlocking..." + Environment.NewLine;
this.StatusField.Refresh();
if (itemToUnlock.File.CheckOutStatus == SPFile.SPCheckOutStatus.ShortTerm)
{
if (string.IsNullOrEmpty(itemToUnlock.UniqueId.ToString()))
{
StatusField.Text += "File has a short-term lock and " +
"UniqueId cannot be determined for database update.";
return;
}
StatusField.Text += "Unsupported and not recommended WARNING." + Environment.NewLine;
string message = "WARNING!! The selected file has a short-term " +
"lock on it. It should be released in 10 minutes. " +
"You can force the item to be unlocked by setting " +
"the checkout to expire immediately in the content database. " +
"Modifying the database is not supported by Microsoft " +
"and is not recommended. Do you wish to cancel?";
if (MessageBox.Show(message, "WARNING",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1) == DialogResult.No)
{
try
{
UpdateItemCheckoutExpiration(itemToUnlock);
}
catch (Exception ex)
{
StatusField.Text += Environment.NewLine +
"Error occurred. Details: " +
Environment.NewLine + ex.Message +
Environment.NewLine + ex.StackTrace;
return;
}
StatusField.Text += "Database updated. File should now be unlocked.";
// wait 2 seconds for the file to get unlocked
System.Threading.Thread.Sleep(2000);
ReportItemCheckoutStatus(itemToUnlock);
}
}
else if (itemToUnlock.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{ // long-term lock, check it in manually
try
{
itemToUnlock.File.CheckIn("Forced Checkin");
this.StatusField.Text += "File checked in." + Environment.NewLine;
ReportItemCheckoutStatus(itemToUnlock);
}
catch (Exception ex)
{
StatusField.Text += Environment.NewLine + "Error occurred. Details: " +
Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
return;
}
}
else
{
this.StatusField.Text += "File doesn't have a lock." + Environment.NewLine;
}
if (itemToUnlock.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
this.UnlockButton.Enabled = false;
}
Here's the code to update the content database:
Collapse | Copy Code
private void UpdateItemCheckoutExpiration(SPListItem item)
{
SqlConnection contentDatabaseConnection = null;
try
{
contentDatabaseConnection = new SqlConnection(
item.Web.Site.ContentDatabase.DatabaseConnectionString);
contentDatabaseConnection.Open();
string UpdateCommandText = string.Format("UPDATE dbo.AllDocs SET " +
"CheckoutExpires = '{0:yyyy-MM-dd HH:mm:ss:fff}' WHERE Id = '{1}'",
DateTime.Now.ToUniversalTime(), item.UniqueId.ToString());
SqlCommand UpdateCommand = new SqlCommand(UpdateCommandText,
contentDatabaseConnection);
SqlDataAdapter contentDataAdapter = new SqlDataAdapter();
contentDataAdapter.UpdateCommand = UpdateCommand;
contentDataAdapter.UpdateCommand.ExecuteNonQuery();
contentDatabaseConnection.Close();
}
catch (Exception)
{
throw;
}
finally
{
if (contentDatabaseConnection != null &&
contentDatabaseConnection.State != ConnectionState.Closed)
contentDatabaseConnection.Close();
}
}
Points of Interest
Microsoft's recommendation to simply "wait 10 minutes" for the this error to be fixed is ridiculous, and many times doesn't work. I've spent nearly an entire day looking for ways to fix this, and I hope I save someone out there the frustration and time on this one.
History
•First release.
•Updated 10-28-10: Added recursive controls and tweaked code to recursively search folders in a document library. Added ability to search a specific folder for files.
•Updated 06-14-2012: Added exception handling to ReportItemCheckoutStatus to handle stupid SharePoint exceptions when trying to call CheckedOutDate.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
- sharepoint 2007 Force SharePoint Document Unlocked / Checked In
- sharepoint 2007 force close file
- SharePoint--CMS--Document Management
- 401 UNAUTHORIZED in SharePoint 2007
- How to use document library in Sharepoint 2010
- Introducing Document Management in SharePoint 2010 介绍SharePoint 2010中的文档管理
- sharepoint 2007 迁出文档时报错:sharepoint 服务器错误:the file "xxxxxxxxx" is not checked out
- [SharePoint] Enable the anonymous user access in SharePoint 2007
- [SharePoint] Deployment and Programming AJAX server code in SharePoint 2007
- SharePoint
- SharePoint
- SharePoint
- sharepoint
- sharepoint
- Sharepoint
- Sharepoint
- sharepoint
- SharePoint
- Centos上搭建能用于ok6410开发板的tftp服务器
- url地址编码与解码
- 如何保证数据库完整性
- CXF 入门步骤 详解:HelloWorld接口发布
- 学习PHP遇到的乱码问题
- sharepoint 2007 Force SharePoint Document Unlocked / Checked In
- SendMessage 函数
- 安装setuptools的问题
- 程序员面试、算法研究、编程艺术、红黑树、数据挖掘5大经典原创系列集锦与总结
- 一个小程序员3个月的学习历程
- 第一次写MySQL存储过程遇到的关于DELIMITER的问题
- 海量数据处理
- 在Ubuntu 10.04下安装Google拼音输入法
- 重新安装一个linux系统后如何快速搭建可用于开发板nfs挂载根文件系统的过程