Category: Microsoft

Useful JavaScript to know when working with SharePoint Display Templates

This post has some really great examples for JavaScript helper methods and available properties for working with Display Templates in SharePoint 2013.

If you ever had to decide if your script is running on a SharePoint Foundation, use this one:

// Determine if the host is SharePoint Foundation
if (!Srch.U.isSPFSKU()) { }

SharePoint App Deployment fails

Visual Studio does not tell you much if an app deployment fails.


Fortunately SharePoint will log more information about the problem that occurred during the app deployment in the ULS-Log.

So if you run into the “There were deployment errors.” exception, take a look at the ULS-Log. In this particular case SharePoint didn’t like my JavaScript:

App Packaging: CreatePackage: Unexpected exception: There were errors when validating the App package: There were errors when validating the App Package. Other warnings / errors associated with this exception:  Custom action urls must start with "http:", "https:", "~appWebUrl" or "~remoteAppUrl".  The url "javascript:DoSomething();" is not in the right format.

Always to remember to look at the logfiles, if you have exceptions. They often contain more information 🙂

The solution for warming up SharePoint

Most SharePoint Farms will have a solution for the long loading time after an Application Pool recycle or iisreset running. There are many different ways to preload websites, so your users have faster load times. So why another solution?

There are some questions, that I think have not been dealt with before:

  • Most solutions require some sort of Timer to be started (e.g. a Scheduled Task)
  • When should the warmup occur?
  • What about multiple WebFrontend Servers?
  • How about Claims support?
  • Which URLs have to be called? What about extended WebApplications?
  • New WebApplications require the warmup tool to be adjusted
  • Manuell warmup after Deployments
  • What about search?
  • Did the Farm warmup correctly?

Years ago I developed a console application, which warms up SharePoint by calling each Site within a SiteCollection. It has bee updated multiple times with new features.

Basis of the new solution still is the “old” application. It has been integrated into the SharePoint Central Administration and the SharePoint Timer job. That way it can be configured through an Application Page and is executed by the SharePoint Timer on each WebFrontend Server. The Solution has been tested with SharePoint 2010 and 2013.

A Custom Action displays a new link within the “Monitoring” Section of the Central Administration.


All WebApplications are listed, and can be configured separately. The time the Application Pools recycles is read from IIS and will be set as default time (+ 1 minute). That way you can assure fast pages even shortly after the daily recycle.


A manual warmup can be started through the Timerjob page, or by downloading and executing a batch file (has be be executed on each farm server).

If you select to write to the EventLog, each execution of a job will write a summary to the Application Log. If all Websites could be loaded without a problem, the Event ID will be 0. Otherwise 1.


The tool supports Claims WebApplications with Windows Authentication.

The download package contains two WSPs. One for a SharePoint 2010 farm, and the other for 2013.

Download: Download WSP Packages, Sources

Update November 11, 2014

  • Please restart the SharePoint Timer service on all farmservers after intalling the solution

Building a Visual Studio project for SP2010/SP2013 (.NET 3.5/4.0)

In this post I will show you how you can use MSBuild to target your project for .NET 3.5 or .NET 4.0 and use a separate app.config file for each.

My Warmup Tool is supposed to work with SP2010 and SP2013. To achieve that compatibility, I have to change the TargetFramework of the project to be able to compile, as well as the app.config so the application uses the desired Framework. I didn’t want to change the values every time manually. An automated solution has to be possible. And it is. Some little changes to the project file and MSBuild will do all the work for you 🙂

So lets look into the default .csproj file, which sets the TargetFramework and references the app.config.

  1: <?xml version="1.0" encoding="utf-8"?>
  2: <Project DefaultTargets="Build" xmlns="http://..." ToolsVersion="4.0">
  3:   <PropertyGroup>
  4:     <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
  5:     <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
  6:     ...
  7:     <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  8:   ...
  9:   </PropertyGroup>

The version has to be exchanged, because SharePoint 2013 uses the .NET Runtime 4, but SP 2010 the Version 2. Trying to build the project with the wrong Target Framework will fail. The referenced SharePoint Assemblies depend on the correct Framework Version.

An easy way to specify the value depending on a condition, is to use the Constants, you can define on the build page within the project settings.


I use “SP2010” and “SP2013”, which can be used by MSBuild. You can change that value any time. Reloading the project is not necessary, as the Build-process picks up the value when it needs it.

Let’s get back to the TargetFramework. Switching the version depending a constant defined (“SP2013” in my case) is done with two new property groups in the csproj file of your project. I’ve included the lines below the debug/release Property Groups, because the DefineConstants property is defined there.

  1: <PropertyGroup Condition=" $(DefineConstants.Contains('SP2010')) ">
  2:   <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  3: </PropertyGroup>
  4: <PropertyGroup Condition=" $(DefineConstants.Contains('SP2013')) ">
  5:   <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  6: </PropertyGroup>

Remove the default entry, which is the one you see on line 7 of the previous code fragment above.

Now we are set up, and may compile the project for .NET 3.5 and .NET 4.0. Great. To have the application config include the supportedRuntime version as well, I’ve included two config files into my project.


The files are identical, except the value of the supportedRuntime, which is v2.0.50727 for .NET 3.5 and v4.0.30319 for .NET 4.0. Again MSBuild is your friend for using one or the other file depending the previously used constant “SP2010” or “SP2013”.



The switching condition can be specified like this:

  1: <ItemGroup Condition="$(DefineConstants.Contains('SP2010'))">
  2:   <None Include="Config\2010\app.config" />
  3: </ItemGroup>
  4: <ItemGroup Condition="$(DefineConstants.Contains('SP2013'))">
  5:   <None Include="Config\2013\app.config" />
  6: </ItemGroup>

The default entry for including the root-level app.config file has been removed from the csproj file.

As a result of the effort, I can build my console application for SharePoint 2010 and SharePoint 2013 by switching the constant in the project settings. The corresponding app.config file is used as well.

Speed up SharePoint Update Installation

Installing Updates for SharePoint 2013 will take a long time, if you don’t disable some services prior starting the update process by executing the hotfix exe file. To simplify the installation, and speeding it up, you can use a PowerShell script to stop the necessary services, and start the update.

You need to copy the code, and save it as e.g. Install_SharePoint_Update.ps1 in the same folder as the exe file. Start the script from the “SharePoint Management Shell”. It will take care of the services for you.

Btw: You can start the script with PowerShell on a remote path. No need to copy the update file to your SharePoint Servers 🙂

SQL Access to Configuration DB required

In many cases you pass an URL string to connect to SharePoint. In my case I wanted to verify the URL by using this code:

  1: Uri requestUri;
  2: if (!Uri.TryCreate(absoluteUrl, UriKind.Absolute, out requestUri))
  3:   throw new ArgumentException(absoluteUrl + " is no a valid URL.");
  5: SPWebApplication webApplication = SPWebApplication.Lookup(requestUri);

And here comes the “but”. I did not know that the account, which is executing the code, needs permissions to the Configuration Database!

So either grant permissions, or use something like this:

  1: using (var site = new SPSite(requestUri.AbsoluteUri))
  2: {
  3:   SPWebApplication webApplication = site.WebApplication;
  4: }

Happy SharePointing…

When a Feature gets installed

Have you ever thought about the Features folder and when a folder will be created for one of you features? Well, I did 🙂

Why is this relevant, anyway? To be able to activate a feature on a given scope, it has to be installed first. That’s why.

Action Result
stsadm -o addsolution The solution is added to the farm. Features are not available
stsadm -o deploysolution Feature folders are created and the Features are available for activation
stsadm -o installfeature A feature with ID xyz has already been installed in this farm.  Use the force attribute to explicitly re-install the feature.

Great. After deploying the solution, the feature is automatically installed and can be used. I did expect this, because installing a feature is a rather uncommon task.

Here comes another one. What if you add a feature to an existing – and deployed solution – and perform an upgrade?

Action Result
stsadm -o upgradesolution Adds the new feature folder
stsadm -o activatefeature Feature with Id ‘4520d607-699b-4025-b605-5f988c97b368’ is not installed in this farm, and cannot be added to this scope.

Ups. Did you expect the result? The feature has to be installed first!


If you add a feature to a solution, make sure the features gets installed prior usage! There are two ways

  1. Install the new feature
  2. Retract and Redeploy the solution

CKS – Dev for Visual Studio 2012 and 2013

The new release brings support for Visual Studio 2013 🙂

The CKS – Development Tools Edition for Visual Studio 2012 and 2013 is a collection of Visual Studio templates, Server Explorer extensions and tools providing accelerated SharePoint 2010/2013 development based on Microsoft’s SharePoint 2010/2013 development tools.

Activating Features after Solution Deployment via VS

Visual Studio allow a F5 Deployment. I guess you all know that. The part where you have to think carefully is, when you add Features to your project.

Should you activate “Activate On Default”? Well, it depends (as always). Usually I don’t enable that setting, because features tend to be activated on scopes you won’t expect.

The problem

Take a WebApplication scoped feature for example. It might create SafeControl entries for your controls. Do you really want them to be added to an Extranet WebApplication if your solution is solely for an Intranet Application?

The problem does not exist for you, if you auto activate your features and have set your deployment configuration to “Default”. But in my case, I use “No Activation” and “Activate On Default = false” most of the time. Then, after you deploy an update of your solution, SharePoint retracts and re-adds the solution. The consequence is a deactivate feature 🙂 (in case of Farm and WebApplication scoped features).

My solution

CKS rocks! What’s that have to do with this?

The CKS Extensions for Visual Studio ( can Update the solution like you would do via PowerShell or stsadm with a new Deployment option named “Upgrade Solution (CKSDev)”.


Unfortunately CKS isn’t available for Visual Studio 2013 preview. So I had to do something else to avoid the problem with non activated features after deployment.

Fortunately Microsoft provided some Command Line action for post-deployment. And since the SharePoint URL is known from the properties of the project, it can be used via variable $(SharePointSiteUrl). Combined with stsadm to activate the feature, I had all I needed.


So for now, Deployment from VS will work again 🙂

SPQuery for my tasks

Developing solution with multiple languages (or a language which is not English) sometimes can be a bit painful. To configure a Webpart to display only my tasks, I would filter for [Me] or [Ich].


To achieve the same via code / CAML, you can filter by UserID and not the string “Me”.

  1: <Where>
  2:   <Eq>
  3:     <FieldRef Name="AssignedTo" />
  4:     <Value Type="Integer">
  5:       <UserID />
  6:     </Value>
  7:   </Eq>
  8: </Where>
  9: <OrderBy>
 10:   <FieldRef Name="Status" />
 11:   <FieldRef Name="Priority" />
 12: </OrderBy>

This is just a reminder for me, so I can find the information more quickly. But maybe this is useful for some of you as well 🙂

Do long running operations on SPListItem creation

Events on SPListItems like ItemAdding or ItemAdded are nothing new. Many of you have already used them. Recently I had a requirement to create a new SPSite, when an item in a list has been created. So an ItemReceiver was my choice.

But the customer wants something special 🙂 During the creation process, which takes some seconds, the user should see a loading animation.


Here comes the problem. The ItemEventReceiver is running in the background, and has no knowledge about the GUI process. Well, at least if it is running asynchronous. A very good explanation can be found here: Using synchronous “after” events (e.g. ItemUpdated) in SharePoint 2010.

The short summary: If you use synchronous events, they get executed in the same thread and you have the HttpContext and SPContext!

You already tried this and didn’t have the context objects?



Here comes the trick…


Grab the objects in the constructor, store them and use later when you need them.

private SPContext _spContext;
private HttpContext _httpContext;
public EventReceiver()
	_spContext = SPContext.Current;
	_httpContext = HttpContext.Current;

public override void ItemAdded(SPItemEventProperties properties)
		if (_spContext == null)
			// item has been created via code from timerjob. no context and no need to redirect

		string url = SPUrlUtility.CombineUrl(_spContext.Web.ServerRelativeUrl, "_layouts...") + properties.ListItemId;
	catch (ThreadAbortException e)
		// occures if redirected

Ok. We’ve successfully redirected to another page in our creation page, which can be a modal dialog or full frame page. I’ve not been able to use the Page to start a SPLongOperation with. A NullReference Exception has been thrown. So my solution was another Layouts-Page, which then starts the SPLongOperation. When it is done, the Layouts-Page is closed. By closing it, the modal dialog from the Item Creation process also vanishes.

I’ve chosen the ItemAdded and not ItemAdding event, because ItemAdding did not like the redirect. The item did not get created.

The Layouts-Page uses SPLongOperation e.g. in CreateChildControls.

using (var longRunning = new SPLongOperation(Page))
   // do your long running operation here
   longRunning.End(null, SPRedirectFlags.Default, Context, null,
      "window.frameElement.commonModalDialogClose(1, null);");

After the operation has been executed, the SPLongOperation is ended and a script passed as last parameter in the End() method is executed. You don’t need script tags here.

To register the ItemEventReceiver to execute synchronously, use the following code.

SPList list = ...

// attach EventReceiver
var receiverDefinition = list.EventReceivers.Add();
receiverDefinition.Type = SPEventReceiverType.ItemAdded;
receiverDefinition.Assembly = "yourAssemblyFullName";
receiverDefinition.Class = "Your EventReceiver class (incl. namespace)";
receiverDefinition.Synchronization = SPEventReceiverSynchronization.Synchronous;


Basically that’s it. A combination of known tasks to create a new solution.


You can show a work-in-progress dialog to a user, when a new SPListItem is created. Here are the steps:

  1. Use a synchronous asynchronous event 🙂
  2. Redirect to a Layouts-Page
  3. Use the SPLongOperation class to do your work
  4. Have fun and happy customers

CKS – Dev for Visual Studio 2012

The Tools have been released for VS 2012. Great!

The CKS – Development Tools Edition for Visual Studio 2012 is a collection of Visual Studio templates, Server Explorer extensions and tools providing accelerated SharePoint 2010/2013 development based on Microsoft’s SharePoint 2010/2013 development tools.

The current 1.0 release includes the following features:

  • Server Exploration from CKSDev 2010 v2.4 – Visual Studio 2012 version of the Visual Studio 2010 exploration. Includes all the existing server explorer features.
  • Quick Deploy extensions from CKSDev 2010 v2.4 – Visual Studio 2012 version of the Visual Studio 2010 quick deploy. Includes all the existing quick deploy features.

About the Community Kit for SharePoint

The Community Kit for SharePoint is a set of editions, components, tools and recommended documentation for SharePoint development. You are currently viewing the edition project site for the Development Tools Edition. To learn about the other editions and components you can go to

You can read more and download the tools here:

A CodePlex page also exists:

Now Available: Office Developer Tools for Visual Studio 2012

Finally! Now Available: Office Developer Tools for Visual Studio 2012

There are some points to mention, where the final release of the tools differ from previous preview releases:

  • validation experience that helps you to find and fix common errors prior to submitting your apps to the Office Store
  • A continuous integration workflow
  • Windows Azure cloud service projects for creating provider-hosted Apps
  • A dramatically improved Workflow designer

The download link:

SharePoint Konferenz im März, ich bin dabei

SharePoint konferenz - Alles zu MOSS 2007 und Microsoft SharePoint 2010!

Im März ist wieder SharePoint Konferenz Termin. Ich werden mit zwei Vorträgen dabei sein.



SharePoint 2013 und Social. Was ist neu, was kann man machen?

Enterprise-Lösungen mit Business Connectivity Services

Nach der BASTA 2012, BASTA Spring 2012, BASTA 2011, BASTA 2010, BASTA 2009 und den SharePoint Konferenzen 2010, 2009 ist das mein 7. Auftritt als Speaker.

Cool. Es macht ja auch jedes mal aufs Neue Spaß 🙂

Using .NET 4 with SharePoint 2013

A while ago, I wrote an article about performing operations parallel with SharePoint 2010 (.NET 3.5). –> Execute code in multiple threads (even with SharePoint)

Since I am not the only guy with this kind of “problems”, others are writing about SharePoint and .NET. Especially .NET 4.5 and SharePoint 2013.

Stephane Eyskens hat posted a nice 6-post series about .NET within SharePoint 2013.

If you stumble across more great resources, please leave a comment.

Getting an “Object reference not set to an instance of an object” when accessing the User Profile Service via Code

This is one of the posts which shall remind me about something. And may help others as well.

Coding against the User "Profile Service Application requires Connection Permissions for the executing user account!

From the beginning. I wrote a console application which leverages the User Profile Store. Every time I created a new instance of the UserProfileConfigManager class, an exception was thrown:

Object reference not set to an instance of an object

at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.get_ApplicationProperties()
at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.get_ILMMachineName()
at Microsoft.Office.Server.UserProfiles.UserProfileConfigManager.Initialize(UserProfileApplicationProxy userProfileApplicationProxy, Guid partitionID)
at Microsoft.Office.Server.UserProfiles.UserProfileConfigManager..ctor(SPServiceContext serviceContext)
at ITaCS.UserProfileManager.GetUserProfileServer() in D:\Data\Development\tfs02\ITaCS\Components\UserProfileProperties\UserProfileProperties\UserProfileManager.cs:line 49

Fiddling with Reflector and creating the object with Reflection didn’t help. The solution was much easier. Just grant the executing account, which was my user who executes the console application, Connection Permissions to the User Profile Store Service Application (UPS).



That’s it.

One other thing. If you are running your SharePoint with local accounts, you might not be able to verify a domain account. In that case, you can tell the people picker to use a domain account instead of the service account (which is a local account and does not have permissions in the active directory). See Configure People Picker (SharePoint Server 2010) and  Multi Forest/Cross Forest People Picker peoplepicker-searchadcustomquery.