Skip to content

Related items field – how to access it programmatically by code?

When paying with new Workflow tasks I have noticed that they now do contain the new field of type “related items”.

This is an awesome field that allows you to add links to any items from your site collection.

By default this field exists in a new content type called Workflow Task (SharePoint 2013).

So what happens when a SharePoint 2013 workflow creates a task for an item? It fills a link to an original item that workflow has to do with in this field.

Her is how it looks like.

If you press Add related item, then

You see a nice dialog that allows you to open any item from your site collection.

Once a customer asked me to do the following logic. Once a task has been updated by someone, add comments and the guy who actually implemented the task to the original item.

So I came to a problem – how do I actually read the related items and find out what is inside?

When I looked at the fields I figured out it is actually a multiline text field

So when I wrote a short program that actually gets the value and I was surprised to see it is actually JSON!

Or in JSON.

So basically you need to add a simple parser that will read the values.

I have tried a parser which I found out in ASP.NET MVC4 but apparently it needed a couple of DLLS to be installed which we could not figure out, so I have used a NewtonSoft JSON which was added with a simple nuget package.

So the code of reading the values from related items is

using (ClientContext ctx = GetAuthenticatedContext())


TraceHelper.TraceInformation(ConsoleColor.Magenta, “reading related items”);

ctx.Load(ctx.Web, x=>x.ServerRelativeUrl);


var workflowTasksListUrl = UrlUtility.CombineUrl(ctx.Web.ServerRelativeUrl, Lists.WorkflowTasks.GetListUrl());

var workflowTasksLIst = ctx.Web.GetList(workflowTasksListUrl);

// this is just for demo, this is not the best code to work with sharpeoint items

var items = workflowTasksLIst.GetItems(

new CamlQuery()




string relatedItemsString = (string)items[0][BuiltInInternalFieldNames.RelatedItems];

dynamic decodedRelatedItems = JsonConvert.DeserializeObject(relatedItemsString);

foreach (var item in decodedRelatedItems)


int itemId = int.Parse(item.ItemId.ToString());

var listId = new Guid(string.Format(“{{{0}}}”, item.ListId.ToString()));

var webId = new Guid(string.Format(“{{{0}}}”, item.WebId.ToString()));

Console.WriteLine(“Found an item from web {0}, list {1}, itemid:{2}”,webId,listId,itemId);


And can be found in a demo app called “DemoAp.Reader”.

Before you can use it run DemoApp.AssetBuilder that uses spmeta2 for provisioning and builds a structure.

Source code can be found at


Creating SharePoint solutions with TypeScript.

crossposted from



This post explains how to use TypeScript in your apps for SharePoint. It assumes that you are familiar with SharePoint-hosted apps and JavaScript.

Great thanks for Jim Crowley from Microsoft to make the text awesome.




SharePoint-hosted apps are written in JavaScript, which is often hard to debug. It also does not provide many of the advantages of a strongly typed language. Luckily, Anders Hejlsberg has created a superset of JavaScript called TypeScript. This language provides strong types, interfaces, and extensible classes that bring common object oriented programming concepts and techniques into JavaScript development.


The TypeScript compiler produces a JavaScript file from a source file with a .ts extension. You can think of TypeScript as your source code and JavaScript as analogous to binary code generated by a compiler.


The compiler also produces a map file that makes it possible for you to debug TypeScript code. This file maps lines of TypeScript with the lines of JavaScript produced by the compiler. The TypeScript debugger works as long as you include your TypeScript and map files in the same location as your JavaScript file.


You can easily install TypeScript as a plugin to your installation of Visual Studio 2012 and Visual Studio 2013 from the TypeScript official site (


Some JavaScript libraries, such as JQuery and the SharePoint JavaScript libraries, might be a little difficult to use with TypeScript. Since TypeScript is strongly typed, it will complain about the classes and functions in these libraries unless you have corresponding TypeScript definitions for them. The DefinitelyTyped project addresses this issue by putting a lot of these definitions on NuGet ( You will find many libraries there, including ones for Knockout and JQuery. One library is called SharePoint.TypeScript.DefinitelyTyped. You can install it from NuGet, but you should also take a look at the project on CodePlex (, which contains samples for lots of common tasks, like CSR rendering, autofills, mQuery, forms with tabs, custom fields, search, user profiles, social capabilities, and more. 

Using TypeScript in your project


It is very simple to include TypeScript in your SharePoint-hosted app project. Just follow these steps.


1.      Install TypeScript to Visual Studio 2012 or Visual Studio 2013 from the official site.

2.      Create a new Sharepoint-hosted app.

3.      Now you need to do a little trick to make sure that Visual Studio knows how to compile TypeScript in the context of an app for SharePoint.

a.      Right-click the project name and select Unload Project.

b.      Right-click the project name and select Edit <your project name>.csproj.

c.      Add these lines before the last closing <Project> tag. 





<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" />


1.      Right-click the project name and select Reload Project.

2.      Now you will see the TypeScript tab in the project properties.



4.      Now you can add the TypeScript definitions. Right-click the project name and select Manage Nuget Packages. Search online for “sharePoint.Typescript.” Install the sharePoint.Typescript.DefinitelyTyped package.


6.      Also search for “jquery.typescript” and install the jquery.Typescript.DefinitelyTyped package.

7.      Rename App.js to App_1.js so that we can use it later. Create a new TypeScript file called App.ts. You’ll need to search for the Typescript File type when you add this new item. Both of these files should be in the Scripts directory in Solution Explorer. You can also find this template in the Web category of templates.



8.      Copy the contents of App_1.js to App.ts.

9.      Add these lines to the top of the App.ts file:

///<reference path="typings/sharepoint/SharePoint.d.ts" />
///<reference path="typings/jquery/jquery.d.ts" />

This will allow us to use both JQuery and SharePoint definitions.

10.   Build the project.

11.   In Solution Explorer press the Show all files button. The Scripts directory will include new App.js and files. Right-click both file names and select Include In Project. Make sure that each file has a deployment type of ElementFile

12.   Now we have turned our Javascript Sharepoint-hosted app to a Typescript Sharepoint hosted app.


Adding the People Picker control with TypeScript


Now let’s see how to do a basic task. We’ll update an existing MSDN sample app ( that adds a client-side People Picker control to an app for SharePoint so that it uses TypeScript. You can create this sample by updating the SharePoint-hosted app that we created in the last section.


1.      Move these two lines from the App.ts file into the _references.js file in the Scripts directory:

///<reference path="typings/sharepoint/SharePoint.d.ts" />
///<reference path="typings/jquery/jquery.d.ts" />

2.      Create a new web page inside the Pages directory of your project. Name it Default1.aspx.

3.      Open the AppManifest.xml file and make this new page the Start page of your app. You’ll find this setting under the General tab.

4.      Create a new TypeScript file inside the Scripts directory of your project. Name it App1.ts.

5.      Build the project.

6.      In Solution Explorer press the Show all files button. The Scripts directory will include new App1.js and files. Right-click both file names and select Include In Project. Make sure that each file has a deployment type of ElementFile.

7.      Find this tag in your Default1.aspx file:

<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">

Copy this lines under that tag:

 <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="../Scripts/App1.js"></script>
Note – the actual javascript version may differ on your computer, as the Nuget package always gets the latest jquery version.

8.      Close the tag


9.      Replace the contents of the PlaceHolderMain section with these lines:

<%– The markup and script in the following Content element will be placed in the <body> of the page –%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<SharePoint:ScriptLink name="clienttemplates.js" runat="server" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink name="clientforms.js" runat="server" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink name="clientpeoplepicker.js" runat="server" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink name="autofill.js" runat="server" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink name="sp.js" runat="server" LoadAfterUI="true" Localizable="false" />

<SharePoint:ScriptLink runat="server" Name="mQuery.js" />

<div id="peoplePickerDiv"></div>

<h1>User info:</h1>
<p id="resolvedUsers"></p>
<h1>User keys:</h1>
<p id="userKeys"></p>


Notice that we have added a reference to MQuery. MQuery is a JavaScript JQuery subset library built into SharePoint. It is more limited in scope than JQuery, but it contains the awesome m$.ready() function, which gives us a good entry point for our code after all of the SharePoint stuff has been loaded.


9.      Add this TypeScript code to the App1.ts file:


module App1 {

    m$.ready(() => {




    //Load the people picker

    function loadPeoplePicker(peoplePickerElementId: string) {

        var schema: ISPClientPeoplePickerSchema = {

            PrincipalAccountType: ‘User,DL,SecGroup,SPGroup’,

            SearchPrincipalSource: 15,

            ResolvePrincipalSource: 15,

            AllowMultipleValues: true,

            MaximumEntitySuggestions :50,

            Width: 280,


            OnUserResolvedClientScript: onUserResolvedClientScript



        SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema);



    function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) {


        var keys = "";


        // Get information about all users.

        var userInfo = ”;

        for (var i = 0; i < users.length; i++) {

            var user = users[i];

            keys += user.Key + ",";

            for (var userProperty in user) {

                userInfo += userProperty + ‘:  ‘ + user[userProperty] + ‘<br>’;





        // Get user keys.






The code has the same length as in the MSDN article, but here we have a strongly typed schema for ClientPicker properties and we can easily add other properties. In the original JavaScript model, there is a dictionary, and you need to know the keys. Here we have strong type checking and IntelliSense, so the developer experience is dramatically better.




Press F5 to test your app. Here is what the app looks like when it runs.






You can find a more sophisticated sample at the SharePoint Typescript page on CodePlex ( This sample also gets data from user profile services. Here is what it looks like:


We strongly recommend that you also try this sample.


TypeScript is a very interesting and promising solution for using JavaScript with SharePoint. You can use Typescript in full trust solutions that include JavaScript.


You can find the source code for the solution used in this article on GitHub (



How to debug xslt transformations

aka How to display source xml in xslt.


Today we have been looking for the methodology of working with xslt. The first step was to add some line so the xslt also gives us the source xml which we could use.


Now we could not find it for 10  minutes soI am posting it here


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xmp><xsl:copy-of select="*"/></xmp>



How to use TypeScript for making strongly typed data in SharePoint hosted apps?

As a developer I hate loosely typed data. When I  have started playing with Sharepoint Hosted apps and had to use JavaScript, one of my pain points was the common SharePoint pain – loosely typed data. I mean, that you have you SP.ListItem, and you cannot check if you did not make a misprint, no one tells you that is is  better to use listitem.get_item(“yourmegafield”) instead of listitem[“yourmegafield”]. So I was looking into TypeScript for the reason that you might have need to make a strongly typed data.

So I made a little demo and a little class that demonstrates how you could work with strong types. I have a list that has a title and a number. So I want to work with the list in a strongly typed way.

Here is the core TypeScript code

    export class ListItemWrapper {
        constructor(private listitem: SP.ListItem) {
        public id(): number {
            return this.listitem.get_id();

        getOrSetAnyValue<T>(propertyname: string, value?: T): T {
            if (!(typeof (value) === "undefined")) {
                this.listitem.set_item(propertyname, value);
            return this.listitem.get_item(propertyname);

        public title(value?: string): string {
            return this.getOrSetAnyValue("Title", value);

        public _number(value?: number): number {
            return this.getOrSetAnyValue("Number", value);

Here is how I am using the code.

Whenever I have a listitem, I am creating a wrapper. After that I can use properties of a wrapper either as wrapper.title() which basically returns the result, or like wrapper.title(“new string value”), which sets the result .

That’s all folks, this is easy!

You can download the whole demo solution from which I plan to update. I will continue to upgrade the demo and I am planning to add a support for other types. Will start with Moment conversion as javascript default date formats are just weird. (Sorry americans, the default JavaScript format MM/DD/YYYY is considered weird in other countries including Russia and Australia Smile ). Also planning to try working with user and lookup fields.

HOW TO: Customizing SharePoint AppWeb web template (fixed version) or how would you make your custom default master page into your sharepoint app?

This article is basically a clone of

but I tried to add a missing pieces of code. It was a hell for me to gettting through this article as it is missing a lot.

So I have used


Originally I had a question – how could you change the logo that happens on all app pages if you are using a default master page?

So/ let us go and make a fixed version of the article. I will try to follow the original numeraton,is possible.

I assume that you have a SharePoint hosted app already. I will go through the steps from technet article and will add missing pieces of code and screenshots.

So I have a SharePoint hosted app and a picture like this to be on the place of the logo.

here is an url

(and yes,, and all that stuff, I like watching myself)

So let us go through the original article.

1. Create a SharePoint hosted App project using VS2012.


2. Right click the project in Solution Explorer and click > Add new item > Empty Element.  Name it “MyCustomMaster”.

3. Go to "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\SiteTemplates\App\Xml\ONET.XML"  and copy the ONET.xml file and paste it in the MyCustomMaster folder that is created in the project as a result of the above step. Note: the original article tries to use sts template, but anyhow most of the links from it ain’t gonna work, so we are taking app template.

4. Include the onet.xml to the project, make sure the deploymentType is ‘ElementFile’ in onet.xml’s properties window.

5. Open onet.xml and we will start modifying it as below:
    Remove all <Configuration></Configuration> but the one with ID=0.  In WebTemplate we can only have Configuration with ID=0.
    Remove all <modules></modules>.  There should be no <modules> in a webtemplate.
    Remove <serverEmailFooter>
    Rename configuration to conform to your elements name.

<Configuration ID="0" Name="MyCustomMaster" MasterUrl="_catalogs/masterpage/MyCustomMaster.master">

now I will add some more items as opposed to original article.
5.1 Add a module and call it masterpages. Set path to “_catalogs/masterpage”.
    remove the default sample.txt and add a copy of "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\GLOBAL\app.master". Let us call this copy a MyCustomMaster.master.
Be sure that is deployed directly under _catalogs/masterpage and add some additional properties. Your elements.xml shoudlook like this.
<?xml version="1.0" encoding="utf-8"?>
Elements xmlns="">
Module Name="masterpages" List="116" Url="_catalogs/masterpage">
File Path="masterpages\MyCustomMaster.master" Url="MyCustomMaster.master" ReplaceContent="TRUE" Type="GhostableInLibrary" Level="Published">
Property Name="UIVersion" Value="15"></Property>
Property Name="MasterPageDescription" Value="my master page" />
Property Name="ContentType" Value="$Resources:cmscore,contenttype_masterpage_name;" />

5.2 Change the onet.xml  <Configuration ID="0" Name="App" MasterUrl="_catalogs/masterpage/app.master"> to point to your master page  <Configuration ID="0" Name="MyCustomMaster" MasterUrl="_catalogs/masterpage/MyCustomMaster.master">

Note: you actually could find and replace SiteLogoUrl in the onet.xml but for the purpose of this post we will change the master page.

5.3 Let us customize the master page.  Find the line “ <SharePoint:SiteLogoImage CssClass="ms-siteicon-img" name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl="/_layouts/15/images/siteIcon.png?rev=23" runat="server"/> Replace it with. <img class="ms-siteicon-img" name="onetidHeadbnnr0" id="onetidHeadbnnr2" src =""/&gt;


6. Open the Elements.xml of CustomWebTemplate and paste below xml: <WebTemplate Name="MyCustomMaster" Title="A site with my custom master" BaseTemplateID="1" BaseTemplateName="APP" BaseConfigurationID="0" DisplayCategory="App sites" />

Important note: I am not 100% sure but it is better to have Name attribute to be the same as element you have created earlier.

7. skipped.

8. Right click AppManifest.xml and click > View Code.

9. Before </Properties> copy below xml.

<WebTemplate Id="{27afae7b-e5a8-48c6-b337-817f38d288ce}#MyCustomMaster" />

10. this line is made by an id of your feature, that you can find by editing the feature, and the name of your elements file with onet.xml.


11. skipped.

12. Save all changes and deploy the app.  Once deployed browse the app.  You will notice that the App is now using team site template instead of App template.  You will see familiar quick navigation and site settings.

Full solution is available at 



Creating SharePoint solutions with typescript.

This article explains how you could use TypeScript with SharePoint.

I have to confess – I hate JavaScript. I have been through Assembly language, Pascal, Java ,C , C++, C# and many other exotic things including Fortran and TeX. Could be I am getting older and more conservative, but I cannot stand the language that can change a variable type on the fly, that has no type-checking.

Unfortunately for me  – SharePoint becomes more and more JavaScripty.

To make things worse, some things I was already rather good at, are now changed. Let us take a simple example – override the way how your list looks like. I have already got used to vwstyles.xsl and even got familiar with many override techniques. Did you know, for example, that you can use the language id in XSL and make rendering the same list different for different languages?

Now the mainstream is CSR rendering and  – SharePoint moves to JavaScript. This is basically the way to operate with the site when you have SharePoint Hosted app. There is a whole bunch of new stuff. And as a SharePoint specialist I have to move into that.

Luckily there is a modern trend that helps strongly-typed guys like me to accept JavaScript.

The thing is TypeScript. TypeScript is a new rock stuff from Anders Hejlsberg and is worth many other articles itself. To be short – TypeScript gives a lot of things like strong types , classes and interfaces into JavaScript. Classes – yes, real classes, not a function within a function within a function. And you have a great intelligence.

Typescript support can be easily installed into your Visual Studio 2012+ from the official site

TypeScript file is actually producing JavaScript file. That is why you do not worry about browser support. You may think of TypeScript as C# that produces MSIL (JavaScript). Or think as C producing assembly code. The same code, runs on same thins, but more clear.

TypeScript definitions are generally shorter and more clear, and you have a compile time type checking. This is really important and we should not underestimate that.  Once it saved me half a day debugging when I messed up with using Moment and Date at the same time.

Once have decided using TypeScript, there is one little problem. The problem is that if you have a JavaScript file calling a library with function foo() and you want to call it, you will get a compiler error unless you have a TypeScript definition for foo. All major frameworks have this support though. To get this support, you could open a nuget package manager and type there a magic keyword “DefinitelyTyped”or just typescript and you’ll get this for almost any library you going to use.


A few Russian MVP’s created a great project called SPTypeScript (

This project has two major features

  1. TypeScript definitions for a big part of SharePoint CSOM.
  2. A lot of useful sampled. To name a few – custom rendering of list view + overriding forms and making new/edit forms with tabs containing native editors inside. Some samples  is an input from guy Anton Vishnyakov.

Let us try to use the code from the first sample and create our own app with a list with custom rendering.

Step 1- create a SharePoint Hosted App.



Now let us create a task list instance


This will be a task list that we want to have custom rendering.  We want to have tasks colored based by their percentage.

But before that let us make our project support TypeScript. Out project is not a TypeScript project, thus some additional work may be required.

Press unload project and then edit project

clip_image005   clip_image006[6]

Now add the following lines to the end of your project.







  <Import Project=”$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets” />


You can find a more specific information about these lines.

I would like to point out that you can choose ES3 or ES5 depending of which version of EcmaScript

You plan to support. ES5 is not compatible with IE8, but has cool things like properties.

Press reload project


Press Project\ Manage nuget packaged and find the package called sharepoint.typescript.DefinitelyTyped


Alternately you could run this command in the Nuget console

InstallPackage sharepoint.TypeScript.DefinitelyTyped

Now press project – right click – add new item, select TypeScript and let us create a file Mytasks.ts


Check that build action is set up to TypeScriptCompile.

The trick here is that for some reason the files generated by TypeScript are not added automatically to the project, so build the project, select Show Al lFiles and add the relative files into the project.


Now we need to make sure that our JavaScript file is connected to the list, i.e it is added to all list-relative pages.

Open your elements.xml file related to your list and add the line


   1: <CustomAction Location="ScriptLink" ScriptSrc="~site/Scripts/mytasks.js" />

Now let us create the code.  This is a slightly modified version of a sample you could find if you would download the Sptypescript project.

   1: module MyTasks {

   2:     export function init() {

   3:         var options: SPClientTemplates.TemplateOverridesOptions;

   4:         options = { Templates: {} };

   5:         options.OnPostRender = OnPostRender;

   6:         SPClientTemplates.TemplateManager.RegisterTemplateOverrides(options);


   8:         function OnPostRender(ctx: SPClientTemplates.RenderContext_InView) {

   9:             for (var i = 0; i < ctx.ListData.Row.length; i++) {

  10:                 var listItem = ctx.ListData.Row[i];

  11:                 var percentComplete = parseFloat(listItem['PercentComplete.']);

  12:                 var row = document.getElementById(GenerateIIDForListItem(ctx, listItem));

  13:                 if (row) {

  14:                     if (percentComplete > 0.8) {

  15:                = '#f8502a';

  16:                     }

  17:                     else if (percentComplete > 0.4) {

  18:                = '#52f82a';

  19:                     }

  20:                 }

  21:             }

  22:         }

  23:     }

  24: }


  26: if (document.location.href.indexOf('/Lists/MyTasks') > 0) {

  27:     SP.SOD.executeOrDelayUntilScriptLoaded(function () {

  28:         MyTasks.init();

  29:         SP.SOD.executeOrDelayUntilScriptLoaded(function () {

  30:             //Enable script with MDS

  31:             RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~site/Scripts/MyTasks.js"), MyTasks.init);

  32:         }, "sp.js");

  33:     }, "clienttemplates.js");

  34: }

Let us discuss this part

   1: if (document.location.href.indexOf('/Lists/MyTasks') > 0) {

   2:     SP.SOD.executeOrDelayUntilScriptLoaded(function () {

   3:         MyTasks.init();

   4:         SP.SOD.executeOrDelayUntilScriptLoaded(function () {

   5:             //Enable script with MDS

   6:             RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~site/Scripts/MyTasks.js"), MyTasks.init);

   7:         }, "sp.js");

   8:     }, "clienttemplates.js");

   9: }

SP.SOD is a classical way to lead with SharePoint ScriptOnDemand engine. We want to be sure that our code runs after the scripts we depend on are loaded.

RegisterModuleInit is explained in detail here

Now let us go to the init function.

Basically for this example the code is similar to what you might have had with using JavaScript. A good Intro co a client side rendering can be found here

In this function we do register an OnPostRender callback function. Note that we have a full access to the items themselves and also to the UI elements that has to do with these items.

Here is the result


To conclude the article – let us think again – why do we use typescript?

An easy answer would be : compile time checks.

Just to illustrate this – I will make  a misprint.


As you can see a project is not compiling.

So I hope that I could show that actually it is not a hard task to add TypeScript to your SharePoint projects. By making a few things, you will get  a huge speed up in your SharePoint projects.

How to make SharePoint use debug scripts?

Recently I have setup a new machine and wanted to dig into some standard SharePoint scripts. The thing is that SharePoint has used all normal minimized scripts (sp.js, core.js) while I want it to run sp.debug.js and code.debug.js

To get the answer we need to get into the component called ScriptLink.

If your script is registered as ScriptLink (as most sharepoint scripts are), then the ScriptLink class can automatically use .debug. scripts if ScriptManager.iSDebuggingEnabled is true.

ScriptManager.IsDebugging enabled follows the following logic.

If there is <deployment retail=”true”> – return false.

Else if the script mode is not auto and not inherint, return (ScriptMode = Debug)


return what is set in <compilation debug=”xxx”…/>

So for developer farm the easiest thing to do is go to web.config and set there


<compilation batch="false" debug="true">