search blog
most popular
MCP MCTS MCT MVP

SPS 2010: Getting started with LINQ to SharePoint in SharePoint 2010

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

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 14\bin 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.

Noteworthy:

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

SPMetal.exe

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 Files\Common Files\Microsoft Shared\Web Server Extensions\14\bin
    image
  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:
      image
  3. Now navigate to C:\ (or wherever you chose to output your file) and make sure the file has been generated:
    image
  4. Open up the file and take a look at the content that SPMetal now have provided us with:
    image
    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:
    image

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:
image

In your code, reference the assemblies:
image

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 :-)

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.

image

IntelliSense!

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

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]

Enjoy!


Published: Feb-19-10 | 4 Comments | 0 Links to this post

SPS 2010: Programmatically work with External Lists (BCS) using the Client Object Model

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

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:
image

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:
 image

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 =
                                      ProductList.GetItems(camlQueryAwesomeness); 

    IEnumerable<SP.ListItem> externalList =
                                      context.LoadQuery(productItems);

    // This is where we actually execute the request against the server!
    context.ExecuteQuery(); 

    // 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
    gvProducts.Rows.Clear();
    gvProducts.Columns.Clear(); 

    // 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
        gvProducts.Rows.Add(
                                 product.ProductID,
                                 product.ProductName,
                                 product.ProductDescription
                                 );
    }

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: [ Zimmergren.SP2010.ClientOM.BCS.zip ]


Published: Jan-21-10 | 6 Comments | 0 Links to this post

SPS 2010: Programmatically work with External Lists (BCS) in SharePoint 2010

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

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:

image

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)
    Console.WriteLine(item["Name"].ToString());

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

image

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";
item.Update();

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:
image

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.

Summary

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!


Published: Jan-19-10 | 6 Comments | 0 Links to this post

SPS 2010: Getting started with Business Connectivity Services (BCS) in SharePoint 2010

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

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: http://blogs.msdn.com/bcs/

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:
image

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

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:
image

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:
    image
    Loading this page might take some time, be patient!
  3. Click to create a new External Content Type like this:
    image
  4. Click the link that reads: "Click here to discover external data sources and define operations":
    image
  5. Click "Add Connection"
    image
  6. Select "SQL Server" as your Data Source Type:
    image
  7. Enter the details about your connection to your SQL Server:
    image
  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":
    image 

    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:
    image
  11. Click "Finish"
  12. You'll be presented with a list of operations that your External Content Type can do, like this:
    image

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…
    image
  2. Select the External List template, and click Create
    image
  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:
    image

    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:
    image
  6. Now simply click the button called Create:
    image

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:
image

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:
image

Summary

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!

Enjoy


Published: Jan-18-10 | 11 Comments | 0 Links to this post

SPS 2010: How To - Relational lists in SharePoint 2010

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

One of the new cool things in SharePoint 2010 is the fact that we now have relational lists. In my previous article about List Joins, I talked about how you programmatically can fetch and join information from more than one list with the improved SPQuery object.

In this article I will give you an overview of what capabilities you get out of the box when installing SharePoint 2010 - in terms of relational data in lists.

Relational Lists in SharePoint 2010 - Overview

By utilizing Lookup fields in SharePoint 2010, we can enforce a relationship behavior that we previously would have to work very hard to achieve.

Microsoft have now provided us with a few new options when working with Lookup Fields:

  1. Joins between lists
  2. Projected Fields
  3. Relational integrity

Joins between lists

As mentioned, we have the capability to create relationships between lists in SharePoint 2010. This is quite easy to do using the browser UI, which I will soon demonstrate step-by-step.

Projected Fields

With projected fields we have the capability to pull information from a parent list into the view of the child list.

This basically mean that you can reference and display information from a parent list, in your child list. The fields are Read-Only but enables you to get a much nicer joined view.

Relational integrity

With SharePoint 2010 and relations in lists, you would of course wonder how it handles the relational integrity. E.g. what happens if I delete or try to delete something in the parent list?

Well, there's generally two relational integrity options:

  1. Restricted delete
    Basically the restricted delete option enables you to enforce a behavior that means that you can't delete any items that have relations from the list. E.g. if the item you're trying to delete have a bunch of child-items, you cannot delete them.
  2. Cascade delete
    Cascade delete on the other hand, means that when you're trying to delete an item which has relations - it'll delete the related items as well.

Delete and Recover related items - Recycle Bin

A question I got the other day was:

"If I delete an item in my parent list and have cascading delete so all my child items are deleted, how do I restore them if I made a mistake?"

Quite simple my dear Watson, you utilize the recycle bin. When you delete an item using Cascading Delete, the item and it's related items are placed in the Recycle Bin. From there you can obviously easily recover the items as well. This is what an item with relations looks like in the recycle bin:

[PIC]

Step by step - Do it yourself

Alright - so we've covered some of the basics of relational lists, nothing fancy. But now we want to create some lists and have relationships between them - so let's get on with it!

1. Create a parent list

  1. Create a new Custom List named "ParentList"
  2. Create a new Coumn in that list as per the following settings:
    image 
  3. Add some sample items in the list like this:
    image

2. Create a child list

  1. Create a new Custom List named "ChildList"
  2. Create a new Column in that list as per the following settings:
    image
    Please note that I checked the City checkbox. This will create a Projected Field against the lookup automatically so you can view that information which exist in the parent list - directly in the child list.

3. Test out the projected fields functionality

Add some new items in the ChildList to see that when you add an item and choose a company from the ParentList it will automatically show the projected field ("City") as a read-only field in the child-list:
image

4. What about enforcing relational behavior?

I'm glad you asked. When you create (or change settings for) a lookup field (like the "ParentLink" field), you have the ability to change settings for the relational behavior.

Go to your "ParentLink" column, or when you create a new lookup field - and see the following dialog:
image

From this dialog as you can see, you have the ability to make the necessary settings for your fields.

Restricted Delete

If you choose the "Restricted Delete" option, you will see the following behavior when trying to delete an item that has related items:
image 

Cascade Delete

If you choose the "Cascade Delete" option for your lookup field instead, you'll be sending the items directly to the Recycle Bin instead. Then it'll look like this in the recycle bin:
image

Note, that you have the icon that looks like a relational diagram in your recycle bin - this means that you've deleted an item that may have deleted linked items. If you restore this item (in our case, TOZIT) it will automatically restore all of the items that were originally deleted.

So, we have the kind of enforced relationships we've longed for since the dawn of days!

Summary

Voila. Easy as 1-2-3, you have created two very simple lists and created a relationship between them - and optionally you can enforce this relationship using the "Enforce relationship behavior" settings for Restrict Delete or Cascade Delete.

Enjoy!


Published: Jan-05-10 | 8 Comments | 0 Links to this post

SPS 2010: How To - Event Receivers and Custom Error Pages

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2007

Many of you are aware that in SharePoint 2007, you can create Event Receivers (aka. Event Handlers) to take care of things for you when specific things happen. For example, you can subscribe to the "ItemAdded" event for a specific list, and have your custom code execute when the event fires.

Also, you are in SP 2007 able to cancel an event if you have the need for it, hence providing the user with an error message in the browser.

With SharePoint 2007 you had no way to customize this error message, and could only display the out-of-the-box message.

I've been getting the question about 1 million times - but never had any really good answer. Until now, where this specific functionality is built into SP 2010.

SharePoint 2010

The object model has been extended in various places, and this is one of the most welcome changes for me and a lot of my fellow peers doing daily SharePoint development.

So, in this article I will walk you through the news with Event Receivers in SP 2010 in regards to creating custom Error Pages for your users.

Creating an Event Receiver in SharePoint 2010 with a Custom Error Page

Using Visual Studio 2010, choose the new template called "Event Receiver" like so:
image

Choose if you want this to be a Farm Solution or a Sandboxed Solution. Then click next:
image

Finally, choose the Type of receiver you want to create, what event you would like to hook up and to what type. I chose "List Item Events", "Announcements" and "An item is being added":
image

Click next and let Visual Studio 2010 work it's magic.

You're presented with the following project structure that is created for us:
image

I will not dig deep on how and why the structure of the project looks the way it does now - it will be covered in another article.

1. Adding some basic logic for your Event Receiver

In the EventReceiver1.cs file that you're presented with, you can quite easily add any code you want - and some code has already been added so you don't have to!

The code looks like this out of the box:

image

Now, what I want to do in order to make sure my event receiver works - is to simply add some dummy-code and have it tested!

Add the following code to your ItemAdding-method:
 image

All we do here is check our item that is being added makes a condition to see if the DueDate property is set. The breakpoint is simply added because you easily should see that your code executes and works as expected.

2. Press the Holy Button (F5)

By pressing F5, Visual Studio will take care of the build, packaging and deployment of your Event Receiver. For more details on the actual F5-experience, I encourage you to read MSDN, SDK and all the blogs out there.

You are presented with a web page (VS 2010 launches IE for you as well), where you now can easily test your Event Receiver.

In our case, when adding a new Announcement, we should automatically check the DueDate property. Currently we don't cancel the event or do anything else - let's leave that to your imagination.

Cancelling an Event in SharePoint 2010

So - now that we've got a very basic Event Receiver in SharePoint 2010, we should add that Custom Error Page we talked about.

  • Start by adding a New Item to your project of type Application Page:
    image
  • Visual Studio 2010 will now automatically add a mapped folder called "Layouts" which is mapping to the _layouts folder in the SharePointRoot (14-folder):
    image
  • Edit the ErrorDueDate.aspx file to add some rich HTML:
    image
    Note that I am referring to an image as well. I just popped that into the same Layouts-folder that was created for my Event Receiver project. 
     
  • Edit your EventReceiver1.cs file and add the current logic:
    image
    This will now cancel the event if the DueDate field is empty, and show the user a custom error page that you designed yourself.
  • Hit F5 and let Visual Studio 2010 work it's magic again
  • Try it out by adding a new Announcement without adding a DueDate:
    image
  • You should now be presented with the following dialog:
     image

As you can see, your custom HTML now appears. Apparently I didn't do any fancy design on my Application Page, but you can add more images and whatever else you want to make it more easy for the users to understand what actually went wrong - and how to make it on from there.

Summary

As easy as 1-2-3, you've created a new event receiver in SharePoint 2010 - and created a Custom Error Page upon which your users will land when they're presented with the error - something that wasn't really possible in 2007.

Enjoy!


Published: Jan-05-10 | 100 Comments | 0 Links to this post

SP 2010: Getting started with the Client Object Model in SharePoint 2010

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In this article I will talk about how you can get started with using the Client Object Model in SharePoint 2010. This new object model is introduced in SharePoint Foundation 2010, and does not require SharePoint Server 2010 to be installed.

The Client Object Model is a new object model introduced in SharePoint 2010 which is aimed at making things easier for the developer when developing client-side applications for SharePoint 2010.

Three new client APIs

With the Client Object Model, Microsoft has introduced a set of new APIs to work with to ease the daily tasks of developers.

  • .NET Managed Applications (using the .NET CLR)
  • Silverlight Applications
  • ECMAScript (JavaScript, JScript)

The client APIs provide you as a developer with a subset of the Microsoft.SharePoint namespace which is based on the server-side object model.

Naming conventions

As a small side-note I would like to mention that the objects you are comfortable with calling “SPWeb”, “SPSite”, “SPList” and so on are now named “Web”, “Site”, “List”.

So to conclude the naming convention, the “SP” in the objects has been dropped. Easy enough to remember, right?

Good, let’s move on to some actual code samples to get things fired up!

SharePoint 2010 Client Object Model – Creating your first client-side application

With some fundamental knowledge about the Client OM mentioned above, I would like to take this one step further and actually demonstrate how you can utilize the Client OM in order to create your first client-side application and work with data from SharePoint, instead of using the built-in Web Services.

Step 1 – Creating the Visual Studio project

To be able to follow along with this article, the prerequisites are that you have SharePoint 2010 and Visual Studio 2010 installed in a development environment.

  • Launch Visual Studio 2010
  • Create a new project
  • Choose “Windows Application” and apply the following settings to your project:
    • Target Framework: .NET 3.5
    • Build output: AnyCpu (or x64)

As you can see we are specifically targeting .NET 3.5 since this is the version of the framework that SharePoint 2010 is based on.

Also notice that we are changing the build output from x86 (unsupported!) to AnyCpu or x64 in order to be able to compile and run this project properly.

You should now have an empty Windows Application project like so:   
ScreenShot001

 

Step 2 – Adding the Client Object Model references

Next, we need to add references to the Client Object Model in order to be able to work with the client-side APIs from our awesome Windows Application.

  1. Right click the “References” node and choose “Add Reference”  
    ScreenShot002
  2. Choose “Browse
    1. Navigate to this folder:
      C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI
    2. Select these two files:
      1. Microsoft.SharePoint.Client.dll
      2. Microsoft.SharePoint.Client.Runtime.dll 

         ScreenShot004
  3. Make sure they are included in the references of your project: 
    ScreenShot005
  • Add the following using-statement in your class (note the last line!): 
    ScreenShot008

Alright – that was easy enough. Adding the references shouldn’t be any problems. Moving on the the more interesting part – getting our first client object model application up and running!

Step 3 – Make our Windows Application pull out some data from SharePoint

Now that you’ve created your Windows Application, targeted the correct framework and platform, added the Client object model references – we’re ready to take on some Client Object Model action!

Adding the necessary controls to the form
  • Add the following controls to your Windows Application:
    • A new ListBox control
    • A new Button control
    • A new TextBox control (Set multiline = true, readonly = true etc to make it look like mine if you want..)

ScreenShot006

Adding some code-logic to fetch the lists on a particular site and populate the ListBox
  • Double-click the Button that you’ve created and add the following code logic:

private void btnGetLists_Click(object sender, EventArgs e)
{
    lbLists.Items.Clear(); 

    using (SP.ClientContext ctx = new SP.ClientContext("http://zimmer"))
    {
        var web = ctx.Web; 

        ctx.Load(web);
        ctx.Load(web.Lists); 

        ctx.ExecuteQuery(); 

        foreach (SP.List list in web.Lists)
        {
            lbLists.Items.Add(list.Title);
        }
    }
}

  • Double-click the ListBox that you’ve created and add the following code logic:

private void lbLists_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (SP.ClientContext ctx = new SP.ClientContext("http://zimmer"))
            {
                var list = ctx.Web.Lists.GetByTitle(lbLists.SelectedItem.ToString());

                ctx.Load(list);
                ctx.ExecuteQuery(); 

                string infoAboutList =
                    string.Format("Title: {0}ItemCount: {1}IsHidden: {2}",
                    list.Title + Environment.NewLine,
                    list.ItemCount + Environment.NewLine,
                    list.Hidden.ToString()); 

                textBox1.Text = infoAboutList;
            }
        }

Things to note:

Running the simple application

When you decide to run this awesomely simple application, it will look something like this: 
ScreenShot009

With a few simple lines of code you have created your first Client-side application for SharePoint 2010.
Of course we could elaborate this sample to make it way more complex, but this is a teaser for you to get started with the client object model.

Step 4 – Authentication Options for our application

Quite naturally, the question of how you can authenticate to SharePoint often pops up when I do my SP 2010 training and seminars. With that said, I’ll walk you through the different authentication options you’ve got for your client application.

Basically there are three (3) authentication options you can use when you’re working with the Client Object Model in SharePoint 2010:

  • Anonymous
  • Default
  • FormsAuthentication

ScreenShot010

If you do not choose an authentication method in your code, the application will default to using the client’s Windows Credentials (DefaultCredentials)

Example 1: Using anonymous authentication

ctx.AuthenticationMode = SP.ClientAuthenticationMode.Anonymous;

Example 2: Using Forms Authentication with the Client Object Model

SP.FormsAuthenticationLoginInfo formsLoginInfo = 
new SP.FormsAuthenticationLoginInfo("TobiasZimmergren", "SecretPassword");

ctx.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;

ctx.FormsAuthenticationLoginInfo = formsLoginInfo;

When you call the Forms Authentication, it will automatically call the Authentication Web Service for you and return the authenticated cookie.

Summary & Downloads

With very little effort, we have created a new Windows Form application that can be run as a client-side application – without the need of SharePoint to be installed on that machine.

Easy enough we have done so without calling any Web Services.

With that said, you should now at least be updated on how you create your first few Client Object Model applications, and be able to start your own project(s) using this new awesome OM.

ENJOY!

Download my sample project

Download my awesome sample project here


Published: Nov-30-09 | 13 Comments | 1 Link to this post

SharePoint BDC Part 2: Creating your first BDC Web Part

Author: Tobias Zimmergren
URL: http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In my previous article (SharePoint BDC Part 1: Getting started with the Business Data Catalog) I talked about what you'll need to do in order to begin to work with the BCD in SharePoint (MOSS 2007 specifically, as it's an Enterprise feature).

In this article I will briefly guide you through the process of creating your first BDC Web Part that will communicate with the BDC.

Note: You can download the source code for this sample project here [Download]

Prerequisites

You need to have your BDC set up and ready to use before you can start creating your own BDC Web Parts to communicate with the BDC. (See my previous article for a walkthrough)

We will also use Microsoft Visual Studio (2005/2008) to create the Web Part.

Enjoy!

What we had -> where we're going

In the previous article I talked about using the built-in Web Parts for your BDC needs. Although they fill a lot of requirements, sometimes you just might want to write your custom Web parts instead.

This is what the standard BDC list looks like:

image

This is what the final result will look like: (Note, this is a custom Web Part which you'll develop in the following steps)
image

Step 1 - Create a new Web Part project

I will expect that you already know how to create a new Web Part project (either using the VSeWSS or using WSPBuilder, or any other tool of preference).

See this article for a WSPBuilder complete walkthrough: WSPBuilder - Walkthrough of the Visual Studio Add-in

Step 2 - Add the BDC references to your project

Once you've got a Web Part project up and running, you should add some references that are needed for the BDC Object Model.

You should add the "Microsoft® Office SharePoint® Server component" reference to your project:
image

Once you've added this reference to your project, you have a GO for using the BDC namespaces.

Add the following using-statements to the top of your Web Part:

using Microsoft.Office.Server.ApplicationRegistry.MetadataModel;
using Microsoft.Office.Server.ApplicationRegistry.SystemSpecific.Db;
using Microsoft.Office.Server.ApplicationRegistry.Runtime; (if you need it..)

This is what my Visual Studio project looks like when using the WSPBuilder to create my Web Parts (notice the reference to microsoft.sharepoint.portal which comes from the reference we added):
image

Now we're good to go! Let's start coding then!

Step 3 - Utilize the BDC object model to access data

Note, you can download the complete Visual Studio Project at the end of this article with the source code.

Fetches all the LOB instances from the metadata repo:

var myInstances = ApplicationRegistry.GetLobSystemInstances();

 

Fetch the HR instance for Human Resources:

var humanRecourcesInstance = myInstances["HR"];

 

Pick out the Department entity from the HR instance:

var departmentEntity = humanRecourcesInstance.GetEntities()["Department"];

 

Fetches the method GetDepartments which is specified in our ADF file (Application Definition File) for our BDC connection:

var getDepartmentMethod = departmentEntity.GetMethods()["GetDepartments"];

 

Fetches the MethodInstance DepartmentFinderInstance:

var deptFinderInstance =
      getDepartmentMethod.GetMethodInstances()["DepartmentFinderInstance"];

 

We call the departmentEntity.Execute() method to fetch DbEntityInstance's:

var foundEntities = 
     (DbEntityInstanceEnumerator)departmentEntity.Execute(
                                                                          deptFinderInstance, 
                                                                          humanRecourcesInstance);

 

Simply loop the DbInstances and then shoot out their name in a bunch of literal controls.
In a real scenario, we would most likely add those intances to an SPGridView instead of printing Literals to enable Views, Sorting, Paging and a whole set of awesome features that comes with the Grid View.:


while (foundEntities.MoveNext())
{
    var currentDepartment = (DbEntityInstance)foundEntities.Current;
    Controls.Add(new Literal{Text =
              "<div style='border-bottom:1px dashed #c0c0c0; width:100%;'>"});

    Controls.Add(new Literal {Text =
              currentDepartment.GetFormatted("Name")+ "<br/>"}); 

    Controls.Add(new Literal { Text=
currentDepartment.GetFormatted("DepartmentID").ToString() }); 

    Controls.Add(new Literal{ Text = "</div>" });
}

When you've written the aforementioned code, you will have the base set up for retreiving data from your BDC connection. You will (of course) have to dig a whole lot deeper if you want to master the arts of BDC and the object model that comes with that. But at least it's a start for you to get to know the namespace, and learn what namespaces to use - and see that it actually works!

Step 4 - Finalize and deploy your Web Part

Once you've created the project, build it and deploy to your SharePoint development machine and add your Web part to see the action:

image
(Yes, the Web Part is called SharePointRules BDC Web Part - and for a good reason too!)

Step 5 - May your creation shine upon SharePoint! (aka. Final result)

This is what the creation looks like (wow..), which basically only utilize the most basic aspects of the BDC Object Model to get started - but here you have it in action, fetching data immediately from your back-end SQL server (Adventure Works database in this case) using the BDC:

image

Summary

That's a wrap for this article. I have walked you through the few simple steps needed to create your own first BDC Web Part.

In my next BDC article I will talk about what alternative tools I find suitable to use for generating your ADF (Application Definition File).

 


Published: Jul-25-09 | 5 Comments | 0 Links to this post

SharePoint BDC Part 1: Getting Started with the Business Data Catalog

Author: Tobias Zimmergren
URL: http://www.zimmergren.net | http://www.tozit.com 

Introduction

In this article I will guide you through the very basics of getting started with Business Data Catalog, BDC:

  1. Install the AdventureWorks 2008 Sample Databases
    1. We will use this database as our example for retrieving data using the BDC.
  2. I will step you through the simple process of creating your ADF (Application Definition File)
    1. We will use this file as our import connection
  3. I will guide you through how we can import this ADF file and create our BDC Application
  4. Lastly, I will guide you through the process of creating a basic site and use some of the basic BDC Web Parts

Install the AdventureWorks sample database

  • You'll need to go and download the AdventureWorks sample databases
    image

  • Just finish the installation by clicking next a couple of times and let the installer do it's normal Microsoft-installer magic.
  • You should now see a couple of new databases in your SQL Server Management Studio:
    image
    AdventureWorks, AdventureWorks2008, AdventureWorksDW, AdventureWorksDW2008, AdventureWorksLT, AdventureWorksLT2008

Alright - We've got our databases, now we need to start thinking about how we will get data from our SQL server into SharePoint. This is done by creating/generating an Application Definition File (ADF) as you will see in the next section.

Creating the ADF (Application Definition File)

Alright, there's a few different options to create your ADF (Application Definition File). I will show you how to get started with using the free tool called "Application Definition Editor" that comes with the latest SharePoint Server SDK.

Note: See the bottom section in this article for a summary of links to all resources mentioned in the article.

After you have installed the latest SDK, you can choose to install the "Microsoft BDCTool" located here by default: "C:\Program Files\2007 Office System Developer Resources\Tools\BDC Definition Editor". Which will give you the following item in your Start Menu:
image

Launch the BDC Application Definition Designer

Click the application and launch the editor. You will see an interface like this:
image

Create or import your ADF file

There's basically two alternatives when it comes to editing an ADF (Application Definition File).
One is to create a new one (which I will guide you through first), and the other is to import an existing one (which I will show you after the first alternative).

Alt 1) Creating our own ADF file
Now we're going to connect to our newly created sample-databases and create an ADF file for use with those databases.
  • Click on ADD LOB System
  • Choose Connect To Database
  • You will see a nice popup-dialog where you will be able to enter the connection details to your desired database
    • Enter your connection details, example:
       image
  • You are presented with the "Designer Surface" that looks something like this:
    image
  • In our case, we're going to use the table called "vEmployee" which exist in the AdventureWorks database in order to pull out some information about our employees.
    • Search for the table called vEmployee and drag it out to the Design Surface
    • Search for the table called vEmployeeDepartments and drag it out to the Design Surface
    • It should look something like this:
      image
    • Make any necessary changes, then click OK
    • You'll see a view similar to this one after some tweaking:
      image 
    • After you've done the necessary changes to your configuration, making sure it's a valid ADF with proper filters, enumerators and methods or whatever you need in your application then smile, because we're done with that part!
Alt 2) Importing an existing ADF file

If you don't want to do everything from scratch or you've already got an ADF file that you wish to modify, you can do so by importing an existing ADF file into the Definition Editor. Here's how:

  • Open the BDC Definition Editor tool, then click the "Import" button in the menu:
    image
  • Browse to your existing ADF file and choose to import it. Simple as that.
    (I am importing a file called BDCAWDW.xml, which contains definitions for Product, Reseller, ProductSubcategory, ProductCategory as shown below)
  • You'll see the imported ADF file's structure immediately in the designer, under the prerequisite that your SQL connection string in the ADF file is valid:
    image 

Note: I will not detail how you create filters, finders, methods etc. in this article. You can read more about that here:
http://msdn.microsoft.com/en-us/library/ms145931(SQL.90).aspx

I may cover the topic of ADF-functionality in another article later on.

Generate the ADF file from the designer

I really don't need to tell you this, but there's a button called "Export" which you use to export the definition you've created using the definition editor to an xml file:
image

Import the ADF file

If we have gotten this far, we might as well get the last few bits in place.
What we now need to do is to import our ADF file into SharePoint, since that's where it should reside. Follow along with these few simple steps to make sure you're properly importing your file into SharePoint.

  • Navigate to your Shared Services Provider Administration site (You can access your SSP through Central Administration)
  • You are presented with a section called "Business Data Catalog" where you'll find a bunch of different alternatives.
  • Make sure you have the permissions to modify the BDC (See the link Business Data Catalog permissions)
  • Click "Import application definition"
    image  
  • Browse for your .xml file and click "OK":
    image
  • You'll see a progress bar (You don't see that a lot in SharePoint. I love it!), telling your how the import process is going:
    image
  • When it's done, you'll click "OK" and be presented with an overview of your imported BDC Application:
    image
Configure permissions on the BDC Application Definition

In order for all users to be able to select/read data from your BDC Application, you'll need to make sure they've got the appropriate permissions to actually do so.

Usually I do this setting on each of the imported entities, in case you want specific permissions on different entities - instead of on the entire application.

  • Select the DropDown list on your first entity and choose "Manage Permissions":
    image 
  • Choose "Add Users/Group":
    image
  • Enter "NT AUTHORITY\AUTHENTICATED USERS" and choose "Select in Clients":
    image
  • Repeat these steps for the other entity as well.
  • You're done.

Now we have created or imported an ADF file with the Business Data Catalog Definition Editor tool, exported it to an .xml file, imported it into SharePoint, set basic permissions on the entities.

Next, we should make sure that the application works in SharePoint by adding a Business Data Catalog-WebPart to a page.

Use the basic built-in BDC Web Parts

Awesome. Now that we have gotten this far by importing an ADF file into SharePoint and set appropriate permissions on the entities - We're ready to actually use the ADF connection to view stuff in our database.

Note: I have created a new blank site where I can easily show the built-in BDC Web Parts - so that's where I am adding my Web Parts.

 

  • Add two Web Parts to your page called "Business Data List" and "Business Data Item":
    (Note that when you've configured a BDC application, you'll see the Business Data web parts)
    image
  • Choose to edit the properties of the Business Data List Web Part:
    image
  • Click the Browse-icon to the right to pop up the BDC entity chooser:
    image
  • It will present you with the following interface (note, BDC applications will of course vary depending on what you have imported..):
    image 
  • Double click the "Employee" type, and then click "OK" in your Web Part property window.
  • Repeat this process for the "Business Data Item" Web Part, and select "Employee" in the BDC Type Picker as well.

Now we've got one BDC List Web Part which will list all employees, and one BDC Item Web Part that will display details about the employee we select.

In order for this to work we must connect the two Web Parts.

  • Edit menu of your Web Part -> Connections -> Send Selected item To -> Employee
    image

Test our BDC Application out, and make sure it works!

  • Choose "LastName" then "contains" and enter "smith":
    image
  • Select one of the results by clicking the radiobutton to the left, and see that the result (details) about the Employee shows up in the connected Web Part:
    image 

Resources and links

Summary

This article is a basic step-by-step guide to getting started with BDC in MOSS 2007. I've shown you every step from creating the databases required (in our case some sample databases) to creating the ADF file and to finally utilize the BDC connection from a site, using the BDC Web Parts.

In an upcoming post I will talk about how you can create your own BDC Web Parts! Keep your eyes open!


Published: Jun-25-09 | 34 Comments | 0 Links to this post

Debugging your code execution for anonymous users in SharePoint

Author: Tobias Zimmergren
URL: http://www.zimmergren.net

Introduction

Often when developing solutions that has anonymous users enabled, it can be hard to debug them from your local machine - because when you reach a point in your code where permissions higher than anonymous is required, SharePoint automatically tries to identify the user.

This means that if you're running local development, and is browsing as an anonymous user - everything can be fine until you hit a line of code in your application that requires authentication, you are then automatically logged in.

This makes it rather hard for anyone to truly debug their solutions in anonymous mode.

With this article I'm laying out the tips that I'm using to debug application requiring anonymous users, and making sure that I don't step up my privileges if the application needs to - I will now get an access denied instead.

Featured Solution that I am using

  • Enable Anonymous access for your web application
  • Enable anonymous access for your site and lists
  • Enable Remote Desktop on your development machine
    • If it is a virtual machine, you'll also need to give it access to the internet or at least the local network so you can RDP to it using Remote Desktop.
  • Hook up your Visual Studio debugger to the IIS worker process so your breakpoints can hit
  • Use the web browser on your LOCAL machine (not the development machine) to browse your site (remember, it has to be an IP reachable from the local machine - make sure your network settings are valid)
    • This ensures that whenever you hit a point in your code that doesn't allow anonymous users, it can not impersonate the account of the logged in user, which will result in an access denied exception. (Yes, this is where your breakpoints and debugging skills come in)
  • Now, when the breakpoint has hit - simply remote to your development machine (or use the lagged-out funked-up VPC console.. (no, use RDP!!)) and step through the code, as the breakpoint has hit!

Summary

Debugging anonymously accessible code can be a bit of a pain, but following my mentioned recommendations should make it a bit easier.

I tend to use this technique whenever I'm playing around with anonymous access, least-privilege code and things like that.

Hope it can help someone.


Published: Jun-05-09 | 3 Comments | 0 Links to this post
 Next >>