Friday, November 17, 2017

Unlocked -Checked-In files in sharepoint

Good article:
https://www.codeproject.com/Articles/93965/Force-SharePoint-Document-Unlocked-Checked-In

OR


Using POWERSHELL
You can unlock it programmatically!
There is no UI to unlock the locked files - as we do have for Check-in Checked-out files. So, Here is my solution to unlock the locked files using PowerShell.
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Web and File URLs
$WebURL ="http://intranet.crescent.com/support/"
$FileURL ="http://intranet.crescent.com/support/T1Support/Reports/ServiceTickets.xlsx" 

#Get Web and File Objects
$web = Get-SPWeb $WebURL
$File = $web.GetFile($FileURL)

#Check if File is locked
 if ($File.LockId -ne $null)
 {
     Write-host "File is Loked out by:" $File.LockedByUser.LoginName
     Write-host "File Lock Type: "$file.LockType
     Write-host "File Locked On: "$file.LockedDate
     Write-host "File Lock Expires on: "$file.LockExpires

     #To Release the lock, Uncomment below lines:
     #$File.ReleaseLock($File.LockId)
     #Write-host "Released the lock!" 
 }
--------------------------------------------------------------------------------------

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:
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())
        {
            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 += &quot;Could not find library: '&quot; + 
                                    this.LibraryField.Text.Trim() + &quot;'.&quot;;
        }
    }
    catch (Exception ex)
    {
        StatusField.Text += Environment.NewLine + &quot;Error occurred. Details: &quot; + 
            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:
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:
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.

Wednesday, March 29, 2017

Step by Step - Always On feature in SQL Server 2012

http://www.sqlhammer.com/how-to-configure-sql-server-2012-alwayson-part-1-of-7/

https://www.mssqltips.com/sqlservertip/2519/sql-server-alwayson-availability-groups--part-1-configuration/

http://www.sqlservercentral.com/blogs/forrards-group-database-blog/2015/08/06/step-by-step-guide-to-setting-up-ms-sql-server-alwayson/

Friday, March 24, 2017

Restore IIS website on WFE

If you accidentally deleted the IIS site in any front-end server or you want to repair WFE IIS. Please use the below steps

When you have multiserver environment, your web application provisioning can go wrong due to many reasons (app pool timeout etc.) and as a result you can get one WFE works while the other does not.

In my case, Deleted IIS folder in my on of WFE and want to restore and I don't want to recreate my web application from scratch. SharePoint provides Provision() and ProvisionGlobally() method.

We ran Provision() on the Deleted WFE and it fixed all our IIS sites (default and internet zone) in one go.

To do this just open power shell on the WFE:

?
$webApp = Get-SPWebApplication https://sharepointsiteURL.com/ 
$webApp.Provision()

$webApp = Get-SPWebApplication https://sharepointsiteURL.com/ 
$webApp.ProvisionGlobally()
If you want you can remove the IIS site completely in WFE IIS manager and Provision() will recreate the IIS site After executing the above commands in powershell