OutOfRangeException in SharePoint 2013 SetThreadCulture method

The problem

Recently I had to work on a tricky SharePoint bug. Sometimes users called about a correlation ID that was displayed when accessing a SharePoint publishing site. The issue was sporadic. In some cases refreshing the page was enough but on other cases the correlation ID was displayed during several minutes. We were running SharePoint Server 2013 with SP1 without any cumulative updates.

So we did what any SharePoint developer would have done : scanning the ULS logs. Here is a copy of the exception :

System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.Dictionary2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary
2.TryGetValue(TKey key, TValue& value)
at Microsoft.SharePoint.SPFallback1.GetPath(T node)
at Microsoft.SharePoint.SPFallback
1.GetPathLength(T startNode, T endNode, Int32& length)
at Microsoft.SharePoint.SPFallback`1.TryDetermineBestMatch(T[] supporteds, T[] desireds, IsMatched isMatched, LanguageDecisionOptions options, T& bestMatch)
at Microsoft.SharePoint.SPLanguageSettings.TryDetermineLanguage(UInt32[] supportedLcids, UInt32[] desiredLcids, LanguageDecisionOptions options, UInt32& bestMatchedLcid)
at Microsoft.SharePoint.SPLanguageSettings.TryDetermineLanguage(String[] supportedLanguages, String[] desiredLanguages, LanguageDecisionOptions options, String& language)
at Microsoft.SharePoint.WebPartPages.Utility.ComputeUICultureForMUIWebs(String strMUILanguages, UInt32 WebLanguage, UInt32& uiCultureLcid)
at Microsoft.SharePoint.WebPartPages.Utility.SetThreadCulture(SPWeb spWeb, Boolean force)
at Microsoft.SharePoint.ApplicationRuntime.SPRequestModuleData.GetFileForRequest(HttpContext context, SPWeb web, Boolean exclusion, String virtualPath)
at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.InitContextWeb(HttpContext context, SPWeb web)
at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.GetContextWeb(HttpContext context)
at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.PostResolveRequestCacheHandler(Object oSender, EventArgs ea)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Note : text in bold was found in several locations in ULS. Text that is not in bold is variable since the “SetThreadCulture” method is called by many other methods. So you can encounter the same behavior with a different stack trace.

Why? (Skip if you are not a developer)

The problem happens when SharePoint sets the thread culture. We have french language pack installed on our Farm and the SharePoint site on which the error occurs is multilingual. Moreover we  developed a custom product to translate our publishing pages. This tool is setting the thread culture depending of the current user’s language preference. Since we have some custom code that is playing with the thread culture we thought that was a good lead. Unfortunately our code seemed OK and we didn’t find any problem with it.

At this time we decided to decompile the Microsoft.SharePoint.dll assembly and search for any clue.

Here is the code of the “GetPath” method you can see in the stack trace :

The m_path field that is highlighted is instantiated in the constructor the generic SPFallback class :

And the SPFallback instance used by SPLanguageSettings (check the stack trace if you are lost) is actually static (I invite you to decompile the SPLanguageSettings class if you are curious). To summarize the m_path Dictionary is shared by all the requests made on this particular Web Application…

Did you see that coming?

A lot of .Net developers are not aware that a Dictionary is not thread-safe in .Net. Worst : you can end with a high cpu usage when reading and writing in a Dictionary concurrently!

A Dictionary<TKey, TValue> can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure (MSDN).

See the thread safety section of the Dictionary reference : https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

The funny thing is that the developer who wrote this piece of code was aware of a potential concurrent issue so he (or she) decided to put a lock (Monitor.Enter actually) around the block that clears the m_path Dictionary. Unfortunately that is not enough!

The solution

Install the May 2014 Cumulative Update! In the description you can read :

When you change the fallback language on a SharePoint Server 2013 server, you experience high CPU usage on the server.

Here is the link : https://support.microsoft.com/en-us/kb/2878240

If you are a developer and you are curious about how this has been fixed, you can decompile the code after applying the CU and you will see that the Dictionary I was talking about has been replaced by a ConcurrentDictionary.

SharePoint Image Renditions Size Restriction

Image Renditions are a great feature of SharePoint 2013. While writing another blog post about Image Renditions I figured out that there is actually a maximum size when adding an Image Rendition.

If you are used to add Image Renditions by using the UI you may have noticed the validation message “The value entered is invalid. Value must be a number between 1 and 2048” :

If you are a developer like me who is playing with the API before the OOB features this limit is not so obvious. When you are provisioning Image Renditions thanks to a SharePoint Feature you won’t have any messages or log entries to warn you. The Image Renditions with a width or height over 2048 will be simply ignored.

Is it possible to configure your environment to increase this value? No. When decompiling the IsValid method of the Microsoft.SharePoint.Publishing.ImageRendition class you can notice that 2048 is actually a constant.

It’s not really an issue in my opinion. You probably won’t need to generate renditions over this size but I think it’s good to know this limitation when deploying this kind of artifacts for SharePoint.

Custom WebPart ToolPart with SharePoint look and feel

Sometimes things that should be pretty simple are finally a lot more complicated than you would imagine. Today I tried to create a custom WebPart ToolPart to expose a custom property. Writing a toolpart for a SharePoint WebPart is pretty straightforward. You need to create a class that inherits Microsoft.SharePoint.WebPartPages.ToolPart. This class will handle the controls needed to edit your custom properties. Then you have to override the GetToolParts method to return the SharePoint base ToolParts and yours.

I won’t explain here in detail the steps needed to create the ToolPart, if you need more info you can read the post of Tobias Zimmergren here : http://zimmergren.net/technical/how-to-custom-web-part-properties-toolpart

So after putting these blocks together you end up with this :

That’s was not what I was expected at all ! See the difference with the Advanced section that is OOB. Instead of the collapsible panel with the blue title I get an ugly ASP .Net style toolpart.

So I decided to run one of my favorite SharePoint developer tool : dotPeek (I’m saying dotPeek is a SharePoint tool because when you start developing serious solutions for SharePoint there is a point you just NEED to explore the API by yourself).

After decompiling a couple of classes I finally found the control that is used to render the toolpart like SharePoint does.

Here are the steps to recreate the look and feel of a SharePoint ToolPart :

  1. Disable the Chrome of the ToolPart in the constructor.
  2. Instantiate a Panel Control into CreateChildControls. You have to put an id to this panel, it is required by the JavaScript which is handling the collapse / expand functionality.
  3. Instantiate a Microsoft.SharePoint.WebPartPages.TPPanel with reflection (this is an Internal type) and pass the Panel created in step 2 in the argument list.
Here is a code sample of the CreateChildControls method :

Warning : we are using reflection here to instantiate a control that is marked as internal. You shouldn’t use this method because it’s not supported by Microsoft. I won’t argue on this topic in this post but personally I’m OK with that. The only risk is to break the functionality when upgrading to the next version of SharePoint, unfortunately if I try to reproduce the SharePoint style by applying the same CSS than the TPPanel on custom controls I probably have to change the CSS with the next version. You know what? I rather prefer to update a line of C# every 3 years than struggling with some CSS.

That being said here is the result :

If you want to apply the SharePoint style on the Controls inside the TPPanel I invite you to download the attached project that contains a full example of Custom ToolPart. The final result :

I hope you will enjoy your custom toolpart with SharePoint Look and Feel ! Don’t hesitate to leave a comment if you have any question.

CustomToolPane.zip (13KB)

Automatically log off disconnected RDP sessions with PowerShell

Here is a PowerShell script I use to log off disconnected sessions. When a user closes its connection and forget to actually use the Sign out button on Windows, all the programs he was using are still running and using resources. You can use this little script to configure a scheduled task that will force the disconnected sessions to actually be closed.

I’m using the command line tool qwinsta that is shipped with your Windows installation. So you don’t have to install anything to run this script. qwinsta shows you all the RDP sessions with their state, user and id. When you have found the disconnected sessions you can kill them thanks to the command line tool rwinsta.

The script is pretty simple, it just parses the result of the qwinsta command and calls rwinsta for each disconnected session.

To use it, you can call it from the server hosting the sessions or call it from anywhere and use the server parameter to specify the target machine. Note that you have to be joined to the domain of the target machine if you are using it remotely.

I hope this script will help you keep your server clean off disconnected sessions :)

Detect touch devices in JavaScript

Today I’m writing about a JavaScript snippet that I use to detect if the device has a touchscreen.

This code won’t work on some old version of Chrome on Windows 8/8.1 because at this time the browser was supporting some touch features on non-touch devices. You can read about it here : http://www.stucox.com/blog/you-cant-detect-a-touchscreen/

You have to be aware that it is very difficult to detect if a device has a touchscreen because depending of the browser and operating system, the touch features can be implemented on a non-touch device. So I tested my snippet with Safari on iOS, Firefox, Chrome and Internet Explorer 10/11 on Windows 8.1 and Windows 10 technical preview but I can’t tell for how long it will keep working.

You can test this snippet thanks to this fiddle : http://jsfiddle.net/wawawum/xak5bbv7/

Your Windows 8.1 install couldn’t be completed

Today my Surface Pro decided to stop working. My Windows Explorer process was freezing. I tried to solve the issue without success. Finally I tried the “Refresh your PC” option that reinstalled Windows 8. Then I tried to reinstall Windows 8.1 and get an error message : “Your Windows 8.1 install couldn’t be completed, try again later”.

I installed every missing Windows Update (115 updates), no success. Then I installed optional updates, no success. Finally I noticed that 15 apps (Modern UI Apps) were not up to date. You can see this in the Windows Store at the top right corner of the screen. After installing the updates for these apps, I was able to install Windows 8.1.

So when installing Windows 8.1 remember to :

– check Windows Updates

– check Modern UI Apps Updates

Get the Selected WebPart ID with Client-Side code (JavaScript)

This week one of my coworker needed to retrieve the Storage ID of the selected WebPart in the page. Since he needs to do that from a Custom Action in the Ribbon, he has to use JavaScript code to retrieve the ID.

The solution came to me when looking into the definition of the SP.ListOperation.Selected.getSelectedItems function. If this function is able to get the selected Items of a ListView WebPart, it probably knows how to retrieve the selected WebPart and maybe its ID. This function calls the GetSelectedItemsNative function which is defined into CORE.js. Inside its body the GetCurrentCtx function is called. Here is its definition :

Yeah! That’s exactly what we need. The purpose of this function is to retrieve the context of a ListView WebPart (List URL, Web URL etc…) but the main part of the code is about retrieving the ID of the WebPart. Let’s rewrite it :

If you don’t know how to retrieve your WebPart server-side with this ID, check this code :

I hope it will help you Vincent 😉

SharePoint 2010 and AJAX – Part 2

This article follows my first one about SharePoint 2010 and AJAX. We saw how to create a simple WebPart with jQuery and Knockout in order to retrieve data with AJAX and use the MVVM pattern in our client-side code. You certainly noticed some hard-coded values in my examples. It’s not the kind of things I call “Best practices”. The goal of this article is to address this problem.

With server-side code we are used to stored the configuration needed by the components in different places : WebBrowsable Properties for a WebPart, web.config, Property Bag, Custom Database, SharePoint Lists, etc.

Here I’m proposing a solution to access your configuration client-side. I’m going to use jQuery and Knockout.js but the concept is generic.

I will use the same code than in the first part of this article. You can download it here : WawawumAjaxPatterns.zip

The Concept

The idea is very simple. Given that it’s easier to access the configuration with server code, the options needed by the View Model will be generated thanks to server code. All the configuration will be wrapped in an object passed into the constructor of the View Model.

The “options” will store different types of data:

  • Configuration values (the URL of the WCF Service for example)
  • Controls’ Client ID
  • Resources

Setting up the project

As said before we will start from the project available on the first part of this article. The WebPart contained inside this project has no configuration. All the parameters are hard-coded client-side. So we will update this project to add some properties to the WebPart.

Adding WebPart Properties

Open the TasksWebPart.cs file located into WebControls\TasksWebPart and add the following properties :

Add a constructor to initialize default values of these properties :

Override the Parent property in the Child Control

Accessing the Parent WebPart from the child User Control is a common problem when developing a Visual WebPart. Personnaly I always use the following piece of code that must be added into the TasksWebPartUserControl.ascx.cs file :

Don’t forget the new keyword in front of the Parent Property.

Updating the Business and Service Layers

These steps are not directly link to our problem. I just want to demonstrate how to serialize/deserialize different data types. What’s why I added the ItemsLimit property to the WebPart in order to have an integer. In the first part of this article, the number of items to retrieve cannot be set. So we have to update the business and service layers.

First update the TasksManager by adding a itemLimit parameter to the GetTasks method :

Then modify the signature of GetTasks in the ITaskService interface :

Finally implement the new version of the ITaskService interface in TasksService :

Creating the options object

What we want to generate is something like that :

We can achieve that by multiple ways :

  • Write a server-side method that will collect the settings and write them into a string formatted as JSON.
  • Write a Class which represents the settings and override the ToString method to write the instance of the object as JSON.
  • Write a Class which represents the settings and use the JSONDataContractSerializer or JSON.Net to serialize it as JSON.

The first two ones are obviously the easiest to implement but the most difficult to maintain. Each time a setting will be added, the corresponding code to format it will have to be written. Moreover, serializing complex types is a tedious work.

That’s why I prefer the solution of serializing an object representing the options thanks to the JSONDataContractSerializer or JSON.Net. Usually my advice is to use the native features of the .Net Framework rather than referencing third party libraries. This is true if the framework fits to your needs but in this case the JSONDataContractSerializer is quite limited.

The main limitations I found are :

  • No circular references : you cannot serialize an object having a property of its type (a Person with a Manager property of Person type for example).
  • Dictionaries cannot be serialized.

You can see a comparison table between JSONDataContractSerializer and JSON.Net here : http://james.newtonking.com/projects/json-net.aspx

Thus in this example I will use JSON.Net to serialize our object since I need a Dictionary to store the localizable resources and the Controls’ Client IDs.

Creating the Client Options Class

Add a class named “TasksClientOptions” into the TasksWebPart folder and put some properties which will be used to configure our View Model.

Serializing the Client Options

As said in the introduction of this section, I will use JSON.Net. You can download it here : http://json.codeplex.com/

Then reference the DLL into your project.

Here is the cool part. We will add a method that will be called directly from the ASCX. This method will create a new instance of the TasksClientOptions object, assign properties to it and then return a JSON representation of this object. That’s how the configuration retrieved server-side will be available client-side.

The following piece of code take care of these tasks :

See how it’s simple. The TasksClientOptions object is created and the ServiceUrl and ItemsLimit properties of the WebPart are retrieved thanks to the Parent Property we overriden before.

The Client ID of the div surrounding our controls is added to the Controls array. That will be usefull to get a reference to this control client-side thanks to document.getElementById or jQuery selectors.

Then ressources are added to the Dictionary. In this example my resources are hard-coded. In a real-world project these resources should be stored into RESX files.

Finally the serialization takes place in the last line of the function. JSON.Net makes us the task very easy. Calling the SerializeObject method will serialize the TasksClientOptions object into JSON and return it as string. Of course the serialization process can be configured.

Note that by default JSON.Net serialize all the public properties and fields. If you want to skip some of them you can :

  • Add the JsonIgnoreAttribute on the properties to skip
  • Add the DataContract attribute on the class to serialize and add the DataMember attribute to properties to serialize. This method is compatible with DataContractSerializer.

Retrieving the Client Options in the ASCX file

Now we have a method that generates our client options object in JSON. So we need to get this object client-side. We just need to update the ASCX file “TasksWebPartUserControl.ascx”. Search for the “initTasks” function and update it :

We use inline code to call the GenerateClientOptions that returns the object as JSON. Then this object is passed in the constructor of the View Model object.

After deploying the project we can inspect the generated HTML by viewing the page’s source :

If you want a more readable representation of the JSON generated you can copy / paste it into JSON Parser Online :


The View Model

The last remaining step involves to refactor the View Model to take advantage of the options object. First, update the constructor to keep a reference to this object :

The lastUpdate observable will be used to display the time of the last refresh of the data.
This time the id of the container is not hard coded. So if you add more than one instance of this WebPart, the databinding with Knockout will work perfectly.

Then update the getData function to use the ServiceUrl, ListName and ItemsLimit properties of the options object :

Note that I added a callback when the AJAX call failed. Don’t forget to add it :

This callback uses both the Controls and Resources arrays.


Finally we need to update the ASCX to correct the databinding :

Here I added the runat=”server” attribute to the outer container. I also put a message displaying the last update time. You can see how easy it is to access resources thanks to the options object.

The Result

If you deploy the project you should obtain a very ugly but working WebPart :


In this example I added two WebParts to show that they are independant. That’s cool but what are exactly the advantages of such a solution?

The advantages

Instead of using an object generated server-side then serialized into JSON you could use inline code to inject some dynamic values retrieved server-side into your JavaScript. Unfortunatly by doing this you can’t move your JavaScript code into a separate JS file since your inline code won’t be interpreted as expected.

That’s a major benefit of the solution exposed through this article. With a server-side generated object, you don’t have any reference to server-side code in your View Model. Only the initialization part must be put into your ASCX file.

Thus your code becomes more reusable since you can use your JavaScript file in multiple WebParts / Controls. Only the initialization will change.


Here is the code of this demo :

WawawumAjaxPatterns – Part2.zip

SharePoint 2010 and AJAX – Part 1

I decided to write some tips about building a complete AJAX solution running on SharePoint 2010. There is no rocket science here but sometimes it’s not so simple to put all the pieces together to make a robust and easy to maintain solution. This post will give you some recipes to build AJAX components based on a layer architecture.

This first part deals about setting up your solution and deploy required clients libraries on your SharePoint environment.

Creating the projects

Create a new empty SharePoint project, choose a SharePoint site to deploy your solution and select the “Deploy as farm solution” option. Now add the following folders:

  • Helpers
  • Entities
  • BL
  • Services
  • WebControls

You should obtain something like this :

Adding jQuery

I can’t work anymore without jQuery. It’s a very powerful way to traverse and manipulate the DOM of your page furtermore it provides AJAX helpers. SharePoint does not include jQuery so we have to add it to our solution and ensure that it will be available everywhere in our SharePoint site.

There are multiple solutions to this problem, the one I prefer is to use the delegate control AdditionalPageHead to register our scripts.

First thing to do is download the latest release of jQuery. So, go to http://jquery.com/  and grab the latest production (or development) version.

Then add the SharePoint mapped folder “Layouts” to your project. Visual Studio will add a folder with the name of your solution into it. Add another folder “Scripts” inside and save your version of jQuery here.
Thanks to that jQuery will be deployed into the SharePoint’s hive folder.

Now we will use a WebControl to register the script into the pages. In your project, add a new class named “AdditionalPageHead.cs” into the WebControls folder. Then make the class public and inherit from System.Web.UI.UserControl.


In this WebControl you can register the jQuery file thanks to the ClientScriptManager of the page. This can be implemented like this :

I use the SPUtility.MakeBrowserCacheSafeLayoutsUrl in order to generate a URL that won’t be cached by the browser. It just adds a hash in the URL of the file (in a query string).

Now we have to use a Element file to register our Delegate Control. So let’s add a SharePoint Module named “AdditionalPageHead” to our project, delete the sample file of the module and edit the Element file :

Don’t forget to update the ControlAssembly value and ControlClass with your own namespace and public key token.

Now rename the feature, I chose “WebControls” and set the scope to “Site”. Ensure that the AdditionalPageHead module is included into the feature:


We have a last thing to do in order to make this control work properly : add a Safe Control Entry. Opens the properties of the AdditionalPageHead module (right-click on it) and edit the “Safe Control Entries” attribute :


Now deploy the project to your test environment and you should see jQuery loaded into the Developer Toolbar of Internet Explorer :


Note : instead of creating a class inheriting from UserControl you can add a User Control directly from the Add new item window of Visual Studio. This will create an ASCX file and the code-behind. The benefit of this method is that you don’t have to add the Safe Control Entry. It’s up to you.

Adding Knockout.js

The main problem when you build an AJAX control is to bind the data with the UI. Server-side we have a lot of controls to do such a thing : Repeater, DataList, GridView… Client side is an other story, it can be such a pain to create controls dynamically and bind data to them. Knockout solves this problem by applying the MVVM pattern in JavaScript. It enables you to declare templates and bind them to your data. Your UI  can be automatically refreshed when the View Model changes. Through this article I’ll try to explain the basics of Knockout but I strongly suggest you reading the official documentation if you want to go further : http://knockoutjs.com/

Start by downloading the last version of Knockout and the Knockout Mapping plugin and add them to the Layouts/Scripts folder we created before. Then add a RegisterClientScriptInclude call into the AdditionalPageHead UserControl to register the script files :

Redeploy the project and check if the knockout.js file is loaded.

Creating the Entity and the Business Layer

I’ll take a very simple example for the business layer. We will return the items of a SharePoint Tasks list. This is not very useful but accessing the data is not the point of this article so I let you adapt the code to your needs. You can query items on a list, search results or even data stored into an external database, this won’t change the rest of the solution.

Creating the Entity “Task”

Start by adding a class “Tasks” into the Entities folder and add some basic fields and constructors :

Two important things here :
– You must apply the DataContract to the Task Entity because it will be serialized / deserialized by the DataContractSeralizer when sending and receiving messages through the WCF Service.
– You must apply the DataMember attribute to each field of the Task Entity you want to serialized.

You noticed that I added an enumeration to store the value of the task’s status. I put this enumeration in the same file that the Task class.
When a Task will be instantiated from an SPListItem we will have to convert the SPFieldChoiceValue to a TaskStatus enumeration. In order to achieve this conversion I use a custom class : ChoiceFieldValueAttribute. You can find all the explanations on my blog : SharePoint Choice Field, CAML and Enum.

Here I’ll just give you the steps to add it to our project. Add a new class “ChoiceFieldValueAttribute” into the Entities folder and copy the following lines of code :

Creating the TaskManager

Now we have to create a class to retrieve the data from SharePoint. Add a class “TasksManager” to the BL folder :

I won’t explain this piece of code because there is nothing special here about creating an AJAX component, it’s not rocket science. You can implement your business layer as you want. I often use LinQ to SharePoint to retrieve strongly-typed entities but in this example I’ve decided to get these with the classic SharePoint Object Model and CAML.

All you need is a method GetTasks returning all the tasks of a SharePoint list and a AddTask method to create new items in this list. All the other stuff deals about the disposal mecanism.

Creating the WCF Service

Here is the tricky part if you never have created a WCF Service hosted in SharePoint. It’s pretty easy actually because SharePoint handles all the configuration itself (you don’t have to specify endpoints and all of these XML stuffs).

The WCF Service Contract

Let’s begin by adding an interface “ITasksService” in the Service folder of our project. This interface will define the contract of the WCF Service.

  • ServiceContract : specifies that this interface is a Service Contract.
  • ServiceKnownType : add this attribute for each type that may be serialized / deserialized when a Service method is called. In this example we are only working with Task entities so this is the only type to define.
  • OperationContract : add this attribute on each service method.
  • WebInvoke : this attribute specifies that the decorated method can be called in REST. Moreover you can configure if the method should be called with a POST or GET request.

The Service Implementation

Now we have to implement our contract. Add a “TasksService” class into the “Services” folder and implement the ITasksService interface.

  • BasicHttpBindingServiceMetadataExchangeEndpoint : tells to SharePoint to enable a MEX endpoint

The SVC file

The last step is to create the svc file that will define our service’s type and which SharePoint service factory to use.
The svc file must be deployed to the SharePoint ISAPI folder, right-click on your project è Add è SharePoint Mapped Folder and choose the ISAPI folder. Then add a file named “TasksService.svc” into this folder. The file type does not matter, it can be an empty text file.
Add the following content :

The service attribute must sepcify our service implementation. Replace my assembly full name by yours. Usually you can use the token $SharePoint.Project.AssemblyFullName$ that should be replaced by Visual Studio when packaging your project. In my case it didn’t work on this project so I just put my assembly full name myself.
The factory can be one of the following SharePoint Factories :

  • MultipleBaseAddressBasicHttpBindingServiceHostFactory = SOAP service
  • MultipleBaseAddressWebServiceHostFactory = REST service
  • MultipleBaseAddressDataServiceHostFactory = ADO .Net Data Service

Since jQuery works well with REST  services we choose the second one.

Creating the WebPart

The last step is about creating the WebPart which will consume our WCF Service. I’m suggesting you to first create a very basic WebPart calling the Service without displaying anything. You should be able to see thanks to a tool like Fiddler if the service is actually returning the data. Then you add the databinding with knockout.js.

Adding the WebPart

Add a new Visual WebPart “TasksWebPart” into the WebControls folder of the project and ensure that the WebPart belongs the WebControl feature. Then add the following content into the ASCX file of the WebPart :

This piece of code will enable you to test your service. Deploy the project to a SharePoint development environment and add the WebPart in a page. The WebPart should display the list of your tasks :


If you start fiddler you can explore the result of the AJAX Call thanks to the JSON inspector. If you don’t have installed Fiddler already I suggest you to do it right now. This tool is essential to debug this sort of components. It enables you to see in details the HTTP requests made by Internet Explorer and to inspect the answers of SharePoint.


In the bottom right section of this screenshot of fiddler, you can see the result as JSON. You will notice that the result is always wrapped into an object which name is the concatenation of the service method and the constant “Result”.

DataBinding with Knockout.js

If you have never worked with Knockout.js before I suggest you to read the official documentation here : http://knockoutjs.com/documentation/introduction.html
The three points : Observables, Computed Observables and Observable Arrays are the main concepts to begin with this framework.

There are multiple ways to create the View Model which will be used by Knockout. First the entities returned by the WCF Service can be stored either into a native JavaScript array either in an observable array. The last one is useful when refreshing the View Model. If you want to refresh the WebPart without a postback by making another call to the WCF Service, it is very easy to refresh the whole view thanks to an observable array. Moreover if you support adding new items directly within the WebPart it will make the work straightforward.
Then each field of the entities can be converted to observables. It can be useful if the entities themselves are refreshed.

For this example we will use the most powerful and flexible solution : an observable array of observable entities (not a suprise isn’t it?).

Using the mapping plugin

The WCF service returns JSON objects that must be converted into observable objects. We can do this manually by assigning each field into observables or use the Mapping plugin of Knockout which has been added in the “Adding Knockout.js” part of this article.

First of all we need to add a field into our TasksManager to store the data. Add a “tasks” field into the constructor :

We use Knockout to create an empty observable array and assign it to the new field.
Then we need to convert the JSON objects into observables. Update the for loop in the getDataSucceeded callback function :

The fromJS function of the Knockout Mapping plugin enables to convert the JSON into observables. Note that the converted objects are not observables themselves, only their fields are now observables. So you can’t databind the View on a Task for example but you can do it on a Task’s Title field.
By doing this we bind our Model to the View Model.

Here you can see the content of the mapped object when debuging with the developer tools of Internet Explorer :


Note : To access to the Id field’s value we would write : task.Id() and not task.Id given that this field is an observable.

Creating the view

Replace the div with the id “TasksContainer” by this one and its content :

Then update the constructor of TasksManager :

Only the last line has been added to this constructor. The applyBindings function is like the “DataBind” method in .Net. It binds your View Model to the View.
The first argument is very important : it’s the View Model. And yes we are using the whole TasksManager object as the View Model.

So when we specify the token “tasks” into the “foreach” binding in the div element, we are refering to the “tasks” field of the TasksManager object.
The “Title()” token refers to the “Title” field of the current data item iterated by the foreach.

The second argument enables you to use multiple Views and View Models on the same page. If you don’t specify a DOM element when calling applyBindings, Knockout tries to bind the specified View Model at the page level. This doesn’t work if you have multiple views.
That’s why we target on which view the View Model is bound thanks to this second argument.

Deploy the changes and you should see your tasks.

Refreshing the data

Ok that’s fine but nothing new here. We can also get the list of tasks without Knockout and all this View Model stuff. That’s true but remember that in the first example we just write a list of Tasks. In a real-world example you will need to display plenty of data and add some events and behaviors. To illustrate how knockout can make your developer life easy, we will add a button to refresh our view model.

Modify the HTML markup to add an outer container around the existing one and a button, then updates the ID attributes :

Now we need to bind the View Model to the outer container “TasksWebPartContainer” instead the “TasksContainer” we just delete :

That’s all we need to refresh our data. If a new item is added to the SharePoint list, the WCF service will return it and thanks to the “tasks” observable array, the new results will be displayed with the new item. It is the same thing if an existing tasks is modified.


As you can see in this post’s title, you are reading the first part of a post series about AJAX and SharePoint. So stay tuned if you want more about generating dynamic client options for your AJAX components and some other tips.

Update : you can now read the next part of this article here:

SharePoint 2010 and AJAX – Part 2


Here is the code of this demo :


SharePoint Choice Field, CAML and Enum

If you have already worked with LinQ to SharePoint you have definitely noticed that SPMetal generates enumerations to fit with Choice Field’s values. This feature is really interesting because it enables you to work with strongly-typed values instead strings. Of course this increases your code maintainability.

But LinQ to SharePoint has its pros and its many cons. So in some situations, CAML is the best to fit your needs like in the good old days.

That’s why I’ve written some lines of code to use enumerations with CAML.


My solution is very close to the SPMetal behavior. I use a POCO to represent my data model. This object has an enumeration field which is mapped to a SharePoint Choice Field. On each value of the enumeration, I use a custom attribute to specify the associated SharePoint value.

Here is the code of the ChoiceFieldValueAttribute :

The Entity

Now let’s see how to use it in an entity which represents my data :

It’s realy easy to specify the mapping between the SharePoint values and the enumeration ones. Thanks to the static methods “ConvertToEnum” and “GetValue” you can easily convert SharePoint values to enumeration and vice-versa.

Getting the data

That’s fine but not enough. Here is an example of a business layer to retrieve the data from a SharePoint list and generates some entities :


Here you can see that it is pretty easy to filter the elements of the SharePoint List thanks the enumeration and the ChoiceFieldValue attribute. The main purpose of this, is to easily maintain your code. If the choice field’s values change, you will just update the ChoiceFieldValue attributes at the enumeration level. Your conditions and queries will automatically be updated.


Thanks to the overloaded constructor I’m able to convert SharePoint items to Task entities. This also convert the values of the “Status” field to my strongly-typed enumeration.


The AddTask method uses the CopyTo method of the Task entity to populates the SPListItem and converts the enumeration value to it’s SharePoint string representation.


Download the attached solution to test the code in your SharePoint environment : WawawumEnumCAML.zip
Prerequisites :

  • Sign the project with your key.
  • Deploy the solution to a SharePoint site which contains a “Tasks” list with the default tasks template.
  • Ensure that the “Wawawum -Tasks list” feature is activated.
  • Add the “TasksList” WebPart to a page.