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”

image

3- Click on “Settings”

image

4- Click on “Delete cached files”

Try again and yes it works Smile

I hope that helped

Ahmed

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.)

image 

2- Main controller definition

image

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

image

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

image 

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

image

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

image

7- Finally, result will be like the following:

image

Sample code can be obtained from (here)

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

I hope that helped

Ahmed

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. }  

     

    Notes:

  • 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.
                Descendants<SdtElement>().
                Where(P => P.Elements<SdtProperties>().FirstOrDefault().
                    Elements<Tag>().FirstOrDefault() != null);

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

            // Remove all text from the place holder
            requiredPlaceHolder.Descendants<Text>().ToList().ForEach(
                delegate(Text textObj)
                {
                    textObj.Text =
 string.Empty;
                });

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

        }

I hope that helped

Ahmed

Kuwait Civil ID Validator

In the following solution, I had implemented a custom Enterprise Library Validator for Kuwait Civil ID.

The validation logic has been acquired from PACI as the following:

1 /// <summary> 2 /// Represent the associated validator attribute for <see cref="CivilIdValidator"/> 3 /// </summary> 4 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] 5 public class CivilIdValidatorAttribute : ValidatorAttribute 6 { 7 /// <summary> 8 /// Creates the <see cref="T:Microsoft.Practices.EnterpriseLibrary.Validation.Validator" /> described by the attribute object providing validator specific 9 /// information. 10 /// </summary> 11 /// <param name="targetType">The type of object that will be validated by the validator.</param> 12 /// <returns> 13 /// The created <see cref="T:Microsoft.Practices.EnterpriseLibrary.Validation.Validator" />. 14 /// </returns> 15 /// <remarks> 16 /// This operation must be overriden by subclasses. 17 /// </remarks> 18 protected override Validator DoCreateValidator(Type targetType) 19 { 20 return new CivilIdValidator(); 21 } 22 }

and the validator class:

1 /// <summary> 2 /// MS EL Custom Validation Attribute for Civil ID validation 3 /// </summary> 4 public class CivilIdValidator : Validator<decimal> 5 { 6 7 8 /// <summary> 9 /// Initializes a new instance of the <see cref="CivilIdValidator"/> class. 10 /// </summary> 11 public CivilIdValidator() : base("","") { } 12 13 /// <summary> 14 /// Does the validate. 15 /// </summary> 16 /// <param name="objectToValidate">The object to validate.</param> 17 /// <param name="currentTarget">The current target.</param> 18 /// <param name="key">The key.</param> 19 /// <param name="validationResults">The validation results.</param> 20 protected override void DoValidate(decimal objectToValidate, object currentTarget, string key, ValidationResults validationResults) 21 { 22 if(!Utilities.IsValidCivilId(objectToValidate.ToString())) 23 { 24 LogValidationResult(validationResults, "???? ????? ??? ???? ???? ?? 12 ???", currentTarget, key); 25 return; 26 } 27 } 28 29 /// <summary> 30 /// Gets the message template to use when logging results no message is supplied. 31 /// </summary> 32 protected override string DefaultMessageTemplate 33 { 34 get 35 { 36 return ""; 37 } 38 } 39 40 41 }

The validation logic:

1 /// <summary> 2 /// Custom utilities used by the applciation 3 /// </summary> 4 public class Utilities 5 { 6 /// <summary> 7 /// Determines whether [is valid civil identifier] [the specified civil identifier]. 8 /// </summary> 9 /// <param name="civilId">The civil identifier.</param> 10 /// <returns></returns> 11 public static bool IsValidCivilId(string civilId) 12 { 13 if (string.IsNullOrEmpty(civilId)) 14 return false; 15 16 if (civilId.Length != 12) 17 return false; 18 19 decimal civilIdDecimal; 20 21 if (!decimal.TryParse(civilId, out civilIdDecimal)) 22 return false; 23 24 int calculation; 25 26 int monthPart = int.Parse(civilId.Substring(3,2)); 27 int dayPart = int.Parse(civilId.Substring(3,2)); 28 29 30 if ((monthPart > 12 || monthPart <1) || (dayPart > 31 || dayPart <1)) 31 { 32 return false; 33 } 34 35 calculation = 2 * int.Parse(civilId.Substring(0,1)) + 1 * int.Parse(civilId.Substring(1, 1)) + 6 * int.Parse(civilId.Substring(2, 1)) + 3 * int.Parse(civilId.Substring(3, 1)) + 7 * int.Parse(civilId.Substring(4, 1)) + 9 * int.Parse(civilId.Substring(5, 1)) + 10 * int.Parse(civilId.Substring(6, 1)) + 5 * int.Parse(civilId.Substring(7, 1)) + 8 * int.Parse(civilId.Substring(8, 1)) + 4 * int.Parse(civilId.Substring(9, 1)) + 2 * int.Parse(civilId.Substring(10, 1)); 36 37 calculation = calculation % 11; 38 39 calculation = 11 - calculation; 40 41 if (calculation != int.Parse(civilId.Substring(11, 1))) 42 return false; 43 else 44 return true; 45 } 46 }

I hope that helped.

Ahmed