SharePoint get dates like they should…

Working with dates is just always complicated and it is always an issue, in SharePoint it can be even worse, you retrieve a date and is just off by a date????
To make sure you retrieve the dates correctly you can use this method, I would make an extensions method for it, but here is is:

CamlQuery Modified times

Sometimes you just needs items that have been updated in a certain period of time.
You can do this with a CamlQuery, in this example I’m looking for items that have been modified in the last 80 minutes;
Basically you generate a DateTime object and format it to the right format.
Also look at the ‘IncludeTimeValue’ option of the query…

 <View Scope='RecursiveAll'><Query><Where><Gt><FieldRef Name='Modified'/>
<Value  IncludeTimeValue='TRUE'  Type='DateTime'>" + datetime + "</Value></Gt></Where>><OrderBy><FieldRef Name='Modified' Ascending = 'true' /></OrderBy></Query></View>

Add jQuery to EditForm.aspx

I needed to remove the content editor dropdown you sometimes see in the form.
The most efficient way to do this is to add een Content Editor WebPart to the form of your list.
This way you could also add any javascript to your edit form, or other things to your page.

Here is the code:

SPList list = web.Lists[LIST_NAME];
string EditFormURL = list.DefaultEditFormUrl;

web.AllowUnsafeUpdates = true;

SPFile file = web.GetFile(EditFormURL);

if (null != file)
      using (SPLimitedWebPartManager mgr = file.GetLimitedWebPartManagerPersonalizationScope.Shared))
if (null != mgr)
//create new webpart object
ContentEditorWebPart contentEditor = new ContentEditorWebPart();
//Add content to CEWP
XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = xmlDoc.CreateElement(“Root”);
xmlElement.InnerText = GetValidationScript().ToString();
contentEditor.Content = xmlElement;contentEditor.Content.InnerText = xmlElement.InnerText;

//Add it to the zone
mgr.AddWebPart(contentEditor, “0”, 0);


private StringBuilder GetValidationScript()

StringBuilder sbScript = new StringBuilder();
string sJQueryURL = “_layouts/JQuery.js”;//exact path of your js file
sbScript.Append(“<script src='” + sJQueryURL + “‘type=’text/javascript’></script>”);
sbScript.Append(“<script type=’text/javascript’>”);
sbScript.Append(“$(document).ready(function() { “);
sbScript.Append(@” $(‘select[id*=””ContentTypeChoice””]’).parent().parent().hide();”);
sbScript.Append(“}); “);
return sbScript;





Security trimmed sitemapprovider accross site collections

For one of my customers I needed a top navigation which was the the same acccross their different
sitecollections, and offcourse security trimmed.
The top navigation will look like this:


So in this post I’m explaining the following :

  • create a custom security trimmed sitemap provider
  • deploying a masterpage accross all sitecollections
  • modifying the web.config
  • activating the masterpage acccross the whole site collection

The solution will look like this:


To create a custom sitemapprovider a created a sitemap file.
Just add an xml file and rename it:

<siteMapNodetitle=Global Portaldescription=“”url=//>
<siteMapNodetitle=Test 002description=“”url=~/Test 002>
<siteMapNodetitle=test 001url=~/sites/test 002/001description=“”/>
<siteMapNodetitle=test 002url=~/sites/test 002/002description=“”/>
<siteMapNodetitle=test 003url=~/sites/test 002/003description=“”/>
<siteMapNodetitle=Information Technologydescription=“”url=~/it/>
<siteMapNodetitle=North Americaurl=~/regions/NAdescription=“”/>
<siteMapNodetitle=Middle Easturl=~/regions/medescription=“”/>

The next step is to tell SharePoint that this provider exists, therefore we need to change the web.config file.
We could do this manually but if you have a large farm mmmm….
I created a feature with a receiver that does the work form:

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;namespace MUAC.SiteMapProvider.Features.MUAC.SiteMapProvider
public class MUACEventReceiver : SPFeatureReceiver
// Uncomment the method below to handle the event raised after a feature has been activated.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
webConfigMod(true, webApp);
catch (Exception exception)


public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
webConfigMod(false, webApp);

private void webConfigMod(bool setting, SPWebApplication webApp)

#region Muac Custom Navigator

SPWebConfigModification setting_CustomNavigator = new SPWebConfigModification();
setting_CustomNavigator.Path = “configuration/system.web/siteMap/providers”;
setting_CustomNavigator.Name = “add[@name=’MUAC_CustomNavigator’]”;
setting_CustomNavigator.Sequence = 0;
setting_CustomNavigator.Owner = “MUAC_CustomNavigator”;
setting_CustomNavigator.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
setting_CustomNavigator.Value = @”<add name=””MUAC_CustomNavigator”” siteMapFile=””_layouts/MUAC.sitemap”” type=””MUAC.SiteMapProvider.CustomNavigator, MUAC.SiteMapProvider, Version=, Culture=neutral, PublicKeyToken=02fc9494e4423234″” securityTrimmingEnabled=””true”” />”;


if (setting)
RemoveProperty(webApp, setting_CustomNavigator, “MUAC_CustomNavigator”);

catch (Exception exception)


In the code I created a method to add or delete a setting from the web.config.
When you activate your feature your web.config will look like this:


<addname=MUAC_CustomNavigatorsiteMapFile=_layouts/MUAC.sitemaptype=MUAC.SiteMapProvider.CustomNavigator, MUAC.SiteMapProvider, Version=, Culture=neutral, PublicKeyToken=02fc9494e4423234securityTrimmingEnabled=true />

Dont mind the type property yet, we will get back on this later.
The last thing to do is to modify your masterpage.
I downloaded a version of the v4.master, renamed it and then did the changes on the copy, which is in my case ‘MUAC.master’

You need to search in the masterpage for the ‘SharePoint:AspMenu’.
Right before this control you need to place the following line:

<asp:SiteMapDataSource ShowStartingNode=”False” SiteMapProvider=”MUACNavigationProvider” id=”MUACNavigationProvider” runat=”server”/>

and then you need to modify the ‘SharePoint:AspMenu’ control itself so it looks like this:

<asp:SiteMapDataSource ShowStartingNode=”False” SiteMapProvider=”MUACNavigationProvider” id=”MUACNavigationProvider” runat=”server”/>

You need to change the DataSourceId to the one you just added to your masterpage.
Also change the ‘MaximumDynamicDisplayLevels’ else you will not have submenu’s.
I you now save , publish… this master page in to your SharePoint and deploy this feature you will have your menu.

But you need to manually change your masterpage on all sites … , activate the publishing features on all sites…, deploy your masterpage…
This should be done automaticilly!
So we add a new feature site scoped, this feature will only deploy the masterpage.
To do so we need to add a new module to our solution I called it ‘MasterPage’.


Remove the sample file and add your masterpage (MUAC.master) to your module.
(Right Click add existing file and then search for your altered masterpage)
Open the the ‘Element.xml’ file and modify it so it looks like this:

<FileUrl=MUAC.masterType=GhostableInLibraryIgnoreIfAlreadyExists=TRUE >

This module is just deploying the masterpage.
To do so we add a new feature because this cannot be combined with our first feature because that one is not site scoped but webapplication scoped.
The feature looks like this:

We have now 2 features:

  • To deploy our custom sitemap
  • To deploy the masterpage

Next we want that the masterpage is automaticilly set so we do not have to change every sitecollection manually.
In ourr first feature I added 2 extra methods:

private void InstallMasterPage(SPWebApplication webApp)
foreach (SPSite site in webApp.Sites)
SPWeb topLevelSite = site.RootWeb;           // Calculate relative path to site from Web Application root.
string webAppRelativePath = topLevelSite.ServerRelativeUrl;
if (!webAppRelativePath.EndsWith(“/”))
webAppRelativePath += “/”;

// Activate publishing infrastructure
site.Features.Add(new Guid(“f6924d36-2fa8-4f0b-b16d-06b7250180fa”), true);

site.Features.Add(new Guid(“9e9d8436-3a78-4abd-a9d1-d49707ea2116”), true);
catch (Exception ex)

// Enumerate through each site and apply branding.
foreach (SPWeb web in site.AllWebs)
// Activate the publishing feature for all webs.
web.Features.Add(new Guid(“94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb”), true);
web.MasterUrl = webAppRelativePath + “_catalogs/masterpage/MUAC.master”;
web.CustomMasterUrl = webAppRelativePath + “_catalogs/masterpage/MUAC.master”;


private void UnInstallMasterPage(SPWebApplication webApp)
foreach (SPSite site in webApp.Sites)
SPWeb topLevelSite = site.RootWeb;

// Calculate relative path to site from Web Application root.
string webAppRelativePath = topLevelSite.ServerRelativeUrl;
if (!webAppRelativePath.EndsWith(“/”))
webAppRelativePath += “/”;

site.Features.Add(new Guid(“9e9d8436-3a78-4abd-a9d1-d49707ea2116”), true);

// Enumerate through each site and apply branding.
foreach (SPWeb subSite in site.AllWebs)
subSite.MasterUrl = webAppRelativePath + “_catalogs/masterpage/v4.master”;
subSite.CustomMasterUrl = webAppRelativePath + “_catalogs/masterpage/v4.master”;
subSite.SiteLogoUrl = string.Empty;
catch (Exception ex)


Add ‘InstallMasterPage ‘ in the feature activated and the ‘UnInstallMasterPage’ in the deactivation method.
So this will activate the feature that contains the masterpage if it is their, also activate the publishing features on every site and subsite.
And next it will set the masterpage, when you deactivate it will reverse the settings again.
It just loops through all sitecollections and changes the propery of the masterpage.

site.Features.Add(new Guid(“9e9d8436-3a78-4abd-a9d1-d49707ea2116”), true);
catch (Exception ex)

This piece will acctivate our other feature that holds the masterpage, your guid will properbly be different.
You can find it in the properties of the feature, the one that contains the masterpage.
So everything is almost finished, but to make sure our topnavigation bar is security trimmed we need to create our custom Navigator class,
which has a propery called ‘IsAccessibleToUser’ which we can override:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Navigation;
using System.Web;
using System.Xml;namespace MUAC.SiteMapProvider
public class CustomNavigator :XmlSiteMapProvider// SPXmlContentMapProvider
public override bool IsAccessibleToUser(HttpContext context, SiteMapNode node)
if (node == null)
throw new ArgumentNullException(“node”);
if (context == null)
throw new ArgumentNullException(“context”);
if (!base.SecurityTrimmingEnabled)
return true;
if (string.IsNullOrEmpty(node.Url))
return this.IsGranted(context, node.ChildNodes);
return this.IsGranted(context, node);
return false;

private bool IsGranted(HttpContext context, SiteMapNode node)
bool isGranted = false;
using (SPWeb web = new SPSite(SPContext.Current.Site.MakeFullUrl(node.Url)).OpenWeb())
SPUser user = web.AllUsers[context.User.Identity.Name];
if (user != null)
if ((node.Roles != null) && (node.Roles.Count > 0))
foreach (string str in node.Roles)
isGranted = (str == “*”) || (user.Groups[str] != null);
if (isGranted)

isGranted = web.DoesUserHavePermissions(user.LoginName, SPBasePermissions.EmptyMask | SPBasePermissions.ViewPages);

return isGranted;

private bool IsGranted(HttpContext context, SiteMapNodeCollection childNodes)
bool flag = false;
foreach (SiteMapNode node in childNodes)
flag = this.IsGranted(context, node);
if (flag)
return flag;
this.IsGranted(context, node.ChildNodes);
return false;

The code is not hard to understand so I’m not going to explain eveything.
But let’s look add the code of our first feature again where we added a provider into the web.config.
This provider needs to referr to this class and asssembly because we created our own Navigator.
The type property needs to referr to our class !!!

  <add name="MUAC_CustomNavigator" siteMapFile="_layouts/MUAC.sitemap"
 type="MUAC.SiteMapProvider.CustomNavigator, MUAC.SiteMapProvider, Version=, Culture=neutral, PublicKeyToken=02fc9494e4423234" securityTrimmingEnabled="true" />

When you now debug it should your class and checking if the user has access or not.

So that actually it, if you have questions or remarks let me know…

Write to people field

If you have a webpart or a custom form where you use the SharePoint peoplepicker you have to fetch the values of the control to place them into SharePoint.
This is how you do this.




When I press the save button on my form this code I need to use:

string[] userarray = ppTechnicalManager.CommaSeparatedAccounts.ToString().Split(‘,’);
SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();
for (int i = 0; i < userarray.Length; i++)
item [“Technical Manager”]= usercollection;      
public SPFieldUserValue ConvertLoginAccount(string userid)
SPFieldUserValue uservalue;
SPSite site = new SPSite(SPContext.Current.Site.Url);
SPWeb web = site.OpenWeb();
SPUser requireduser = web.EnsureUser(userid);
uservalue = new SPFieldUserValue(web, requireduser.ID, requireduser.LoginName);
return uservalue;

And now the values will be saved into your list.

If you wwant to retrieve those values from your listitem again and display this into you control:

SPFieldUser userField = (SPFieldUser)list.Fields.GetField(Fields.TechnicalManager);
SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(item[Fields.TechnicalManager].CheckForNull());
ArrayList entityArrayList = new ArrayList();
PickerEntity entity = new PickerEntity();
if (fieldValue.User != null)
SPUser user = fieldValue.User;
entity.Key = user.LoginName.ToString();
SPGroup group = SPContext.Current.Web.Groups[fieldValue.LookupValue];
entity.Key = group.LoginName.ToString();

This checks for groups and users.

Hope this helps

Deploy my WSP to a certain WebApplication and not Globally

Most often you want your customsolution to be deployed to only a specific webapplication but SharePoint won’t allow it.

It’s actually very easy to fix this by tricking SharePoint.


In your package manifest you add a safe control:

<Solution xmlns=””&gt;
<Assembly Location=”dll_name_of_your_solution.dll” DeploymentTarget=”GlobalAssemblyCache”>
             <SafeControl Assembly=”dll_name_of_your_solution,Version=,Culture=neutral, PublicKeyToken=****************” Namespace=”namespace_of_your_solution” TypeName=”*” />


JQuery into SharePoint

Most of you have already worked with jQuery, if you have not shame on you.
I have worked with jQuery a lot the past years, client site scripting gives you more flexibility towards your customers.
The way you can manipulate the DOM is just great.

Many people find it hard to start with jQuery, the first step of the process is to get your jQuery into SharePoint.
There are several ways of doing this which I’ll be explaining to you in this post.

First we have to download jQuery  here. Just save it somewhere so that you know were it is.

The ways that I know to import jQuery into SharePoint are the following:

  • Put a reference into your MasterPage
  • Put a reference in your webpart or your layouts page
  • Load it programmatic
  • Through the content editor webpart
  • With a feature

1. Put a reference to Jquery

You can tell your webpart, layouts page and master page to load the script directly.
Keep in mind if you do this in the MasterPage then everywhere in your SharePoint the jQuery is loaded.

This technique is the most simple of loading the jQuery.
You have to open SharePoint designer for this, and open the site where you want to place the jQuery.

Next thing you have to select ‘all files’ and then catalog.

Jquery SPS 001

Next you have to select your MasterPage en select ‘Edit file in advanced Mode’

Jquery SPS 002

Next you will see the HTML and stuff of your MasterPage , there we can place a link to the jQuery file.
We can link directly to the jQuery site

Jquery SPS 004

or to our local JQuery file , stored somewhere in the layouts folder of SharePoint in this case

Jsurty local file system  master page linked to layouts folder

Next you just save and publish the masterpage and your are done.

And how do I know that it worked ????
If you open your IE explorer en type F12 which will open the development tools of IE, you’ll see a tab called scripts.

Jquery SPS script loaded from LAyouts folder

Jquery SPS script loaded with direct link

Told you it was simple.
This technique can be repeated for a VisualWebPart or a Layouts page.
I’m not gonna show because it is just copying the same script tags
2. Load the script programmatic

Personally I prefer this way.
It’s easy, it’s faster, no SharePoint designer, Visual Studio and so on

When you’re using jQuery you are going to develop something, so you’ll be using VS anyway.
So you can deploy the jQuery along with your solution.
I’m just gonna create a very simple webpart to demonstrate.
My Visual Studio project looks like this:

vs 001

I added a link to the SharePoint Layouts/1033 folder in my Visual Studio, then I added the jQuery file which I downloaded earlier in this folder in Visual Studio.
The reason I placed it there is because SharePoint also put it’s JavaScript files there.
Now let’s add this thing into our WebPart, but lets test this.
Lets create a simple “HelloWorld.js” that throws an alert when the page is loaded, and put this also in the 1033 folder.

vs 003

Then you deploy the webpart and add it to your page, now every time the page is loaded it will throw an alert.

vs 004

Using this techniques you do not have to open SharePoint designer every time you have to add a jQuery file.
To my point of view this techniques gives you way more flexibility.

3. Content Editor WebPart

This is the most simple technique there is.
Just edit the page add add a CEW.

Edit the webpart and just add this in the text:

// <![CDATA[
javascript” src=””&gt;
// ]]>


Click ‘ok’ and you are done.
I find this more unprofessional but it would do the trick, but there are risks to it.

4. Using a feature

This is also a very simple technique to load the general jQuery files into SharePoint.

Add to your solution a new Module.
Delete the txt file that comes with the Module, and change the content of the Element.xml file to look like this:

feature Jquery 001

In the screenshot you’ll see I have put the Module into a feature and that is it.
Go to your feature in SharePoint and activate

feature Jquery 002

You can test with the development tools to check if the feature is deactivated and deactivated.

Hope it helps.

Leave a comment


Convert SharePoint 2010 Solution to 2013 and Visual Studio 2012

Serveral times I had opened a project developed for SharePoint 2010 and I needed to make some changes for instance to make it work in Sharepoint 2013.

When you open it you will receive some problems regarding your dll references, what the hell ???

The solution for this is to make some changes in the xxx.proj file.

I was able to get my solution upgraded from a 2010 project to 2013 using the following.

Note that this will update your solution to use the new 2013 API.
First edit your .csproj file (for c#).

Modify the target framework to this:


Add this a node for the office version, I put mine directly below the TargetFrameworkVersion tag


Update references
Reload the project and update your referenced assemblies.
If you haven’t specified a specific version they should already be referencing the v15 (SharePoint 2013) assemblies.

Do a find replace for to This updates any references on your pages, layouts, and master pages to the v15 assemblies.

Hope it helps !

Create an extra group on your site settings

This is something I created in 2007 but it is still usefull for 2010

First you need to set up your base project. If you don’t know how check out the other Blog. You just create a new C# ClassLibrary and add the necessary folder, they should look like your 12 folder of SharePoint

It should something like this. Add two XML files underneath the folder, like showed here above. To The feature XML add the following code

<Feature xmlns=""
         Description="Site Iformation tool"
         Title="Site Information"
        <ElementManifest Location="elements.xml"/>

Let me explain the code:

  • The first line give an ID to your feature which is logic, cause every feature needs to have an unique ID.
  • Title , where you define the Title of your feature.
  • Description , you give a description to your feature.
  • Version, if you want to apply versioning on your feature.
  • Hidden, this can have two value “TRUE” or “FALSE”, is you set the value to “TRUIE” you will not be able to see the feature in your ‘Site Feature’ on your website.
  • Scope, this can have four values site,Farm ,WebAplications,Site and Web, this value will determine on which level your will deploy your feature.
  • ElementManifest ,within these brackets you will add certain files to your feature, it define the elements of your feature, a feature can be ANYTHING, a workflow, a menu an list, a custom field ,…

To The element XML add the following code

<Elements xmlns="">
        Title ="Extra Admin Options"
        Title="Extra Site Information"
        <UrlAction Url="/_layouts/SITEINFORMATION/SiteInformation.aspx"/>

Let me explain the code:

  • CustomActionGroup, here you define a group to which your action belongs to.
  • Id= Each group needs to have an ID.
  • Location=”Microsoft.SharePoint.SiteSettings” , this is where your group is located
  • CustomAction, you you see that you are going to add a new action group to your site
  • ID , every action needs to have an ID
  • Description, add a description
  • Title, you can give a title to your custom action
  • GroupID, this is actually the most important property. Where you are going to define where your ‘Action’ will be added. In our case it’s the name of the group we have created.
  • ImageUrl, here you can define which icon you’ll see before your feature.This is sorted also in the virtual file system,you can use your explorer to go your 12 folder, and check in the map “_layouts/images” there you’ll find all the images that are used within SharePoint , you can paste your images in there, although here I just use a standard one and paste in my, which is not needed BUT recommended.
  • UrlAction , where you define the action of your feature, I think if you click on your feature you want something to happen, in his case our link will go to the SiteInformation.aspx, which is a custom page, but you an like it to everywhere.

NOTE : The location is in our case “Microsoft.SharePoint.SiteSettings”, if your groudId is different your location can be Different. You can check these thing in your virtual file system. Or you can visit this site SharePoint Custom Action Identifiers.
I hope this blog was usefully, if so please spread the word.