Posts Tagged ‘SPS’

Author: Tobias Zimmergren | | @zimmergren 


I’ve been getting some questions lately about modifications to web.config files and SharePoint 2010 – is it possible to automate so that the administrator don’t have to manually edit those files on each WFE?

Yes, that’s the easy answer. This was possible in SharePoint 2007 as well.

In this article I’ll quickly demonstrate how you (using a Web Application feature) can make modifications to web.config automatically.

Please note that this is just a getting-started point which you’ll have to work deeper into to tweak it to your likings for updates and removals from the web.config file.

Automatic web.config changes using a SharePoint 2010 feature

Basically, if you want to get some type of change into the web.config, it oftentimes has to do with adding custom settings or values that you’ll later reference in your applications.

In this scenario, we’ll add the following key into web.config using a Feature Receiver, so we don’t have to do it manually after/before deploying our solutions:

 <add key= "isAwesome " value= "1 " />

So, in order to achieve this programmatically without actually editing the web.config by hand – you could utilize the class called SPWebConfigModification something like this:

 public  override  void  FeatureActivated(SPFeatureReceiverProperties  properties)
     var  value = 1; // We want to set the key isAwesome to the value "1" 

     var  webApp = properties.Feature.Parent as  SPWebApplication ;
     var  mySetting = new  SPWebConfigModification 
         Path = "configuration/appSettings",
         Name = string.Format("add [@key='isAwesome'] [@value='{0}']", value),
         Sequence = 0,
         Owner = "Zimmergren.SP2010.WebConfigModifications.Awesomeness",
         Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
         Value = string.Format("<add key='isAwesome' value='{0}' />", value)


By executing this cute snippet of code you will actually add the setting called isAwesome to the web.config of your web application. (This will be persisted to all the WFE’s of course).

Please note: You will need to tweak your code quite a lot to make the sweet SPWebConfigModification class behave the way you want on activation/deactivation of the feature. This should at least give you a starting point :-)


In this short introductory article about web.config modifications I’ve talked a bit about how you can automate the process of altering your web.config files without actually opening them on the file system.
Nothing fancy, but a good starting point for those of you who requested some info on the topic.


Author: Tobias Zimmergren | | @zimmergren


In SharePoint 2010, you’ve got some new capabilities for error reporting and logs. One of the most noted features for me as a developer is that whenever you bump into an error message – you’ll be presented with a correlation ID token.

In this article I will try to explain how you can fetch that token from SharePoint, and also provide a small snippet of code to be able to build your own “Log Searcher Web Part” for your administrators.

Correlation ID, what’s that?

In SharePoint 2010, you get a Correlation ID (which is a GUID) attached to your logs/error messages when something happens. This ID can then be used to lookup that specific error from the logs.

This Correlation ID is used per request-session in SharePoint 2010, and if you are in the process of requesting some information from SharePoint and bump into some problems along the way – your Correlation ID will be the best starting point for searching for what went wrong along that request!

You might get an error message like this in SharePoint 2010 (don’t worry, if you haven’t seen one like this one yet – just hang in there, sooner or later you will.. Winking smile)


Search for the log messages based on the Correlation ID token

So if you’ve gotten such an error message and want to find out more information about the actual error and don’t have the time to go around poking in the logs and searching – there’s a few methods you can do this rather easily, as described below.

Using PowerShell to lookup a log message based on Correlation ID token

One of the quick-n-awesome ways to do this is to simply hook up a PowerShell console (SharePoint 2010 Management Shell) and then just write the following command (replace the <GUID> with the Correlation Id):

get-splogevent | ?{$_Correlation -eq "<GUID>" }

This will give you the details about your specific error like this in the console:


You might want to be more precise and get more specific details out of your query, then you can try something like this:

get-splogevent | ?{$_.Correlation -eq "<GUID>"} | select Area, Category, Level, EventID, Message | Format-List

This will give you the details about your specific error like this with some juicy details:


Finally if you would want these messages to be put into a text or log file instead, you could just add the classic “> C:Awesome.log” after the command like this:

get-splogevent | ?{$_.Correlation -eq "<GUID>"} | select Area, Category, Level, EventID, Message | Format-List > C:Awesome.log


On MSDN they have an overvoew of using SP-GetLogEvent which I would recommend!

Using SQL queries to find log message based on Correlation ID token

You can utilize the SQL logs database to fetch the specific error message based on Correlation id as well. In your logging DB (usually called WSS_Logging, but can be called something else if you’ve changed it) there is a view called ULSTraceLog which you can query with a simple SQL query and fetch the results.

I’ve created a query to fetch the items from the logging database like this:

 select 	[RowCreatedTime],  [ProcessName],  [Area],  
 		[Category],  EventID,  [Message] 
 from  [WSS_UsageApplication].[dbo].[ULSTraceLog] 
 where  CorrelationId=< pre>'B4BBAC41-27C7-4B3A-AE33-4192B6C1E2C5'

This will render your results in the SQL Query window like this:


This can of course be implemented in a Web Part for your convenience as well (I’ve created a bunch of diag. and logging web parts that I’ve got deployed to Central Admin) that could look like this (this way you don’t need physical access to the ULS logs all the time, but can do a quick lookup from the web part):


Get the current Correlation ID by using code

I got this piece of code from my good friend Wictor’s blog post. Thanks Wictor – this made my Logging-project more satisfying!

With the following code you can fetch the current Correlation Id of a request.

Create a method (in my case called GetCurrentCorrelationToken()) to wrap up the functionality of returning the current token like this:

 public  class  CorrelationId 
     [DllImport ("advapi32.dll")]
     public  static  extern  uint  EventActivityIdControl(uint  controlCode,ref  Guid  activityId);
     public  const  uint  EVENT_ACTIVITY_CTRL_GET_ID = 1;

     public  static  Guid  GetCurrentCorrelationToken()
         Guid  g = Guid .Empty;
         EventActivityIdControl(EVENT_ACTIVITY_CTRL_GET_ID, ref  g);
         return  g;

Then from wherever in your code you can simply call it by using this approach:

 protected  void  Button1_Click(object  sender, EventArgs  e)
     Label1.Text = CorrelationId .GetCurrentCorrelationToken().ToString();

(Normally you might want this in a try/catch statement or something like that)



This article should give you (administrator and developer) an insight in how you easily can track the specific errors your users encounter in their/your application(s). If a user gets an error message in SharePoint 2010, they’ll also see the Correlation ID.

If you can train your users to write down that Correlation ID along with a few simple steps on how the error might have been occurring, you’re going to have a much easier way to find the details about that specific error than ever before.


Author: Tobias Zimmergren | | @zimmergren 


In SharePoint 2010, there is a new Service Application called Word Automation Services. This Service Application is used to convert documents from Word to different formats.

Word Automation Services can open about the same formats as Windows Word 2010 can:

  • Filetypes it can open include:
    .docx, .docm, .dotx, .dotm, .doc, .dot, .rtf, .mht, .mhtml, .xml (Word xml)

  • Filetypes it can save as include:
    .docx, .docm, .dotx, .dotm, .doc, .dot, .rtf, .mht, .mhtml, .xml (Word xml), PDF, XPS

In this article you’ll see an example of how you can utilize the Word Automation Services in order to build a custom solution that takes care of converting documents (as listed above) into PDF documents.

Programmatically work with Word Automation Services in SP 2010

Note: You cannot deploy a solution working with the API’s in the Word Automation Services in the Sandbox. Rather you’ll need to target your application as a Farm Solution.

There’s not really a whole lot to it. Just follow along with these few steps and you’ll be fine!

In the API for Word Automation Services you’ll find a few different ways to convert documents including:

In the following example I’ll demonstrate how to use the AddLibrary() method in order to convert the contents of an entire document library into PDF documents! (Yes, that is way awesome)

1. Add the Word Automation Services API reference to your project

The following reference needs to be added to your project:

It can be found here:

2. Add the proper using-statements

 using  Microsoft.Office.Word.Server.Service;
 using  Microsoft.Office.Word.Server.Conversions;

3. Create a job to convert an entire Document Library to PDF’s

First, fetch the WordServiceApplicationProxy object (so we don’t have to hard-code the service app name..). This first line requires the Word Automation Service Application to be added to the default proxy group.

Second, we instantiate a new ConversionJob class and shoots in your WordServiceApplicationProxy as a parameter:

 var  wordAutomationProxy = 
     (WordServiceApplicationProxy )
     SPServiceContext .Current.GetDefaultProxy(typeof  (WordServiceApplicationProxy ));
 var  conversionJob = new  ConversionJob (wordAutomationProxy);

Next we need to specify a UserToken for the job to tell the job under what credentials to run.
We also need to specify a
name for the job.
Finally you can add whatever
Settings you want for your job, I’ve chosen that I want my files to be output as PDF’s.

 conversionJob.UserToken = SPContext .Current.Web.CurrentUser.UserToken;
 conversionJob.Name = "Zimmergren.SP2010.WordAutomationDemo Conversion Job" ;
 conversionJob.Settings.OutputFormat = SaveFormat .PDF;

Next we will simply specify a library where the original .doc or .docx files reside and point out the destination library like this, and start the job by adding it to the timer job queue:

 conversionJob.AddLibrary(origLib, destinationLib);

This is the sample code in one snippet

 protected  void  btnConvert_Click(object  sender, EventArgs  e)
         SPList  origLib = SPContext .Current.Web.Lists[ddlLibraries.SelectedValue];
         SPList  destinationLib = SPContext .Current.Web.Lists["PDFLibrary" ];

         var  wordAutomationProxy = 
             (WordServiceApplicationProxy )
             SPServiceContext .Current.GetDefaultProxy(typeof  (WordServiceApplicationProxy ));
         var  conversionJob = new  ConversionJob (wordAutomationProxy);

         conversionJob.UserToken = SPContext .Current.Web.CurrentUser.UserToken;
         conversionJob.Name = "Zimmergren.SP2010.WordAutomationDemo Conversion Job" ;
         conversionJob.Settings.OutputFormat = SaveFormat .PDF;

         conversionJob.AddLibrary(origLib, destinationLib);

         Label1.Text = "Conversion job started!" ;
         Label1.Visible = true ;
     catch (Exception  ex)
         Label1.Visible = true ;
         Label1.Text = "Error:<br/>" ;
         Label1.Text += ex.Message;

So what’s the results?

When you’ve created a new ConversionJob, it’ll be added to the Timer Job schedule to be run by SharePoint. When the job has been run, it can look like this:

Original Document Library, filled with some Word documents:

These files will then be converted to PDF’s and put into my PDFLibrary like this:


To get started with the Word Automation Services, you don’t really need to do a lot of coding. Just specify the references, hook up a reference to your service app and create a new ConversionJob and you’re up and running.

This article demonstrated how to convert an entire library of documents to PDF’s with a single click.

Awesome. Enjoy!

Author: Tobias Zimmergren | | @zimmergren


One of the coolest new set of functionality for SharePoint 2010 is the Taxonomies (Term Store, Term Sets, Terms) that you can easily create using the amazing Managed Metadata Manager service application.

In this article I’ll talk briefly about how you can utilize the SharePoint API to programmatically work with Taxonomies and create terms and fetch the terms in your term store. This should give you some nice ideas on how to get going!

A simple example of a taxonomy

Let’s say we’ve got a taxonomy worked out and implemented in SharePoint. It could look something like this (I’m using some made up samples below):


So, if you’ve got a taxonomy configured in your Managed Metadata Service Application, you can work with those programmatically – and that’s what this little tip is about.

Work with the taxonomy API’s programmatically in SP 2010

In this article I will talk about some of the basics to get started with taxonomies in SharePoint 2010 programmatically. First, of course, we need to create a new project and add the references for the Taxonomy API.

Preparing for development

First of all, create a new project (In my case, I chose to create a Visual Web Part project).

You’ll need to add the following reference to your project:


You’ll find this reference here:
C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPIMicrosoft.SharePoint.Taxonomy.dll


So, the first thing we would like to do is to learn how we can read the taxonomies we’ve got in our store. To do this, we utilize Microsoft.SharePoint.Taxonomy.

There’s a few good-to-know classes in this namespace that we’re going to work with:

The above classes are stated in their hierarchically correct order, meaning means that you start out with the TaxonomySession which contains the TermStore, which contains the Groups.. and so on.

Reading the Metadata store (Managed Metadata Service) programmatically

Sample code from my Visual Web Part’s user control (I have a control called tvMetadataTree in the user control):

     public  partial  class  TaxonomyWebPartUserControl  : UserControl 
         protected  void  Page_Load(object  sender, EventArgs  e)
             SPSite  thisSite = SPContext .Current.Site;
             TaxonomySession  session = new  TaxonomySession (thisSite);

             TreeNode  treeNode = new  TreeNode ();
             treeNode.Text = "Metadata Awesomeness" ;

             foreach (TermStore  termStore in  session.TermStores)
                 var  tsNode = new  TreeNode (termStore.Name, null , null , "" , null );
                 //treeNode = tsNode; 

                 foreach (Group  group in  termStore.Groups)
                     var  node = new  TreeNode (group.Name, null , null , "" , null );
                     //treeNode = node; 
                     foreach (TermSet  termSet in  group.TermSets)
                         node = new  TreeNode (termSet.Name, null , null , "" , null );
                         treeNode = node;

                         foreach (Term  term in  termSet.Terms)
                             AddTermSet(term, treeNode);

         void  AddTermSet(Term  term, TreeNode  treeNode)
             var  node = new  TreeNode (term.Name, null , null , "" , null );
             treeNode = node;

             foreach  (Term  t in  term.Terms)
                 AddTermSet(t, treeNode);

The end result will be a simple TreeView control filled with the Metadata structure from the store, looking something like this:


That’s about what you would need to get started with this!


Alright, so I wrote this small article up due to some students asked me for some taxonomy sample code a while back. I hope everyone enjoys this tip on how to programmatically work with the Taxonomies in SharePoint Server 2010!

As always, enjoy!

Author: Tobias Zimmergren | | @zimmergren


In this article I will talk about how you can create your custom Document ID provider for your SharePoint Server 2010 installation. Sometimes I’ve been getting the question weather or not it’s possible to change the behavior or change the way the Document ID’s are generated, and some people have a tendency to say no to that question, just because there’s no interface or out of the box functionality to do so.

I’ll give you a quick walkthrough of how you can extend your Site Collection by adding a custom Document ID provider, that will automatically generate custom ID’s based  on your own algorithms entirely!

Recommended reading about Document ID’s before proceeding:

Document ID overview

This section will give you a very brief conceptual overview of Document ID’s in SharePoint Server 2010.

What is Document ID’s?

Document ID’s in SharePoint Server 2010 provide you with the ability to tag documents with a unique identification number. Something a lot of my clients have done manually or by implementing custom solutions to take care of in SharePoint 2007. With this new feature, you get all the required functionality to tag documents with unique identification numbers based on a specific pre-set formula with a custom prefix.

See this sample screenshot for an example:

Where do I enable Document ID’s for my Site Collection?

In order to enable Document ID’s in your Site Collection, you’ll need to activate the Site Collection Feature called Document ID Service.

See this screenshot for an example:

How do I change the way my Document ID’s are generated?

If you want to alter the way the Document ID’s are generated for your documents in your Site Collection, you can do that by navigating to:

Site Actions – Site Settings – Document ID Settings, like so:

From this new settings page, you’ll get the possibility to tell SharePoint how it should generate your unique ID’s. You can specify a prefix for all the generated ID’s:

I want to take it one step further!

If you’re not quite satisfied with the way SharePoint 2010 generates your Document ID’s for you, then you should most definitely follow along with the rest of this article as I will guide you through the steps to create your very own Document ID provider to generate exactly the kind of ID’s you want – based on your very own code/algorithms!

Bring it on!

Learning about a SharePoint 2010 Custom Document ID provider

This section will give you an overview of what you will need in order to create a custom Document ID provider for SharePoint Server 2010!

Note: As of this writing MSDN isn’t fully updated on these new SharePoint Server namespaces. Some details may or may not change when SharePoint Server 2010 is released into the wild (RTM)


The namespace Microsoft.Office.DocumentManagement contains a class called DocumentIdProvider, which will be the base for our upcoming project!


This is the class we will derive from when creating our custom provider. It contains three (3) abstract methods and one (1) abstract method that we need to implement:

A description of each of these methods and the property will be made inline in my code in the samples!

Creating a SharePoint Server 2010 Custom Document ID provider

Let’s code this little piece of functionality, shall we. The final project (very basic) will look something like this:

So, let’s get coding.

1. Create a class and derive from DocumentIdProvider

public class CustomDocumentIdProvider :
        // Method to generate the actual document ID. Awesomeness lives here!
        public override string GenerateDocumentId(SPListItem listItem)
            // In this method we will tell SharePoint how it should generate
            // the unique ID we want.
            // In my case, I’ve just created a dummy-generator. 
            // Normally you would perhaps want to fetch this from another system or
            // generate it properly instead of like this.. 

            // Points to a method I’ve created that generates foo-ID’s
            return FooSampleIDGenerator.GetFooUniqueID();

        public override bool DoCustomSearchBeforeDefaultSearch
            // If set to true: It will call the GetDocumentUrlsById method before search
            // If set to false: It will use SharePoint Search before custom methods
            get { return false; }

        public override string[] GetDocumentUrlsById(SPSite site, string documentId)
            // Returns an array of URLs pointing to 
            // documents with a specified DocumentId
            // An empty string array 

            // This is where you will implement your logic to find
            // documents based on a documentId if you don’t want to use
            // the search-approach.
            return new string[] { };

        public override string GetSampleDocumentIdText(SPSite site)
            // Returns the default Document ID value that will be initially
            // displayed in the Document ID search web part as a help when searching
            // for documents based on ID’s.
            // This should correspond with the way you’ve designed your ID pattern
            return "AWESOME-12345-67890-SharePointRules";

2. Create a Feature Receiver to hook up your custom provider with your Site Collection

public class ProvisionCustomDocIdProviderEventReceiver : SPFeatureReceiver
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
        DocumentId.SetProvider(properties.Feature.Parent as SPSite,
                                                                 new CustomDocumentIdProvider());
    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        DocumentId.SetDefaultProvider(properties.Feature.Parent as SPSite);

Actually, you’re all done with the code for now.

3. Go to Document ID Settings page and see this message appear


This basically means that your custom provider has been successfully enabled (as per our Feature Receiver).

4. See that the Document ID’s on your documents now is using your custom provider

(Please allow for some time to pass so the Timer Jobs can do their magic, or manually go into Central Admin and run the timer jobs instantaneously)

Behold, awesome custom Document ID provider in action:

Summary and Download

What did we just do?

What we just did was to create a custom Document ID provider that generates our very own custom Document ID’s based on whatever algorithm or pattern we want. There’s no need to follow the built-in format for your generated IDs – which some people have presented in their seminars and blogs. So there you go, step by step!

This could be especially awesome if you’ve got an external system generating Document ID’s already, and you want SharePoint to use those ID’s alongside whatever other system is running. Use your own imagination as to what can be done. The code is in your hands, Obi Wan Coder!

Download project

You can download my sample project here

Enjoy, and please don’t be afraid to leave comments!

Author: Tobias Zimmergren | | @zimmergren


Microsoft has published the two developer-oriented certifications for SharePoint 2010 on Microsoft Learning.

Personally, I think there is a huge improvement now as we’re not only getting the MCTS-credit but can now also become an MCPD (Microsoft Certified Professional Developer) on the SharePoint platform. Something I’ve been waiting for a long time ;-)

SharePoint 2010 exams

For us developers/solution architects there are two certifications of interest (of course you should do the IT-pro tracks as well, but let’s start here with the developer ones):

  1. 70-573: TS: Microsoft SharePoint 2010, Application Development
  2. 70-576: PRO: Designing and Developing Microsoft SharePoint 2010 Applications

SharePoint 2007 Exams

Way back in 2007 I wrote about passing all 4 certifications for SharePoint 2007 (link here). For SharePoint 2007 there is four certifications for the 2007 product-line:

  1. 70-541TS: Microsoft Windows SharePoint Services 3.0 – Application Development
  2. 70-542TS: Microsoft Office SharePoint Server 2007 – Application Development
  3. 70-630TS: Microsoft Office SharePoint Server 2007, Configuring
  4. 70-631TS: Microsoft Windows SharePoint Services 3.0, Configuring


So, keep an eye out on those two new certifications and be well prepared when they arrive – should be a fun ride :-)

Author: Tobias Zimmergren | | @zimmergren 


With the new version of SharePoint comes a full set of new and awesome features that you’ll have to indulge and learn. One of the small things that makes my day much more fun is to display messages to your users in the Status- and Notification areas.

Example of a message in the Status bar area:

Example of a message in the Notification area:

How do we make this magic happen?

In order to display these messages, you really (really) don’t need a lot of code. I’ll lay out the simple code I used to display the messages you saw in my screenshots.

It’s all JavaScript based, so get ready to dig out those old JS skills you know you’ve got lying around somewhere ;-)

Oh wait, you don’t need skills to do this, it’s just that easy!

Show me a Status bar!


function ShowStatusBarMessage(title, message)
    var statusId = SP.UI.Status.addStatus(title, message, true);
    SP.UI.Status.setStatusPriColor(statusId, ‘yellow’); /* Set a status-color */

HTML, call the JS method:

<a onclick="ShowStatusBarMessage(‘Title’!',’Awesome message!’)">
    Display Status Bar message!

Show me a Notification popup!


function ShowNotificationMessage(tooltip, message, sticky)
    SP.UI.Notify.addNotification(message, sticky, tooltip, null);

HTML, call the JS method:

<a onclick="ShowNotificationMessage(‘I am cool!’,'This is a cool message’,false)">
   Display Notification!


Actually, there’s no need for a summary. It’s way too easy.


SP 2010: LINQ to SharePoint – What CAML lies behind my query?

February 19th, 2010 by Tobias Zimmergren

Author: Tobias Zimmergren | | @zimmergren


The two following questions are quite popular in my SharePoint 2010 developer training classes, so I ought to answer them right here.

  1. "What does LINQ to SharePoint really do?"
  2. "Can I see the CAML query generated by the LINQ to SharePoint query?"

The answer is simple: Yes, you can see the results of your generated LINQ query by using the Log property of your DataContext object.

What CAML lied behind my LINQ to SharePoint query?

In order to fetch the CAML query that lies behind your LINQ query, all you need is to work with the .Log object of your DataContext.

See this simple example, which simply outputs the CAML query to an XML-file for easy reading:


This will essentially generate the following content in the file C:MyEntitiesDataContextQuery.xml:


As you can see, the LINQ to SharePoint query is automatically turned into a CAML Query.


Yep, all you need is the .Log property to fetch the CAML query from your LINQ statement. In my sample I’m outputting it to a file called C:MyEntitiesDataContextQuery.xml.

You could of course output it in any other way you want – not just a physical file on the file system. The Log property is of the type TextWriter.


Author: Tobias Zimmergren | | @zimmergren


In SharePoint 2010 you now have the ability to use LINQ syntax to fetch items from your lists instead of using the "traditional" approach of CAML queries. (Including SPSiteDataQuery and SPQuery objects)

In this article I will give you a brief introduction to how you can get started using LINQ queries in SharePoint, also known as LINQ to SharePoint.

Basics of LINQ?

As a prerequisite to this article, I’m going to imply that you know what LINQ is and how to write basic LINQ queries in any .NET application already. I’m not going to dive into the details about LINQ or the syntax itself here – please see MSDN for that!

LINQ to SharePoint!

In order to work with LINQ in SharePoint 2010, we need use a tool called SPMetal.exe which resides in the 14bin folder. This tool is used to generate some entity classes which Visual Studio 2010 can use to get IntelliSense, and allows for LINQ-based queries to be performed on your lists.


  • LINQ to SharePoint queries are translated to proper CAML queries
  • CAML queries are in turn later translated to SQL queries


Using the tool called SPMetal, we generate our entity-classes that are needed to perform these object oriented queries toward our SharePoint server.

These are the required steps to get hooked up:

  1. Launch a cmd-window and navigate to C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14bin
  2. Run the following command to utilize the SPMetal.exe tool with the following syntax:
    1. SPMetal.exe /web:http://yoursite /code:C:YourEntityFile.cs
    2. Example:
  3. Now navigate to C: (or wherever you chose to output your file) and make sure the file has been generated:
  4. Open up the file and take a look at the content that SPMetal now have provided us with:
    Note that the class name is now MyEntitiesDataContext. It’s based on the name you specify as your code file in the SPMetal.exe command line tool.

    If you were to use /code:C:Awesome.cs instead, it would generate a class called AwesomeDataContext.

With that done – all we need to do is import it to one of our projects and use it!

Visual Studio 2010 – Let’s create a sample Web Part that utilizes LINQ to SharePoint

In this sample I will create a simple Web Part that will use LINQ to SharePoint syntax to fetch some information from the Announcements list. A basic sample I use in my training classes as well, and should be fairly easy to grasp!

  1. Create a new project (I’m going to create a new Visual Web Part project)
  2. Import your DataContext-file by choosing your Project -> Add -> Existing Item:
  3. Specify your file (mine is called MyEntities.cs):
  4. Make sure it’s properly placed in your project structure – then we’re good to go:

Alright – that’s easy enough. Thus far we have created an entity file using SPMetal.exe and now we have successfully imported it into our project.

Add proper references

Now in order to use LINQ to SharePoint, you also need to reference the Microsoft.SharePoint.Linq assembly. Point to references, right-click and choose "Add Reference" and select the Microsoft.SharePoint.Linq.dll file:

In your code, reference the assemblies:

Ready to code?

What you should’ve done up until now is this:

  1. Generate your entities using the SPMetal.exe tool
  2. Reference the newly created file from your SharePoint project
  3. Make sure you’re using the proper references for System.Linq and Microsoft.SharePoint.Linq
  4. Be ready to code :-)


In my example I will have a Visual Web Part that will use LINQ to SharePoint to fetch all Announcements from my Announcement-list and work with those results. If you want to see the entire project, look at the bottom of this article where you can download it.



While you code your queries using LINQ to SharePoint, you will now have access to IntelliSense, which you did not have with CAML queries:

I’m going to leave it at that – very (very) easy to get started with LINQ to SharePoint, and all you really need to know is to start using the SPMetal tool to generate your entity classes and hook’em up with Visual Studio to start coding.

Summary & Download

As you can see, there’s not a lot of things you need to do in order to work with LINQ in your SharePoint applications with your SharePoint-data.

I’ve been pinged plenty of times on how you can get started with this, and there you have it. More in-depth articles to come later – this is just to get your wagon rolling!

To download the sample project, click here: [Download]


Author: Tobias Zimmergren | | @zimmergren


Article 3 in the small BCS-series:

1. SP 2010: Getting started with the Business Connectivity Services (BCS)
2. SP 2010: Programmatically work with External Lists (BCS) in SharePoint 2010
3. SP 2010: Programmatically work with External Lists (BCS) using the Client Object Model

In my previous article in the series, I talked about how easy it is to fetch information using the standard SharePoint server API-approach. In this article I will talk about how you can access data in your BCS data source, by utilizing the Client Object Model.

Client Object Model code to read from the external list

Just like I described in my previous article, you now have the awesome ability to work with data in your External Lists (connected to a data source using BCS) – namely, you can use the standard SharePoint APIs.

Since I’ve shown you how you can do this using the Server Object Model, I thought I could take another spin at it and show you the code for doing basically the same with the Client Object Model.

The underlying data

As with my previous article, I’m still using the same data source as I set up in my first article – the "ProductList" table in my SQL Server database called "Zimmergren_DB"

As seen in the SQL Server Management Studio:

Let’s fetch the data using a Windows Forms application that utilizes the Client Object Model!

I’ve designed a Windows Forms application to utilize the .NET Client Object model (in contrary to using the Silverlight client object model or JavaScript client object model).

It looks like this:

When you click the fancy button called "Get External Data", it will use the Client Object Model to fetch the records from the external list (from the SQL server) and display them in a DataGridView. Nothing fancy.

The code!

With no further delays or chit-chat, here’s the simple code!

    // Define the Client Context (as defined in your textbox)
    SP.ClientContext context = new SP.ClientContext(tbSite.Text);
    SP.Web site = context.Web; 

    var ProductList = site.Lists.GetByTitle(tbList.Text); 

    SP.CamlQuery camlQueryAwesomeness = new SP.CamlQuery();  

    IQueryable<SP.ListItem> productItems =

    IEnumerable<SP.ListItem> externalList =

    // This is where we actually execute the request against the server!

    // Retrieve the products from the product list using some fancy LINQ
    var productListData = from product in externalList
      select new
          // We’re never pointing to the field at the 0-index
          // because it’s used by the BDC Identity itself. Hence our elements start at 1.
          ProductID = product.FieldValues.ElementAt(1).Value.ToString(),
          ProductName = product.FieldValues.ElementAt(2).Value.ToString(),
          ProductDescription = product.FieldValues.ElementAt(3).Value.ToString()

    // Simply clear the rows and columns of the GridView

    // Add the columns we need (ProductID, Name, Description)
    gvProducts.Columns.Add("ProductID", "ProductID");
    gvProducts.Columns.Add("Name", "Product Name");
    gvProducts.Columns.Add("Description", "Product Description");
    foreach (var product in productListData)
        // For each product in the list, add a new row to the GridView

References and recommended reading

  1. Getting Started with the Client Object Model in SharePoint 2010
  2. Getting Started with Business Connectivity Services in SharePoint 2010

Summary & Download

At this point, I’ve showed you three short articles in which I describe how you can set up a Business Connectivity Services data source – then utilize the Server OM or Client OM to fetch information from that external data storage.

Worth to note is that this is still a Beta product, which of course means that it may differ in functionality and performance in comparison with the final (RTM) version of SharePoint 2010.

Download the complete Visual Studio 2010 project here: [ ]

Author: Tobias Zimmergren | | @zimmergren


Article 2 in the small BCS-series:

1. SP 2010: Getting started with the Business Connectivity Services (BCS)
2. SP 2010: Programmatically work with External Lists (BCS) in SharePoint 2010
3. SP 2010: Programmatically work with External Lists (BCS) using the Client Object Model

In my previous article I talked about how you can set up a simple BCS configuration to fetch and work with external data in SharePoint 2010. In this article I will talk about how you can utilize the SharePoint 2010 object model to work with that external data, directly from the SharePoint API. It’s all really simple!

Working with data in an External List using the SharePoint Object Model

The code in this sample doesn’t really differ from the way you fetch information from any other list in SharePoint (2007 or 2010). This – of course – is very welcomed news, as we do not need to learn any new frameworks or tools to work with the data in our external lists. It simply works as any other SPList, basically.

Retrieving external data, made simple:

When fetching items from an external list, you can simply do that by utilizing the good-old SPList object. We do not need to work with any other types of namespaces or frameworks in order to do this.

In my SQL Server I’ve got a table called “ProductList“.
This list is filled with the following data:


Fetching some items from the external list, and displaying them in a console app:

// Product List is my external list, that is working with data in the SQL Server!
SPList list = web.Lists["Product List"];

SPQuery q = new SPQuery();
q.Query =
“<Where><IsNotNull><FieldRef Name=’ProductID’ /></IsNotNull></Where>”;
q.RowLimit = 100;

SPListItemCollection col = list.GetItems(q);

foreach (SPListItem item in col)

This will render the following result (fetched from the database):


The things you see in the console windows is fetched straight from the SQL Server (using a BCS connection through the External List).

Writing data to the External List (hence, writing to the SQL Server)

Seriously, this is way too easy as well…

// Get the external list
SPList list = web.Lists["Product List"];

// Use the traditional approach to create SPListItems and hook it up with the list
SPListItem item = list.Items.Add();
item["Name"] = “Sample Product Wohoo“;
item["Description"] = “Sample Description Wohoo“;

Upon running this code in your SharePoint application, it will create the SPListItem object and add a Name and Description. When you hit .Update() it will push this data through the data source connection, to your SQL server.

Here’s what the updated data looks like:

We’re running a Beta-product!

As you can imagine, there’s a ton of new cool things to work with in SharePoint 2010 – where the BCS is one. This article discuss the very basics of how you can retrieve information from these lists using the normal API-approach.

At the time of this writing (during Public Beta) there isn’t any measures on performance and what impact it has on the server in comparison to alternative ways to fetch and work with the data.

As time goes on, there will be probably be some new information on this – I’ll keep you posted when I know more.


As you can see, working with external data from the SharePoint API isn’t very hard to do. What you need to make sure is to have an external list set up somewhere (see this article for how you can do that) and then you can simply use the normal SPList object from the SharePoint object model to work with the external list and it’s external data from the SQL server (in my case).

So if you haven’t already: Get on the SharePoint 2010 wagon and enjoy the ride!

Author: Tobias Zimmergren | | @zimmergren


Article 1 in the small BCS-series:

1. SP 2010: Getting started with the Business Connectivity Services (BCS)
2. SP 2010: Programmatically work with External Lists (BCS) in SharePoint 2010
3. SP 2010: Programmatically work with External Lists (BCS) using the Client Object Model

BCS in SharePoint 2010 is an awesome refinement of the Business Data Catalog from MOSS 2007. With BCS – or Business Connectivity Services – you get the possibility to connect external data and work with it from SharePoint.

In this article I will not cover the basics of what BCS is all about (MSDN/TechNet does this very well) – I will rather give you a walkthrough of how you can setup a BCS connection to an external database, and then work with this information directly from a SharePoint list – without the user actually knowing anything about the connection to the database.

BCS Poster: Business Connectivity Services Poster
BCS Team Blog:

A sample SQL database

I’ll just show you how my sample database is set up – simply create a new database in your SQL Server and have it filled with some example data. In my case, this is the data in my SQL database, called Zimmergren_DB:

In this sample database, I’ve added a table called ProductList which in theory will represent some products in this database, like this:

I’m filling the database with some sample data, so we will be familiar with this data when we later watch this information from SharePoint:

Alright – we have some sample data in our SQL Server. Nothing fancy, just some very simple data. Great, let’s get going with the fun stuff!

Creating an external content type

The most effective and easy way to set up a simple BCS connection, is to use SharePoint Designer 2010. You heard me, we can now get up and running with BCS by using SPD instead of modeling complex ADF files and things like that.

In order to do this, we need to create a new External Content Type!

Here’s how do create our External Content Type and hook it up with our database, step by step:

  1. Open the site you want to work with using SharePoint Designer 2010
  2. Select "External Content Types" in the left hand navigation:
    Loading this page might take some time, be patient!
  3. Click to create a new External Content Type like this:
  4. Click the link that reads: "Click here to discover external data sources and define operations":
  5. Click "Add Connection"
  6. Select "SQL Server" as your Data Source Type:
  7. Enter the details about your connection to your SQL Server:
  8. When the connection is made, your Data Source Explorer will be filled with the database you have specified. Now choose the table you want to work with, and right-click and select "Create All Operations":

    You’ll be presented with a wizard-like dialog where you can specify the operations, elements and other properties for your BCS connection.

  9. Click "Next" to get to the Parameters page
  10. Select the field that you want to act as an Identifier. In my case I’ve selected my ProductID just to get on with it:
  11. Click "Finish"
  12. You’ll be presented with a list of operations that your External Content Type can do, like this:

That’s it. A few points, a few clicks – and you’re done. Let’s create an external list (using the Browser to show how simple it is..) and hook up our external content type with it!

Creating an external list

There’s a few ways to create an external list in SharePoint 2010. We will create it using the Browser UI to show you how simple it can be.

  1. Open your site and choose Site Actions - More Options…
  2. Select the External List template, and click Create
  3. Enter a name for your list, e.g. Product List
  4. You’ll see a field in this list called External Content Type, click the browse-button beside it:

    What is really awesome here, is that you’re now presented with a dialog where you simply can choose the data source for this list. That means, you’ll select the data source you’ve created (mine is called Zimmergren_DB). Then your list will automatically work against the SQL database, but still have the look and feel of a SharePoint 2010 list.

  5. Select your data source and click OK:
  6. Now simply click the button called Create:

Would you look at that! You’re now working with external data, from your (what looks to be) normal SharePoint list! This is brilliant!

You now have the ability to create new items, update existing items, delete items and do all your normal CRUD-operations (CRUD = Create, Read, Update, Delete) straight from the SharePoint 2010 list.

Proof of concept – Adding a new product

Let’s just for the fun of it add a new product called "Awesome Product 1.0" like the following screenshot:

Now go to your SQL Server and see the changes take effect immediately. The data is NOT stored in SharePoint, it’s stored in your SQL Database.

This is what my table now looks like in the SQL Server, after adding a new item in the SharePoint list:


With a few points, followed by a few clicks – you’ve set up your external data connection. Basically it’s that simple.

Of course there’s a lot of things to consider when doing these configurations – and you might not want to auto-generate the CRUD-operations, but rather create them one by one and specify more fine-grained permissions etc.

This is merely a sample to show you how easy it is to actually get up and running with the SharePoint 2010 Business Connectivity Services (BCS) and work with external data!


Author: Tobias Zimmergren | | @zimmergren


LogoSEF2009 At the SEF 2009 Conference in Sweden I delivered a session about SharePoint 2010 development. The sessions from SEF are now available for download from the SEF web site.

Unfortunately the presentation I did was required to be in Swedish, and I haven’t done any translation to English for this particular presentation.

Download sessions from SEF

My session on SharePoint 2010 Development Introduction:
Tobias Zimmergren – SharePoint 2010 Development Introduction

Download all other presentations from, including great speakers like:

  • Eric Schupps
  • Göran Husman
  • Joel Oleson
  • Penny Coventry
  • Steve Smith
  • Todd Klindt
  • Wictor Wilén
  • and more…


Just like the previous posts, this is just going to be a short "heads up" on some new documentation and links that just showed up on the Microsoft Download Center site:

2010: Microsoft SharePoint Products and Technologies Protocol Documentation

2010: SharePoint Products and Technologies: 2010 (Technical Preview) Developer Documentation


SharePoint 2010 Sneak-Peak videos are officially out

July 14th, 2009 by Tobias Zimmergren

So, if you haven’t heard it already, has updated some information and now let us in on some details about SharePoint 2010.

Take a look at the preview/sneak-peak videos and be amazed! I’m stunned. Wow!

You’ll find the videos here:

Have fun :-)