SPStatefulLongOperation sample

SharePoint long operation is a great component when it comes to run lenghty operations and still give the user nice loading view.

The issue with the mostly used SPLongOperation is that it gives the user static loading message during the whole operation.

The beauty about the not so famous SPStatefulLongOperation that it extends the functionality of SPLongOperation (actually it’s drived from it) and gives us the ability to keep the user posted by the progress of the lengthy operation via the SPLongOperationState Status property.

Important!  SPContext is always null within the stateful oprtation.

Below a quick sample code (in an application page) for your reference:


<asp:Content ID=”PageHead” ContentPlaceHolderID=”PlaceHolderAdditionalPageHead” runat=”server”>


<asp:Content ID=”Main” ContentPlaceHolderID=”PlaceHolderMain” runat=”server”>

    <h1>SPStatefulLongOperation Demo</h1>


        <asp:Button runat=”server” ID=”btnStart” Text=”Start” OnClick=”btnStart_Click”  />



<asp:Content ID=”PageTitle” ContentPlaceHolderID=”PlaceHolderPageTitle” runat=”server”>

Application Page


<asp:Content ID=”PageTitleInTitleArea” ContentPlaceHolderID=”PlaceHolderPageTitleInTitleArea” runat=”server” >

My Application Page



protected void btnStart_Click(object sender, EventArgs e)


            var sites = Microsoft.SharePoint.SPContext.Current.Site.WebApplication.Sites;



                  “<span id=’statusSpan’>Please wait</span>”,


                op =>


                    op.Run(opState =>


                        opState.Status = string.Format(“{0}”, “document.getElementById(‘statusSpan’).innerHTML = ‘Starting….’;”);

                        foreach (Microsoft.SharePoint.SPSite site in sites)


                            opState.Status = string.Format(“{0}”, string.Format(“document.getElementById(‘statusSpan’).innerHTML = ‘Site Id = {0}’;”, site.ID.ToString()));




                    op.EndScript(“document.getElementById(‘statusSpan’).innerHTML = ‘Done’;”);



I hope that helped



Issue opening files in MS Office applications from SharePoint

Strange issue we were facing with opening files from SharePoint into its respective MS Office applications after applying new publishing tool and modify the farm to utilize SSL (https).

The issue was “Sorry, we couldn’t open <file url> file”

After, some research we found the resolution:

1- Close all MS Office Applications

2- Open the “Office <Your Version> Upload Center”


3- Click on “Settings”


4- Click on “Delete cached files”

Try again and yes it works Smile

I hope that helped


Dynamically load AngularJS controller within a modal

First of all, the idea was to have modal dialog using Bootstrap modal (More info.) and hookup controllers dynamically as the new controllers will be registered dynamically when needed.

Now, let’s move into action:

1- Normal AngularJS app definition, just notice the reference of the $controllerProvider (More info.)


2- Main controller definition


3- In our index.html we add the AngularJS controller binding and a simple Bootstrap modal link with the associated target template.


4- Modal target page definition, notice the child controller hookup and the Ajax loading for the child controller definition at the end.


5- Child controller definition, notice it’s done via the cp.register (Controller Provider)


6- Last and the magic trick Smile , after all loaded force compiling the modal main element within the prospective scope.


7- Finally, result will be like the following:


Sample code can be obtained from (here)

P.S. The sample in html only, just open directly from the folder.

I hope that helped


Using SharePoint 2013 Word Automation Services to convert Word file to PDF

In below example, we will demonstrate the solution of converting Word file to PDF file by using the SharePoint 2013 Word Automation Services.

First of all, make sure that the service is configured and running, you can refer to Configuring Word Automation Services for Development.

Initially, add a reference to “Microsoft.Office.Word.Server.dll” which normally resides in:

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.Office.Word.Server.dll

Second, below is the code for taking the SPFile object and pass it to the conversion method, and then wait for the conversion to finish to proceed:

  1. public bool ConvertWordFileToPdf(SPFile file, SPUser user) {  
  2.     if (file == nullreturn false;  
  3.     var fileExtention = System.IO.Path.GetExtension(file.Url);  
  4.     var filePath = string.Format(“{0}/{1}”, file.Web.Site.Url, file.Url);  
  5.     var pdfPath = System.IO.Path.ChangeExtension(filePath, “pdf”);  
  6.     if (fileExtention == “.docx” || fileExtention == “.doc”) {  
  7.         var conversionItemInfo = ConvertWordFileToPDF(filePath, pdfPath, user);  
  8.         if (conversionItemInfo == null) {  
  9.             throw new AccessViolationException(“Word automation services is not accessible”);  
  10.         } else {  
  11.             while (conversionItemInfo.InProgress) {}  
  12.             if (conversionItemInfo.Failed) {  
  13.                 return false;  
  14.             }  
  15.             if (conversionItemInfo.Succeeded) { // Proceed with your own code here  
  16.             }  
  17.         }  
  18.     }  
  19. }  


    Finally, here is the conversion method which creates the conversion job settings which takes care if the conversion for us:

  20. public ConversionItemInfo ConvertWordFileToPDF(string sourceFilePath, string destinationFilePath, SPUser user) {  
  21.     try {  
  22.         var serviceContext = SPServiceContext.GetContext(SPContext.Current.Web);  
  23.         var wordProxy = (WordServiceApplicationProxy) serviceContext.GetDefaultProxy(typeof(WordServiceApplicationProxy));  
  24.         var jobSettings = new ConversionJobSettings();  
  25.         jobSettings.OutputFormat = SaveFormat.PDF;  
  26.         var converter = new SyncConverter(wordProxy, jobSettings);  
  27.         converter.UserToken = user.UserToken;  
  28.         return converter.Convert(sourceFilePath, destinationFilePath);  
  29.     } catch (Exception ex) { // Log the exception    
  30.         return null;  
  31.     }  
  32. }  



  • Make sure that the used SPUser has access to the Word Conversion Service.
  • This method output the exact output of Microsoft Word save as PDF.
  • In the case of PDF conversion, you can use some libraries to optimize the file size (if needed), personally I have tried some but didn’t notice a remarkable difference in the case of text based Word files.
  • Here are the available save formats as well:
  1. namespace Microsoft.Office.Word.Server.Conversions { 
  2. // Summary: //     Represents the supported save formats for output files.  
  3.     public enum SaveFormat { 
  4. // Summary: //     Use the file extension of the output file to determine output format.  
  5.         Automatic = 0, // // Summary: //     Save output file as a Word Document (.docx).  
  6.             Document = 1, // // Summary: //     Save output file as a Word Macro-Enabled Document (.docm).  
  7.             DocumentMacroEnabled = 2, // // Summary: //     Save output file as a Word 97-2003 Document (.doc).  
  8.             Document97 = 3, // // Summary: //     Save output file as a Word Template (.dotx).  
  9.             Template = 4, // // Summary: //     Save output file as a Word Macro-Enabled Template (.dotm).  
  10.             TemplateMacroEnabled = 5, // // Summary: //     Save output file as a Word 97-2003 Template (.dot).  
  11.             Template97 = 6, // // Summary: //     Save output file as a Single File Web Page (.mht).  
  12.             MHTML = 7, // // Summary: //     Save output file as a PDF (.pdf).  
  13.             PDF = 8, // // Summary: //     Save output file as a Rich Text Format document (.rtf).  
  14.             RTF = 9, // // Summary: //     Save output file as a Word XML Document (.xml).  
  15.             XML = 10, // // Summary: //     Save output file as a XPS Document (.xps).  
  16.             XPS = 11, DocumentStrict = 12,  
  17.     }  
  18. }  

Modifying Microsoft Office Word Content Control OpenXml

In my case I had a Microsoft Office Word document which contains content place controls which needs to be filled by specific data after specific business action.

The idea is to select all the descendants from type “SdtElement” which has a tag name specified and then compare it with the provided tag name.

Next, remove all the text from the content control and add our new value.

Sample code:

private void ModifyDocumentPlaceHolder(Document document, string tagName, string value)
            // Find all placeholders with Tag name
            var placeHolders = document.MainDocumentPart.RootElement.
                Where(P => P.Elements<SdtProperties>().FirstOrDefault().
                    Elements<Tag>().FirstOrDefault() != null);

            // Select the required element by tag name
            var requiredPlaceHolder = placeHolders.FirstOrDefault(P =>
                Elements<Tag>().FirstOrDefault().Val == tagName);

            // Remove all text from the place holder
                delegate(Text textObj)
                    textObj.Text =

            // Add the required text
            requiredPlaceHolder.Descendants<Text>().FirstOrDefault().Text = value;


I hope that helped