Office 365 APIs & Its Integration with Andriod, iOS etc

Link Posted on Updated on

Sharepointers,

For the last couple of months I am playing a lot with Office 365 APIs. On my last blog post I have shared about Office365 Video APIs and its REST based games. This time I have something bit broader or some what a high level overview about the new API functionalities.

Please click here to read from my article on organizational blog.

Office 365 Video & Office 365 APIs

Posted on Updated on

SharePointers & Other O365 Folks,

Recently MSFT has released its video streaming service for Office 365, that is basically an intranet site for video portal . Just for curiosity, I tried available preview version from my Office 365 and happily created multiple channels and uploaded videos into it. I liked it very much because this can be used in many organization to publish their corporate videos and share with their employees. More interestingly, its backed by Azure Media services, so that we can leverage the features like video encryption, HLS (http live streaming) and many more. So after making my hands dirty with configuration of this new thingy, I was excited to extend this service to other client application. For this purpose MSFT have released  a set APIs which enable developers to manipulate their data from any client applications . Say, Android Apps ,IOS Apps & ASP.NET applications etc. A bunch of sample code is available on MSDN for office 365 API integration with Mail, Files(OneDrive), Contacts etc .

But as of now, this available sample codes does not cover usage of Office 365  Video REST API, which is in preview. So I thought to share information about usage of Video REST API. In this post I am not providing  huge blocks of code to explain contrary to what I have done on my previous posts, rather I am using POSTMAN client to show the video REST API functionality.

Initial steps to do

  1. Login to Office 365 Portal ( use admin privileges if you need to configure or create channel for video)
  2. Navigate to the video portal and upload videos into your channel or to default community channel.

videodrag

movie

Once the video is uploaded, try to view video from portal so that we can grab the channelID and videoID from the browser URL for the future REST API calls. The below URL highlights the channelID and videoID respectively.

/portals/hub/_layouts/15/PointPublishing.aspx?app=video&p=p&chid=a4dc2759-a618-4bc8-bd94-edd12294c0d7&vid=1d956f3a-e4e0-4eb0-877d-cbb798423abd

For streaming an encrypted video from Office 365(Azure Media Services) to our client application,  we require 2 stuffs – 1. Video playback URL  2. Access token for decryption of video.

Install and open POSTMAN Client – I prefer CHROME for this because we can utilize chrome app of POSTMAN. (Make sure you open a tab for POSTMAN on the same browser instance of chrome where video portal is open, so that authentication will work without any extra effort)

  1. On the POSTMAN app , paste URL in the below format for GET the video playback URL

{VideoPortalURL}/_api/VideoService/Channels(‘{channelId}’)/Videos(‘{videoId}’)/GetPlaybackUrl(‘{streamingFormatType}’)

For my video service , playback video request URL is like below, I have used StreamingFormatType as “1” which is

for “MPEG-DASH” format. if you want use HLS use “0” , so that it will require extra access token to decrypt

https://spsparta.sharepoint.com/portals/hub/_api/VideoService/Channels(‘{a4dc2759-a618-4bc8-bd94-edd12294c0d7}’)/Videos(‘{1d956f90-e4e0-4eb0-877d-cbb798423abd}’)/GetPlaybackUrl(‘1’)

Result will look like this

playbackURL

2.  For getting the decryption access token, again do a GET request in the below format

{VideoPortalURL}/_api/VideoService/Channels(‘{channelId}’)/Videos(‘{videoId}’)/GetStreamingKeyAccessToken

The token request URL for my video is like below

https://spsparta.sharepoint.com/portals/hub/_api/VideoService/Channels(‘{a4dc2759-a618-4bc8-bd94-edd12294c0d7}’)/Videos(‘{1d956f3a-e4ea-4eb0-877d-cbb798423abd}’)/GetStreamingKeyToken

token

Now we have both PlaybackURL and decryption token to stream the video from Office 365 (Azure media service). I used http://amsplayer.azurewebsites.net/ to test my video streaming or else we can directly use IFRAME (see below) or video tag to stream the video.  Click here to open my video in amsplayer -(UPDATE : accesstoken is expired now, if any viewers need to see it functioning Kindly do the request so can update the token.)


<iframe src="//aka.ms/azuremediaplayeriframe?url=%2F%2Fcdn-cvprhkn01m01.streaming.mediaservices.windows.net%2Ff30630fa-4e1d-40bf-bdc4-fb20fd70e875%2F19074820-245b-412e-95d7-96be9693c352.ism%2FManifest&protection=playready&token=Bearer%3Durn%253amicrosoft%253aazure%253amediaservices%253acontentkeyidentifier%3D057c9a97-5d2d-4744-bfe1-d9bb30737b47%26urn%253amicrosoft%253aazure%253amediaservices%253akeyacquisitionhostname%3Dcvprhkn01m01.keydelivery.mediaservices.windows.net%26http%253a%252f%252fschemas.microsoft.com%252faccesscontrolservice%252f2010%252f07%252fclaims%252fidentityprovider%3Dhttps%253a%252f%252fnimbuslkgglobacs.accesscontrol.windows.net%26urn%253aServiceAccessible%3Dservice%26Audience%3Durn%253aNimbus%26ExpiresOn%3D1433202410%26Issuer%3Dhttps%253a%252f%252fnimbuslkgglobacs.accesscontrol.windows.net%252f%26HMACSHA256%3D2ji3D8SXf5OORXaZSxIbtpvAQr2h3r%252fGBTz1Nd6Wh1c%253d&autoplay=false" name="azuremediaplayer" scrolling="no" frameborder="no" align="center" height="280px" width="500px" allowfullscreen></iframe>

Note : Office 365 Video API is still in preview, so kindly keep in mind that MSFT
may change the procedures in future. Also GUIDs & Access tokens used in this post is scrambled because of security concerns.

Hope you enjoyed the post, Feel free to ask your queries.

SharePoint 2013 – Product level issue(s) as on MARCH 2013 CU, SP1, MAY 2014 CU , JULY 2014 CU & September 2014 CU

Posted on Updated on

Sharepointers,

Recently, I have been haunted(/haunting) with few SharePoint 2013 CU / hotfix issues. No idea why MSFT release bugs along with updates  :) , Kidding…!.

So lets start with these bugs / issues , reproduction & fixes available etc.

  • Issue #1 : User Context is redirected to Pages Library root while user tries to create  a page inside a inner folder of the Pages library

This issue very apprehensive because when a user tries to create a page inside a folder or n-level inner folder , which redirects him to root of pages library.

This issue started from Service Pack 1(15.0. 4569. 1506) or precisely from May 2014 CU. But no fix has been provided by MSFT yet. Waiting for November 2014 CU to fix this issue.  On a support case with MSFT , I got a feedback that it will get fixed on Nov 2014 CU.

[Update as on 14-Nov-2014] : No Luck, Issue still persists with November 2014 CU. Waiting for next update from SharePoint Product Group.

I tried till OCT 2014 hot fix from MSFT to validate whether this issue solved or not, but no hope.

Bad news – No fix available as of  10-november-2014.

  • Issue #2 : “Sorry something went wrong” error while user clicks on “Edit properties” or “View properties” button for a page.

This issue happens for pages created from a OOB CT based out of “Article Page”. So when a user creates such a page and before its check-in, if he tries to View/Edit properties then a error page displays with message –   “Sorry something went wrong”.

The issue is reproducible in SP1 (15.0. 4569. 1506)  and above versions in plain vanilla sharepoint environments (i.e. without any customizations) till July 2014 CU.

Good news – This issue got fixed on September 2014 CU.

  • Issue #3 : Mandatory validation not working for Publishing HTML fields on list or library.

Reproduction : Create a list or library which have a Publishing HTML field and mark this field as Mandatory. Try to add data inside this list without entering data inside this publishing HTML field. The system will allow this data to get entered, discarding the validation we provided.

This issue started from March 2013 CU – But I saw this got fixed on Service pack 1 and on higher updates.

  • Issue #4 : On edit mode of a publishing page, Managed Metadata fields throws a JavaScript error “There was error processing this request”

This issue started from March 2013 CU – But I saw this got fixed on Service pack 1 and on higher updates.

As a whole, Issue #1 & Issue#2 are most annoying and out of this, Issue#1 is still a pending backlog from MSFT but Issue#2 is fixed on September 2014 CU.

Translating Text (NOT regular files & sites) using SharePoint 2013 Machine Translation Service Application

Posted on Updated on

Sharepointers,

Recently I came across a very simple requirement from our customer to create a ‘Plain text translation utility Webpart’ on our SharePoint 2013 portal. Presently we have components related to document translation, which is sole purpose of SP 2013 Machine Translation Service (MTS) Application.By default, all object models functionality of MTS on SharePoint 2013 (CSOM, SOM, JSOM) has support to ‘Translate’ the documents. While searching on internet we will come across many articles or documentations explaining the document translation (one good article from MSDN is over here). But there is no straight forward API function to translate the TEXT data, which can provide functionality similar to Google or Bing Text Translation. 

Of course, we can tweak the existing API functions to achieve this functionality.  So below mentioned code explains how we can achieve this.

//Getting the Source text from input control.
            string somestring = txtSource.Text;

            //Retreiving the Service Context of the Site
            SPServiceContext sc = SPServiceContext.GetContext(new SPSite("http://server/sites/MTS/"));

            //Converting the input text to byte array
            byte[] inputByte = Encoding.ASCII.GetBytes(somestring);

            //Creating Synchronised translation job with target language as SPANISH
            SyncTranslator job = new SyncTranslator(sc, CultureInfo.GetCultureInfo("es"));

            byte[] outputByte = null; //byte array variable to get the output.

            //Translate using the "Translate" function of Sync.Job with input text's byte array.
            //Provided a dummy file extension type as "txt" - Here we are not specifying any output file path.
            TranslationItemInfo itemInfo = job.Translate(inputByte, out outputByte, "txt");

            //Converting the translated byte[] to text using UTF8 encoding.
            string result = Encoding.UTF8.GetString(outputByte);

            txtTarget.Text = result; // providing the result to the output text control.

So the trick on the above mentioned code is to use the overload for translating byte[] of the “Translate” function under Translation Sync.Job, then utilize the translated output byte[] to display the result after proper encoding.(UTF8 in this sample) to the text.

The utility webpart created using above code will look like this.

Formatting Date, Number Data on BCS OOB Business Data List Webpart

Posted on Updated on

SharePointers,

Recently I came across an interesting issue/requirement with our Business Data List WebPart. The issue is “Data fetched from an External datasource via  BCS (External Content Type) need to be displayed on OOB Business DataList Webpart with proper formatting and  sorting”. Here, By formatting it means that numbers should be displayed like XXX,XXX or X,XXX and date should display in MM/DD/YYYY format without time part.

From the first look of it, we can easily acheive this by doing  a formatting from Database side. Means for a date data it can be done like

SELECT CONVERT(varchar(10),GETDATE(),3) + ' ' + CONVERT(varchar(10),GETDATE(),8)

and for numbers it can be done like

CONVERT(varchar(50), CAST(1112 AS money), 1)

Both the above approaches will work perfectly to solve the “formatting” requirement but fails for “sorting”. Because in both cases data is converted to type “string” so sorting will fails to work.

The same issue will occur if we try to solve it in any middle tier like WCF or .NET BCS Provider

In the above scenario, to accomplish the requirement of sorting & formatting we dont require to “CONVERT” the data from its base type to “string”. Let the data (date or number) come to SharePoint in its base type(DateTime or INT, DECIMAL etc). From the place where it display we can change its formatting even if it is an Out-Of-Box Business Data List Webpart”.

Yes. We can do it with the help normal “XSLT” functions WITHOUT opening the SharePoint Designer”

Follow the below mentioned steps to crack it out

  • Configure the OOB Business Data List Webpart with our External Content Type(ECT) and View. This is a regular step to display External Data. After this step we can see the data listing without the formatting.
  • In this step we need to take the existing XSL styles of the data listing webpart. For this we need to do the “Edit Webpart” and from the Webpart properties toolbox find the “XSL Editor” button. Click on it, it will pop up the XSL style. Copy the whole XSL and paste it to a Visual Studio instance(or any other good editor).
  • Find the XSL parameter which we need to format. Assume its a number which need to formatted like “#,###”. So here we need apply the XSLT function, “format-number“.

<xsl:value-of select="format-number(@AmountUSD, '#,###')" />

For the date formatting we can use like this

 <xsl:value-of select="ddwrt:FormatDateTime(@ActivityDate, 1033, 'MM/dd/yyyy')" />

  • Take the edited XSL & paste it back to the XSL Editor box on the Webpart properties toolbox. Save the XSL and Press OK on the webpart toolbox. You can see the formatted data

Note :  By  this approach it will perfectly format listing data on the BCS Out of the box Business Data list web part without doing any custom scripts or code, But the data on the filter drop downs will not get formatted.

Organization/Hierarchy Chart on SharePoint (using jquery, Javascipt-CSOM)

Posted on Updated on

Hi developers,

This time I have a very interesting stuff for you guys. Few days back I got a tricky requirement from one of my customers , its about populating their organizational structure dynamically on their  SharePoint Intranet site without any server side components /Code. Means – there will be a SharePoint list from where data will  be pulled and on a Webpart(CEWP or OOB WP) the hierarchy need to be displayed. Fortunately within few hours I was able to integrate 2-3 things with some javascript / jquery code to accomplish this requirement.  Things require to cook out are

  • jQuery
  • jQuery OrgChart PlugIn  – Kindly read the technical artifacts of jQuery OrgChart from this location.
  • Content Editor WebPart
  • SharePoint Javascript CSOM
  • a SharePoint list
  • jQuery Balloon Plug In – If need to show any additional data

The scenario, I am going to demonstrate here is  to create a corporate organizational structure. For example, CEO on the top then COO, CFO, CTO  then Excutive VPs, AVPs then comes Directors,Managers  after that core execution team.

So, Here we start.

1. Create a custom SharePoint list having  columns like Title, Manager, Designation .Enter some logical details as mentioned below.

List data for populating Org Chart

 

 

 

 

 

 

 

 

 

2. Download and place Jquery & jQuery OrgChart plug-in files into the hive’s _layouts folder(see image below).Note : When we  are going through a solution deployment approach we need to place these files inside SP Project to package it to a WSP file.  Here we are directly copying files to _layouts folder just for the sake of demo. If needed you can place the jQuery Balloon file too.

jqueryPlugInFiles

 

 

 

 

 

 

3.Creating the Content Editor WebPart / Script editor WP – Script source file. Save the below mentioned code to a txt file and upload it to the SiteAssets Library. Give the path of the file to CEWP  like  “/SiteAssets/ScriptstxtFile.txt” or directly use this script to your client component.

<link rel="stylesheet" href="_layouts/jquery.orgchart.css" /></pre>
<link rel="stylesheet" href="_layouts/jquery-ui-1.10.3.custom.css" />

<script src="_layouts/jquery-1.9.1.js"></script>
<script src="_layouts/jquery-ui-1.10.3.custom.js"></script>
<script src="_layouts/jquery.orgchart.js"></script>
<script src="_layouts/jquery.balloon.js"></script>

<!--This div will be populated with the <ul><li> structure from the SCOM returned objects-->
<div id="left">
</div>
<style>
 div.node.bladerunner {
 background-color: #a4a0d9 !important;
 }

div.node.replicant {
 background-color: #d9ada0 !important;
 }

div.node.deceased {
 background-color: #d9d2a0 !important;
 text-decoration: line-through;
 }

div.node.retired {
 background-color: #d9c0a0 !important;
 text-decoration: line-through;
 }
</style>

<!--Main Org Structure will pupulate under this DIV-->
<div id="content">
 <div id="main">
 </div>
</div>

<script type="text/javascript">

//loading SharePoint Javascript SCOM
 ExecuteOrDelayUntilScriptLoaded(loadStructure, "sp.js");

//calling the executing function
 function loadStructure() {

//Querying SP using SCOM
 var context = new SP.ClientContext.get_current();
 var web = context.get_web();
 var list = web.get_lists().getByTitle("Employee"); //Employee is SP List containing heirarchy data of the Orgnization
 var viewXml = '<View><RowLimit>1200</RowLimit></View>';
 var query = new SP.CamlQuery();
 query.set_viewXml(viewXml);
 this.items = list.getItems(query);
 context.load(items, 'Include(Title, Manager,Designation)');
 context.add_requestSucceeded(onLoaded);
 context.add_requestFailed(onFailure);
 context.executeQueryAsync();

function onLoaded() {
 //Adding SCOM return objects to an array
 var tasksEntries = [];
 var itemsCount = items.get_count();
 for (i = 0; i < itemsCount; i++) {
 var item = items.itemAt(i);
 var taskEntry = item.get_fieldValues();
 tasksEntries.push(taskEntry);
 }
 //array's filter function wont work in IE8. Hence GetChildArrayObjects
 //var topHead = tasksEntries.filter(function (item) { return (item.Manager == null) });
 var topHead = GetChildArrayObjects(tasksEntries, null);

/////Logic to create <ul><li>....</li></ul> for jQuery orgChart -- ####Starts Here
 var headName = topHead[0].Title;

var title = topHead[0].Designation + ", Manager :" + topHead[0].Manager;

var listString = "<ul id='organisation'><li class='hide' title='" + headName + "'>" + headName;

//Calling the recursive function.getChildNodes
 var childliststring = getChildNodes(tasksEntries, headName, listString);

listString = childliststring + "</li></ul>";

var divForList = document.getElementById('left');
 divForList.innerHTML = listString;
 /////Logic to create <ul><li>....</li></ul> for jQuery orgChart -- ####Ends Here

//Populating OrgChart using Jquery OrgChart Plug in - Basically it reads Created <ul><li> list named 'organisation' and writes a TABLE - DIV structure.
 $("#organisation").orgChart({ container: $("#main"), nodeClicked: onChartNodeClicked });

//enabling balloon for each orgchart block
 for (var i = 0; i < tasksEntries.length; i++) {

$("div[title=\"" + tasksEntries[i].Title + "\"]").balloon({
 contents: '<img src ="/Images1/_t/images_jpg.jpg"/></br><ul><li> Designation :' + tasksEntries[i].Designation + '</li><li>Phone# : 123-234-1233</li></ul>'

});

}

}
 //Handled event for node clicked.
 function onChartNodeClicked(node) {
 //If we need to do anything specific when clicking a node.
 }
 function onFailure() {
 alert('script failed');
 }
 }

 //Recursive function to create <ul><li> organization structure.
 function getChildNodes(tasksEntries, headName, liststring) {

//var childs = tasksEntries.filter(function (item) { return (item.Manager == headName) });
 var childs = GetChildArrayObjects(tasksEntries, headName);

if (childs.length > 0) {

liststring = liststring + "<ul>";
 for (var cnt = 0; cnt < childs.length; cnt++) {
 var head = childs[cnt].Title;
 var title = childs[cnt].Designation + ", Manager :" + childs[cnt].Manager;
 liststring = liststring + "<li class='bladerunner' title='" + head + "'>" + head;
 liststring = getChildNodes(tasksEntries, head, liststring);
 liststring = liststring + "</li>";
 }

liststring = liststring + "</ul>";
 }

return liststring;
 }

//Alternative function for .filter function to query child objects for a parent in an array
 function GetChildArrayObjects(items, manager) {

var newArray = [];
 for (var i = 0; i < items.length; i++) {
 var item = items[i];
 if (item.Manager == manager) {
 newArray.push(item);
 }
 }

return newArray;
 }

</script>

JQuery OrgChart basically needs a <ul><li> (unordered list) format for populating the Org-Chart. So I am querying the SP List using the SCOM(javascript) and using a recursive function (getChildNodes) the <ul><li> structure is created. After loading this <ul><li> structure I call the jquery orgchart function to populate the hierarchy on the other <div>

The main checkpoints on the above script are :

  • loadStructure() – JS Function uses SharePoint JS SCOM to Query the list to get the Parent-Child Hierarchy.
  • GetChildArrayObjects() – its an alternative to .filter JS function since this is not supported on IE8.
  • getChildNodes – Recursive function mentioned above – Which basically structures the unordered list.(see the <ul> mentioned on image below)
  • $(“#organisation”).orgChart({ container: $(“#main”), nodeClicked: onChartNodeClicked });   – This line of  jQuery code in the above script actually reads the <ul><oli> and generate the OrgChart.  While you skim the above code, you will be able to see a <ul> with ID as ‘organisation’ created which is read and org chart is populated to a <DIV> ‘main’
  • After creating the orgChart, I am iterating through the <DIV> of the OrgChart block according to its ID to enable the ballon

//enabling balloon for each orgchart block
for (var i = 0; i < tasksEntries.length; i++) {

$("div[title=\"" + tasksEntries[i].Title + "\"]").balloon({
contents: '<img src ="/Images1/_t/images_jpg.jpg"/></br><ul><li> Designation :' + tasksEntries[i].Designation + '</li><li>Phone# : 123-234-1233</li></ul>'

});

Finally the OrgChart is populated as displayed below.  You can see a <ul><li> list on the top, which can made to visible=false to the <DIV> with ID ‘left’ on the above mentioned script, displayed only for testing purpose.

orgChart

Hope you have enjoyed this article, Kindly let me know if  there is any issues .


	

Custom XML mapping of content control in a SharePoint Document Library Template

Posted on Updated on

Hi Developers,

After a long time ( was in a busy schedule of establishing family after my marriage :) ) I thought I will post this article for setting the XML mapping  of content control  in a Word document template  for SharePoint Document Library. To be frank, in most of the cases we are / will be  using QuickParts Add-in to add the content controls  which are already mapped with SharePoint ContentType fields. But in this article I will be explaining how to set up a document template for a document library without touching the QuickParts Add- in. Sometimes this will be helpful to the developers who are programmatic-ally/dynamically  creating  document templates or content controls to document templates.  To make this article in one line, its about setting XPath, Prefix Mapping for content controls using SetMapping function of XMLMapping property of content control, like contentControl.XMLMapping.SetMapping(Xpath,PrefixMapping).

These are things that  you should have handy with you before starting this exercise.

  1. A  Document Content Type with some site columns referred inside – Say, we will name it as “ExpenseContentType” that have  2 site columns (SC_ExpenseName, SC_ExpenseCount )
  2. A Document Library created which have content type that is mentioned on the above step( Step 1) – Say , ExpenseDocumentLibrary.
  3. Word Content Control Tool Kit – Download this tool kit.  This is just for the analysis purpose of the template or to understand what is happening behind the scene.
  4. Visual Studio – Just in case if  you need to code the logic for XML mapping. (Code is embedded on the bottom of the post)

So, Lets start from the document library (ExpenseDocumentLibrary)

Step 1 . Go the document library setting –> ContentType (ExpenseContentType) –> Advanced Settings

Here on the Advanced setting page of the Document library Content Type, Click on the Edit Template link(see image below) . This will open a blank document template on the MS Word . Save this locally on your machine with any user friendly name , Say ExpenseTemplate.docx

Edit Template from the Document ContentType of the document library

Step 2. For analysis, open the locally saved blank template using the Word Content Control toolkit. We can see the content type fields on the custom XML parts of the document. This means the ContentType related data like Fields etc are there in this document in XML(XSD) format.  Since its a blank document , there is no matter in the Content Controls section.

Blank document

Step 3. Let us add some content controls to this document template. For that, Open the word document using MS Word and from Developer tab add 1 or 2 plain text content controls to the document as if  it resemble a template. (See image below). Name the content controls exactly as the Site Columns name in ContentType. Means, name Expense Name content control as “SC_ExpenseName”.

Save this document after the adding the controls.

Step 4 . Re-Open the document in the Word Content Control Tool Kit. Now we can observe that on the content controls section it showing the control entries without having its XPath set with ContentType Fields inside the file. (See the Image below). Basically XPath and Prefix mapping of the Custom XML parts shown on the right pane for the each field need to be mapped with content control.

Step 5. In this step we will set the mapping between the content controls and ContentType fields. Actually we can set mapping using Word Content Control Tool kit itself , but it will become a manual process. Better we will do it “programmatic-ally”  :) .

For doing this, I am creating  a Word Add-In project  in Visual Studio . So open a Visual Studio Instance –> New Project –> Word Add – In (see image below).

Give any user friendly name to the project.  After that , Add a “Ribbon” into this  Add- in project (Right Click on Project –> Add –>  New Item –> Ribbon (see image below))

Again, give a user friendly name to the ribbon. On the visual designer of the ribbon add a button(label it as “Set Mapping”) and on the click event of  button , we will write some code as shown below .

      ///
<summary> /// Click event of the Set Mapping button
 /// </summary>
        ///
        ///
        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            //Accessing the active document
            Document document = Globals.ThisAddIn.Application.ActiveDocument;
            string nsURI = string.Empty;

            //retreving the content control collection of the active document.
            ContentControls contentControls = document.ContentControls;

            //Looping through the content Control collection.
            foreach (ContentControl cntntCtrl in contentControls)
            {

                var ctrlTitle = cntntCtrl.Title;
                //Setting the XPath for each control. this is under a condition that name of the Content type site column /field
                // and content control name & tag is exactly same.
                string xpath = "/ns0:properties[1]/documentManagement[1]/ns1:" + ctrlTitle + "[1]";

                //Private function to get the NameSpace URI of the content type field
                nsURI = GetXSDNameSpaceURI(document, cntntCtrl);

                //Mapping the content control.
                bool isMapped = cntntCtrl.XMLMapping.SetMapping("/ns0:properties[1]/documentManagement[1]/ns1:" + ctrlTitle + "[1]", "xmlns:ns0='http://schemas.microsoft.com/office/2006/metadata/properties' xmlns:ns1='" + nsURI + "'", null);

                if (isMapped == true)
                { MessageBox.Show("Mapping successfully done...!"); }
                else
                { MessageBox.Show("Error in XML Mapping"); }

            }

        }

        ///
<summary> /// private function to get the namespace URI of the content type.
 /// </summary>
        ///
        ///
        ///
        private string GetXSDNameSpaceURI(Document document, ContentControl control)
        {
            string nsURI = string.Empty;
            CustomXMLParts xmlParts = document.CustomXMLParts.SelectByNamespace("http://schemas.microsoft.com/office/2006/metadata/properties");
            foreach (CustomXMLPart xmlPart in xmlParts)
            {
                XmlDocument XDoc = new XmlDocument();
                XDoc.LoadXml(xmlPart.XML);
                XmlNodeList result = XDoc.GetElementsByTagName(control.Title);
                nsURI = result[0].NamespaceURI;
                break;
            }

            return nsURI;
        }

Build the project and press F5. This will open a default word document. Close that document and open our document library template where we have add content control. Find the ribbon that we have created on the opened document and press the button “Set mapping”. This will set the XPath mapping for each content control and throw a message box saying “Mapping successfully done…!”.(see image below)

Now I will explain what actually the above code does. Basically it iterates through the content controls collection and by using each content control’s title its creating an “XPath” string and “Prefix mapping” using the content type namespace URI . The key player is SetMapping Function of the content control’s XMLMapping property. This function is used to set the mapping for the content control. The SetMapping function can be called on the event after the control adding to make it more clean. But since this is a POC we will use iteration logic. The entire article is based on the SetMapping function to make link between content control and content type.

Now just open the document in the Word Content Control toolkit and see the XPath set against each content control. (see image below)

This is the time to upload this document template back into Sharepoint. Go to the Advanced settings of the Document library content type and upload the template using “upload a new document template”. After the uploading is over try adding document files which have data inserted. You can see content control data getting binded with content type columns within the document library.

I hope you enjoyed/ understood this article. Thanks for readings. Comments are invited.