Friday, November 17, 2017

Unlocked -Checked-In files in sharepoint

Good article:


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 =""
$FileURL ="" 

#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:
     #Write-host "Released the lock!" 


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.


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.LockStatusField.Text = string.Empty;
        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(),
                    libraryFound = true;
                    this.statusField.Text += "Found library. Searching for document..." +

                    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()))
                            SPFolder parentFolder = list.ParentWeb.GetFolder(
                                siteUri.ToString() + "/" + list.RootFolder.Url + "/" +
                            this.statusField.Text += "Found folder." + Environment.NewLine;
                            NameQuery.Folder = parentFolder;
                        catch (Exception)
                            this.statusField.Text += "Could not find folder: '" +
                               siteUri.ToString() + "/" + list.RootFolder.Url + "/" +

                    SPListItemCollection documents = list.GetItems(NameQuery);
                    if (documents.Count > 0 && documents[0].Name.ToLower() == 
                        SPListItem item = documents[0];
                        this.statusField.Text += "Found document at: '" + item.Url + "'" +


                        if (item.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                            this.unlockButton.Enabled = true;
                            this.unlockButton.Enabled = false;
                        itemToUnlock = item;
                        statusField.Text += "Could not find document: '" + 
                            this.filenameField.Text.Trim() + "'.";

            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;

    this.StatusField.Text = "Unlocking..." + Environment.NewLine;

    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.";

        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)
            catch (Exception ex)
                StatusField.Text += Environment.NewLine + 
                    "Error occurred. Details: " +
                    Environment.NewLine + ex.Message + 
                    Environment.NewLine + ex.StackTrace;

            StatusField.Text += "Database updated. File should now be unlocked.";
            // wait 2 seconds for the file to get unlocked
    else if (itemToUnlock.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
    { // long-term lock, check it in manually
            itemToUnlock.File.CheckIn("Forced Checkin");

            this.StatusField.Text += "File checked in." + Environment.NewLine;
        catch (Exception ex)
            StatusField.Text += Environment.NewLine + "Error occurred. Details: " +
                Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
        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;
        contentDatabaseConnection = new SqlConnection(

        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, 
        SqlDataAdapter contentDataAdapter = new SqlDataAdapter();
        contentDataAdapter.UpdateCommand = UpdateCommand;
    catch (Exception)
        if (contentDatabaseConnection != null && 
                 contentDatabaseConnection.State != ConnectionState.Closed)

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

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 

$webApp = Get-SPWebApplication 
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

Tuesday, October 18, 2016

SharePoint Designer 2010 workflow on the specific folder of library

SharePoint Workflow could not be associated with folder, but you could create a List Workflow and specify the following condition to verify if item is located under a folder named Test/ Orders:
CurrentItem:Path ends with Test
enter image description here

Friday, August 26, 2016

SharePoint 2013 Interview Questions and Answers

Q1: Can you deploy .wsp Solutions from SharePoint 2010 in SharePoint 2013?Ans: Yes. SharePoint 2013 provides Support for both 14 Hive and 15 Hive. Solutions from SharePoint 2010 can be deployed in SharePoint 2013 either in 14 Hive,15 Hive or both. This can be done using the new “CompatabilityLevel” parameter of Install-SPSolution cmdlet with which you can now Deploy your wsp Solutions to 14 hive, 15 hive or both. For more Info see DEPLOY SHAREPOINT 2010 SOLUTIONS IN SHAREPOINT 2013

 Q2: Can you Create & Deploy Sandbox Solutions in SharePoint 2013?
Sandbox Solutions are depreciated in SharePoint 2013.You can still Create them and deploy them but they are not supported by Microsoft (not 100% sure about this though).

Q3: What is the new JS Link Property on SPField?
Ans: New “SPField.JSLink” property has been added to help specify any external JavaScript file Containing any Rendering logic for Out-of-Box or Custom field type.With JSLink developers can now Control the Rendering (the presentation and validation) of any Field (Custom or Out-of-box) on List forms as well as in Views by simply adding a reference to an External or deployed JavaScript file.

Q4: Whats are the new Delegate Controls in SharePoint 2013?
In SharePoint 2013, three New Delegate Controls have been Introduced for the purpose of displaying the new Top Suite bar (with links SkyDrive, NewsFeed,Sync,follow). These Controls are -

  • SuiteBarBrandingDelegate delegate Control
  • SuiteLinksDelegate delegate Control
  • PromotedActions Delegate Control
Q5: What are the Changes in CSOM and REST based APIs?
Ans:  Microsoft has improved both Client Side Object Model (CSOM) and Representational State Transfer (REST) based APIs by adding a much needed support for the Search, User Profiles, Taxonomies, and Publishing Object Model.Client.svc service is extended with REST capabilities and accepts HTTP GET, PUT, POST requests.

Q6: What’s the new App model?
 SharePoint 2013 Introduces a Cloud App Model that enables you to Create apps.Apps for SharePoint are self-contained pieces of functionality that extend the capabilities of a SharePoint website. An app may include SharePoint components such as lists, workflows, and site pages, but it can also surface a remote web application and remote data in SharePoint.

Q7: What is the new SPSecurityEventReceiver?
Ans:  SharePoint 2013 Introduces a Cloud App Model that enables you to Create apps.Apps for SharePoint are self-contained pieces of functionality that extend the capabilities of a SharePoint website. An app may include SharePoint components such as lists, workflows, and site pages, but it can also surface a remote web application and remote data in SharePoint.

Q8: What's new Mobility Feature in SharePoint 2013?
Ans: With the new mobility features in SharePoint 2013, you can create SharePoint powered mobile applications for Windows Phone using the new SharePoint phone application wizard template in Visual Studio. You can integrate new features introduced in SharePoint 2013, such as the Geolocation field type and “push" notifications from SharePoint Server, into your mobile applications.

Q9: What are new Apps for SharePoint?
Ans: SharePoint 2013 introduces a Cloud App Model that enables you to create apps. Apps for SharePoint are self - contained pieces of functionality that extend the capabilities of a SharePoint website. An app may include SharePoint components such as lists, workflows, and site pages, but it can also surface a remote web application and remote data in SharePoint.

Q10: Q46: What are Callout Popups in SharePoint 2013.
 Similar to Dialog framework in SharePoint 2010, Microsoft has added a new Callout Popup framework to Create Hover Popups that you know as Preview Windows as well. These Notification\Tooltip\Help (whatever you call it..) Callout Popups can be fully Customized to add Custom Text & Actions for guiding End-users.For more details see The new Hover Over\Preview\Callout Popups in SharePoint 2013.

Q11: Is Callout Popups a replacement to Dialogs in SharePoint 2013.
 No. Dialog Framework still exists.

Q12: Can we view PDF files in Callout Popups?
 Yes. A Custom Result type and Display template would be needed.

Q13: Are there any Changes to Solutions deployed in \bin directory and GAC in SharePoint 2013?
 You can no longer add partial trust Solution Packages to the \bin directory.Any files deployed to the \bin directory must be full trust. Any deployment scripts needs to be updated to make sure that they specify the correct trust level. After the release of .NET Framework 4.0, the GAC was split into two, one for each CLR.
c:\windows\assembly is the location for .NET versions 1.0 through 3.5 and c:\windows\\assembly is location for all the dlls for project Created in .NET Framework 4.0.

 Q14: How are Sandbox Solution Migrated in SharePoint 2013?
 Sandbox Solutions are upgraded with the Content databases.

Q15: What’s new with Visual WebPart in SharePoint 2013?
 A new Visual WebPart Template has been added to Visual Studio 2012 for Creating Visual Webparts for SharePoint 2013. In this new Template both the User Control and WebPart Classes are merged to Create one template unlike SharePoint 2010 where you had a separate ascx and webpart file.Also, now you can Create both Sandbox and Farm solutions using Visual WebPart Template.

Q16: What’s the new TilesViewWebPart in SharePoint 2013?
 SharePoint 2013 Introduces a new “Getting Started” WebPart that has “Tiles” to provide an easy access to some of the main links in the Site like – adding lists\libraries,Creating masterpage etc.To Programmatically Create this new WebPart a new abstract base class TilesViewWebPart has been added in SharePoint API.You have to Create a Custom Webpart and Inherit from TilesViewWebpart and Override GetTiles() to Create Custom tiles.

Thursday, August 25, 2016

SharePoint Server 2016 Installation step by step

Captured from the below URL

SharePoint Server 2016 Preview has been released earlier today, check my previous post for Download and Product Key details, installation media is available for a trial period of 180 days.
I have completed a Single-Server installation of SharePoint Server 2016 with Database server on a separate machine. I am sharing the installation details here which can be helpful for many who are new to SharePoint. The installation is similar to the older versions of SharePoint except MinRoleTopolgy which is introduced for the first time in SharePoint 2016.

System Requirement

I have used the below hardware and software configuration form my current installation.

Hardware Requirement

ScenarioProcessorRAMHard disk
Database Server64-bit, 4 cores8-24 GB80 GB for system drive100 GB for second drive and additional drives
SharePoint Server64-bit, 4 cores8-12 GB80 GB for system drive80 GB for second drive
Software Details:
ServerOSInstallation media
Database ServerWindows Server 2012 R2 – with latest updatesSQL Server 2014 with SP1 – x64
SharePoint ServerWindows Server 2012 R2 – with latest updatesSharePoint Server 2016 Preview

 SharePoint Server 2016 Preview installer

Open the SharePoint Server 2016 Preview installer file from SharePoint 2016 setup which will look like the below:
SharePoint Server 2016 - Installation Screen
Prerequisites Installation
You need to install software prerequisites first before the installation of SharePoint Server 2016, the prerequisites installation can ask for restart multiple time. Start the prerequisites installation as shown below:
SharePoint Server 2016 - Preparation Tool
On next page, you can view the license agreement which you have to accept if you want install, you have to accept it as you having no other choice. Prerequisites installation will take some and will also ask for restart. After restart, re-run the installer file and run prerequisites, this will again ask for agree on terms. Again continue it and wait for the installer to complete prerequisites.
SharePoint Server 2016 - Preparation Tool install wizard
After completion, you can see the installation status. Installation status in my machine is listed below, all installed successfully except .NET framework.
  • Application Server Role, Web Server (IIS) Role: configured successfully
  • Microsoft SQL Server 2012 Native Client: was already installed (no action taken)
  • Microsoft ODBC Driver 11 for SQL Server: installed successfully
  • Microsoft Sync Framework Runtime v1.0 SP1 (x64): installed successfully
  • Windows Server AppFabric: installed successfully
  • Microsoft Identity Extensions: installed successfully
  • Microsoft Information Protection and Control Client 2.1: installed successfully
  • Microsoft WCF Data Services 5.6: installed successfully
  • Cumulative Update Package 1 for Microsoft AppFabric 1.1 for Windows Server (KB2671763): installed successfully
  • Microsoft .NET Framework 4.5.2: was already installed (no action taken)
  • Update for Microsoft .NET Framework to disable RC4 in Transport Layer Security (KB2898850): installation error
  • Visual C++ Redistributable Package for Visual Studio 2013: installed successfully
SharePoint Server 2016 - Preparation Tool restart
I have restarted the machine as it was asking to restart, as you have noticed the one installation error “Microsoft .NET Framework to disable RC4 in Transport Layer Security, you need to install the security update for .net framework”.
The error patch description is “A security issue has been identified that could allow an unauthenticated remote attacker to compromise your system and gain access to information”
So you can download the security patch from Microsoft Download Center through this URL
SharePoint Server 2016 - Preparation Tool installation complete
After installation, run the perquisites again and now you can see the issue is resolved. And we are good to install SharePoint 2016.

SharePoint Server 2016 Installation

Now after the perquisites installation, click on the SharePoint Server 2016 installation link to start the installation. Setup will first prepare the installation files and verify prerequisites and then will start the installation.
On first screen you will be prompt for the Product Key, you can enter key “NQTMW-K63MQ-39G6H-B2CH9-FRDWJ” for SharePoint Server 2016 Preview release.
SharePoint Server 2016 - Product Key
Once again you have to accept the license terms :)
SharePoint Server 2016 - License Terms
Choose the file location for SharePoint server and search server files. Search index files will be stored in local hard drive which can be very large so make sure that there is sufficient free space in selected drive. I will recommend you to use a separate drive for search index and default drive for SharePoint files.
SharePoint Server 2016 - File Location
Click on install now button to start the installation. The installation will take a few minutes to complete, in below image you can see the complete installation status, you can select the check box the start configuration wizard after the installation or you can manually start the configuration wizard.
SharePoint Server 2016 - Installation Wizard completed
SharePoint Product Configuration Wizard
The configuration wizard will start a welcome screen, press next to continue. The following services may have to be started or reset during configuration:
  • Internet Information Services
  • SharePoint Administration Service
  • SharePoint Timer Service
So choose yes to restart the services if required and continue with the configuration wizard.
SharePoint Server 2016 - Configuration Wizard Started
Select Create a new server farm option from the next step as shown in below screen, if you are already have installed a new farm and doing a MinRole installation then select the first option to connect to an existing server farm.
SharePoint Server 2016 - Configuration Wizard Connect Server Farm
Enter the database server details and database access account details, use a separate user for this but I am using the same SPAdmin user for the preview installation. I have assigned it below rights in DB server:
  • Dbcreator
  • SecurityAdmin
  • SysAdmin
SharePoint Server 2016 - Configuration Wizard Database Settings
If you are facing issues in connecting to SQL Server then make sure TCP/IP is enabled in SQL Server Configuration Manager. If you still getting the error then turn off the firewall on SQL server machine.
SQL Server 2014 - Configuration Manager

After completing the database settings, press next which will take to you on Farm security settings page. Enter passphrase here which is required to secure the farm configuration data and is required for each server that joins the farm.
SharePoint Server 2016 - Configuration Wizard Passphrase
Server Roles or the MinRoletopology
Here comes the MinRoles, SharePoint Server 2016 has six types of server roles:
  • Front-end
  • Application
  • Distributed Cache
  • Search
  • Custom
  • Single-Server Farm
You can either select single-server farm or can do a multi-server installation using MinRolestopology. If you have selected Single-Server Farm then you cannot extend to Multi-Server environment, so if you plan to extend to multi-Server farm in future then select the Custom MinRole or Application.
I am using single-server farm installation so will go with the last option.
SharePoint Server 2016 - Configuration Wizard MinRoles
On next screen, you can specify port for Central Admin or can use the default which is selected randomly. I have never used the default port, I always an easy one which I can remember like 5555. Select NTLM installation mode at this phase and press next.
SharePoint Server 2016 - Configuration Central Administration Web Application
Verify the settings in configuration wizar, press next to start the wizard. Advance option is not enabled for Single-Server installation.
SharePoint Server 2016 - Configuration Wizard Completed
Press Next button, it will start the configuration of SharePoint farm. This is similar to what we do in past with MOSS 2007, SharePoint 2010 and SharePoint 2013 or even with SharePoint Foundation which is no more part of SharePoint 2016.
SharePoint Server 2016 - Configuration Product Wizard
The wizard can take some time and if you get some errors then you have to verify the roles of the user in SQL Server. If everything went smooth then if will finish successfully then it means having a good day otherwise some more effort required :)
Being a SharePoint MVP, I am quite lucky to install it without any hurdle.
SharePoint Server 2016 - Product Configuration Successful
So now, happy time for me to do some SharePointing on SharePoint Server 2016. After the installation, run the services wizard from Central Administration, setup will take you to the service configuration wizard page, you can either configure them through wizard and can also configure them manually.
SharePoint Server 2016 - Service Configuration Wizard
As this is test environment, so I will prefer configuring services using wizard. We can define a separate account for services but I am using the same SharePoint Admin account for all services.
SharePoint Server 2016 - Service Configuration Wizard Page
This will complete the services wizard for me and now I am ready to explore SharePoint.
SharePoint Server 2016 - Central Administration Home
Below you can see the central administration page from my machine, and yes there are many new features in 2016, in below screen you can see one of them related to configure hybrid OneDrive and Site features underOffice 365.
Keep visiting, I will also share the hosted environment details so you can able to test the hosted preview of SharePoint Server 2016.