Wednesday, August 20, 2014

SharePoint 2013 - Generate document with data using server object model

When we provide a content management solution with SharePoint, often we need to generate reports or documents using existing data. To generate reports we can use SSRS with “SharePoint List” as the data source. But, how can we generate a word document in a given template?

In this article I will show how to generate a word document with data using SharePoint server object model. To explain the concept I will implement following scenario.

  • Generate contract approval summary document from a template
  • Fill approvers section from list fields

Following are the steps we need to follow.

1. Create a content type and associate with list fields

I’ve created the content type with necessary fields in visual studio and deployed to the farm.

image

2. Associate the content type to a document library and go to advanced settings to change the document template

we will navigate to advanced settings and upload an empty word document (e.g.: template.docx)

image

3. Click on edit template and modify the document to build the template

image

To add dynamic content, we will use quick parts section of the document. As you can see, the content type fields are available in the quick parts section. we will embed those fields to our document accordingly

image

image

Then we will save changes

4. Use following code to create document

  1. var web = SPContext.Current.Web;
  2. web.AllowUnsafeUpdates = true;
  3.  
  4. var tplurl = listItem.ParentList.ContentTypes["Contract Approval Summary"].DocumentTemplateUrl;
  5. byte[] stream = web.GetFile(tplurl).OpenBinary();
  6.  
  7.  
  8. var itemProperties = new Hashtable();
  9. itemProperties.Add("AGMName", agmName);
  10. itemProperties.Add("RegionalControllerName", regionalName);
  11. itemProperties.Add("RVPName", rvpName);
  12.  
  13. listItem.ParentList.RootFolder.Files.Add(listItem.DisplayName + " Approval Summary.docx", stream, itemProperties, true);
  14. web.AllowUnsafeUpdates = false;

That will create the document with required fields.Those fields will be embedded to the document as per the template

Sunday, August 3, 2014

Programmatically add tasks to timeline in SharePoint 2013 Tasks list

In a previous post I described about the new Timeline feature in SharePoint 2013. But tasks are not added to the timeline automatically, which is a huge drawback. As a result we need to create the task and it to the timeline manually as below.

image

From this post I will explain how to add tasks to timeline automatically. There are two options to derive at a solution. They are,

  • Using JavaScripts
  • Using an Event Receiver

In this article I will show a way to implement the task using Item Added event receiver configured to Tasks list type. Following are two logical steps included in the solution.

1. Set required properties in the tasks list

In the RootFolder of a particular Tasks list, there are three properties relevant to the Timeline control. When we create the list, those properties are not automatically set. As a result we have to set those three properties, namely,

  • TimeLineDefaultView
  • TimeLineAllViews
  • TimeLine_TimeLine

2. Get xml document in TimeLine_TimeLine property, and add required nodes

We have to add xml nodes to “tskSet” and “mlSet” sections to represent the task which is to be displayed in Timeline control.

Following is the sample code I used to execute above steps

  1. var web = properties.Web as SPWeb;
  2. var doc = new XmlDocument();
  3. var taskList = web.Lists[properties.ListId];
  4. var root = taskList.RootFolder;
  5.  
  6. if (root.Properties["Timeline_Timeline"] == null)
  7. {
  8. //Add timeline related properties
  9. root.SetProperty("TimelineDefaultView", "Timeline");
  10. root.SetProperty("TimelineAllViews", "Timeline");
  11. //Add default xml to Timeline_Timeline property
  12. root.SetProperty("Timeline_Timeline",@"<TLViewData><fmtSet><fmt id='0' clr='FFEE2222' thm='0001' t1='0' t2='1' type='0' /><fmt id='1' clr='FFEE2222' thm='0001' t1='2' t2='3' type='1' /><fmt id='2' clr='FFEE2222' thm='0001' t1='4' t2='5' type='2' /><fmt id='3' clr='FFEE2222' thm='0001' t1='6' t2='7' type='3' /></fmtSet><fltSet><ft id='{00000000-0000-0000-0000-000000000000}' uid='4294967295' uidSrc='1' onTL='0' fmt='1' y='4294967282' x='0' h='20' /></fltSet><tskSet><t id='{00000000-0000-0000-0000-000000000000}' uid='4294967295' uidSrc='1' onTL='0' fmt='0' ch='4294967295' /></tskSet><options dateFormat='255' panZoomT='9' ProjSummFmt='3' showDates='1' showProjSummDates='0' showToday='1' showTS='1' timelineHeight='133' timelineWidth='-1' timescaleT='8' todayT='10' /><mlSet>
  13. <m id='{00000000-0000-0000-0000-000000000000}' uid='4294967295' uidSrc='1' onTL='0' fmt='2' y='35' x='0' /></mlSet><txtSet><style id='0' type='0' clr='FFEE2222' thm='0001' sz='8' font='Segoe UI' bold='0' ital='0' und='0' strk='0' /><style id='1' type='1' clr='FFEE2222' thm='0001' sz='8' font='Segoe UI' bold='0' ital='0' und='0' strk='0' /><style id='2' type='2' clr='FF999999' thm='0001' sz='8' font='Segoe UI' bold='0' ital='0' und='0' strk='0' /><style id='3' type='3' clr='FFB3B3B3' thm='0001' sz='8' font='Segoe UI Light' bold='0' ital='0' und='0' strk='0' /><style id='4' type='4' clr='FF525051' thm='0001' sz='10' font='Segoe UI' bold='0' ital='0' und='0' strk='0' /><style id='5' type='5' clr='FFB3B3B3' thm='0001' sz='8' font='Segoe UI Light' bold='0' ital='0' und='0' strk='0' /><style id='6' type='6' clr='FF999999' thm='0001' sz='9' font='Segoe UI' bold='0' ital='0' und='0' strk='0' /><style id='7' type='7' clr='FF999999' thm='0001' sz='8' font='Segoe UI' bold='0' ital='0' und='0' strk='0' /><style id='8' type='8' clr='FF999999' thm='0001' sz='8' font='Segoe UI' bold='0' ital='0' und='0' strk='0' /><style id='9' type='9' clr='FFFFA614' thm='0001' sz='8' font='Segoe UI Semibold' bold='1' ital='0' und='0' strk='0' /><style id='10' type='10' clr='FFFFA72B' thm='0001' sz='10' font='Segoe UI Semibold' bold='0' ital='0' und='0' strk='0' /></txtSet></TLViewData>");
  14. root.Update();
  15. }
  16.  
  17. doc.LoadXml(root.Properties["Timeline_Timeline"].ToString());
  18.  
  19. //Create required xml nodes
  20. var tElement = doc.CreateElement("t");
  21. tElement.SetAttribute("id", "{" + properties.ListItemUniqueId.ToString() + "}");
  22. tElement.SetAttribute("uid", properties.ListItemId.ToString());
  23. tElement.SetAttribute("uidSrc", "1");
  24. tElement.SetAttribute("onTL", "1");
  25. tElement.SetAttribute("fmt", "0");
  26. tElement.SetAttribute("ch", "4294967295");
  27.  
  28. var mElement = doc.CreateElement("m");
  29. mElement.SetAttribute("id", "{" + properties.ListItemUniqueId.ToString() + "}");
  30. mElement.SetAttribute("uid", properties.ListItemId.ToString());
  31. mElement.SetAttribute("uidSrc", "1");
  32. mElement.SetAttribute("onTL", "1");
  33. mElement.SetAttribute("fmt", "2");
  34. mElement.SetAttribute("y", "35");
  35. mElement.SetAttribute("x", "0");
  36.  
  37. //Add created nodes to xml document
  38. doc.SelectNodes("/TLViewData/tskSet/t")[doc.SelectNodes("/TLViewData/tskSet/t").Count - 1].AppendChild(tElement);
  39. doc.SelectNodes("/TLViewData/mlSet/m")[doc.SelectNodes("/TLViewData/mlSet/m").Count - 1].AppendChild(mElement);
  40. root.SetProperty("Timeline_Timeline", doc.OuterXml);
  41. root.Update();
  42.  
  43. base.ItemAdded(properties);

After deploying the solution, tasks are added to the timeline automatically.

Thursday, July 31, 2014

Get the display name of a value in person of group field from SharePoint 2013 "_api/web/lists" service

Let’s assume that we need to access a SharePoint list using built in web services. To do the task we can use a service like below.
http://sp13/sites/dev/_api/web/lists/getbytitle('Regions')/items 
What happen if we have a “Person or Group” column in the list? We would get a result like below.

image

As you can see we get only the User Id instead of other properties like login name or display name.
To get those properties, we just need to expand respective properties as shown below.
http://sp13/sites/dev/_api/web/lists/getbytitle('Regions')/items?$select=Area_x0020_General_x0020_Manager/Name,Area_x0020_General_x0020_Manager/Title&$expand=Area_x0020_General_x0020_Manager/Id
Following is the result I got, which is what I expected

image

Friday, July 25, 2014

Cross site collection data access via HTTP web service for a SharePoint 2013 designer workflow. Resolving Unauthorized exception

Recently I created a SharePoint 2013 approval workflow where I had to take approvers from a list located at a different SharePoint site collection.

In this example I have two site collections named Config and Project where I have created the workflow in the Project site collection using SharePoint Designer. In the Config site collection I have a list called Approvers where I store relevant information regarding approvers.

Following diagram shows the scenario I described.

image
To get relevant information from Config site collection, I will use SharePoint api web services. For an example I could use following service to return all items in that list.
“http://sp13/Sites/config/_api/web/lists/getbytitle('Approvers')/items”
Calling a HTTP web service through a SharePoint 2013 Designer based workflow is straight forward. I have explained that in this blog post.

Although I have followed the steps correctly, I was getting an “Unauthorized” exception all the time. I’ve given necessary permissions to the list and web application but still I was getting the same error.

Later I figured out that we need to provide permissions to the workflow explicitly if we need to access resources beyond the current site. Following are the steps I followed to configure permissions to the workflow

1. Activate “Workflows can use app permissions” site feature in the site where I create the workflow (http://sp13/Sites/project )
image
2. Navigate to Site Settings –> Site app permissions where you can see an item called workflow
image
3. Copy the client section of the App Identifier as shown below
image
4.Navigate to <site url>/_layouts/15/appinv.aspx to configure permissions. Then add the client section of the App Identifier in the App Id section and click Lookup to populate content.
image
5. Then we need to specify App’s Permission Request XML
<AppPermissionRequests>
    <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>
Since we are accessing beyond the current site collection, we will use “http://sharepoint/content/tenant” as the scope. More information on app permission and available scopes can be found on this article.

6. Finally we will trust the workflow
image
This will allow our workflow to access resources beyond the current site collection.

Monday, July 14, 2014

SharePoint 2013 Workflow-Check if required documents are available inside a Document Set prior to the approval process

We can use SharePoint Designer workflows to author an approval process. Sometimes the approval process can be complex where we need to create advanced workflows. In SharePoint 2013 workflows we can use HTTP web services and loops to assist such instances.

Recently I created an approval workflow to a library which stores document sets. Following is the pre-condition to the approval.

Each document set has two allowed content types named “Policy Document” and “Policy Checklist”. The approval process proceeds if the document set contain at least one document from each document set. Otherwise the approval process terminates.

Following are the questions we need to address

  • How can we access documents within a document?
  • How can we get the content type ID of each document?

We will call two web service methods to obtain relevant information and will use built in loop to assist the process. Following are the steps I used to answer above questions

1. Construct the server relative URL for document sets

Let’s assume our document set is located at “https://sp13/sites/dev/Shared Documents/DocumentSet1”. Below activity will remove “https://sp13/sites/dev/” component and assigns “Shared Documents/DocumentSet1” to a variable named “itemFolder”

image

2. Prerequisites to call SharePoint REST API

As I mentioned earlier, SharePoint 2013 workflows can call RESTful services by default. In this case we will use services provided in “_api/web”. Since those services provide xml output we have convert them to JSON.

To do that we will create a dictionary. For both “Accept” and “Content-Type” variables provide “application/json;odata=verbose” as the value

image 

image

3. Call web service to get all items within the document set

To get items under a document set we will use GetFolderByServerRelativeUrl() method. Following is a sample service call

https://sp13/sites/dev/_api/web/GetFolderByServerRelativeUrl('Shared Documents/Set1')/Files

If you need further information on this method you can refer this blog post. To call the service using workflow we will use Call HTTP web service activity as shown below.

Following are the sub steps

A. When constructing  the url, we will use the sever relative path created in step 1

image

B. Create an empty dictionary variable named JSONResults

C. Edit properties of the activity to assign “Header” and “JSONResults” dictionaries to RequestHeaders and ReseponseContent parameters.

image

Finally the activity looks like below

image

Unfortunately this service doesn’t return Content Type ID property. As a result we will get a property from this service which can be input to our second service to obtain Content Type Id. We will call the second service in step 8.

4. Store results to a separate dictionary called allItems

image

5. Get count of items to start the loop

image

6. Store variable to hold content type IDs

image

7. Create a loop to iterate each item we have in allItems dictionary

Create an integer variable named index.

image

Then we will get the ServerRelativeUrl property from the item and assign it to variable serverRelativeUrl

image

8. Call the second web service to get content type id.

Since “GetFolderByServerRelativeUrl()/Files” method does not return the content type of items. As a result we need to execute another service to do so. We will use the ServerRelativeUrl property returned from step 7 as an input to the second service

This time we will call GetFileByServerRelativeUrl() method. Following is a sample of the service call.

https://sp13/sites/dev/_api/Web/GetFileByServerRelativeUrl('/sites/dev/Shared Documents/Set1/3.txt')/ListItemAllFields

If you need further information on this method you can refer this blog post as well.

As we did for the first method we will call HTTP web service activity as shown below

image

image

9. Get ContentTypeId property of the item

This service returns just a single item. So it is easy to get the value

image

10. Create Boolean variables to store content type availability 

Since we have two content types, we have two Boolean variables named “ct1IsAvailable” and “ct2IsAvailable”

image

11. Set Boolean value true if the content type was found

image

12. Specify Termination condition at the end of the loop

image

13. Conditionally allow or restrict the approval

image

14. Terminate the workflow

image

Summary

In the above article I explained how to use http web services available in “_api/web” within SharePoint 2013 workflows. A practical scenario was also explained where we need to check at least one document from each content type available in the document set.

Tuesday, June 24, 2014

Presentation–Site provisioning techniques including site provisioning providers for SharePoint 2013

Recently I did a presentation on site provisioning providers at Sri Lanka SharePoint forum. In that session I described about other site provisioning techniques as well.

10393838_10152318026097530_3673986027299882108_n

There are many site provisioning techniques including Site Definitions, Feature Stapling, Web Templates, Site Provisioning Provider (SPWebProvisioningProvider) etc.. If we need to obtain full control over the provisioning process we may need to select the Site Provisioning Provider approach.

You can find some sample codes I used in demo from this location.

Sunday, June 15, 2014

Set result source and item display template programmatically to SharePoint 2013 search ResultScriptWebPart

Sometimes we need to programmatically set search result source and a custom item display template to a search web part.

Following is a sample code segment to do the needful

  1. //Get the instance of web part
  2. var homePage = web.GetFile("SitePages/Home.aspx");
  3. using (var webPartManager = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared))
  4. {
  5. var recentDocs = webPartManager.WebParts.Cast<WebPart>().FirstOrDefault
  6.         (wp => wp.Title.Equals("Recent Documents")) as ResultScriptWebPart;
  7. var querySettings = new DataProviderScriptWebPart
  8.         {
  9.            PropertiesJson = recentDocs.DataProviderJSON
  10.         };
  11.  
  12. //Get the search service application proxy
  13. var settingsProxy = SPFarm.Local.ServiceProxies.GetValue
  14.         <SearchQueryAndSiteSettingsServiceProxy>();
  15. var searchProxy = settingsProxy.ApplicationProxies.GetValue
  16.         <SearchServiceApplicationProxy>("Search Service Application");
  17. var siteOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, web);
  18.  
  19. //Set the result source. I set the default for demonstration
  20. var siteResultSource = searchProxy.GetResultSourceByName("Local SharePoint Results", siteOwner);
  21.  
  22.  
  23. querySettings.Properties["SourceName"] = siteResultSource.Name;
  24. querySettings.Properties["SourceID"] = siteResultSource.Id;
  25. querySettings.Properties["SourceLevel"] = siteOwner.Level;
  26.  
  27.  
  28. //Set the item display template
  29. recentDocs.ItemTemplateId = "~sitecollection/_catalogs/masterpage/Display Templates/Search/Item_Contoso.js";
  30. recentDocs.DataProviderJSON = querySettings.PropertiesJson;
  31.  
  32. webPartManager.SaveChanges(recentDocs);
  33. }
  34. homePage.Update();

That’s all we need to do.