Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Archive for June, 2012

How to create a List in SharePoint using Client Object Model?

Posted by JP on June 30, 2012

ClientContext clientContext = new ClientContext(“http://url”);

ListCreationInformation listCreationInformation = new ListCreationInformation();
listCreationInformation.Title = “New List Title”;
listCreationInformation.TemplateType = (int)ListTemplateType.Tasks;

list = clientContext.Web.Lists.Add(listCreationInformation);

clientContext.ExecuteQuery();

Advertisements

Posted in C# | Tagged: , , | 2 Comments »

SharePoint 2010 – Create Crawl Schedule

Posted by JP on June 29, 2012

In this article we can explore how to create a crawl schedule for the Search.

Following are the steps involved:

1. Open Central Administration web site as shown below:

clip_image002

2. Click on the Manage service applications link as highlighted above:

clip_image004

3. Click on the Search Service Application as highlighted above:

clip_image006

4. Click on the Content Sources link as highlighted above:

clip_image008

5. Click on the Local SharePoint sites cell and in the page on the right side you can see the Crawl Schedules.

clip_image010

You can see two item: Full Crawl and Incremental Crawl

Full Crawl

To start with we have to use Full Crawl. This will be time consuming and provides the starting point for Incremental Crawls. Full Crawl replaces all existing crawl contents regardless they have changed or not.

Incremental Crawl

These are faster crawls as they crawl only modified crawls. A Full Crawl has to be performed previously to do the Incremental Crawl.

6. Use the Create Schedule link to create a new Crawl Schedule

clip_image012

7. Enter the details in the appearing dialog and click the OK button

clip_image014

8. Click the OK button on the page

clip_image016

You can see that the site is reflected with the new crawl schedule:

clip_image018

References

http://social.technet.microsoft.com/wiki/contents/articles/full-and-incremental-crawls-in-microsoft-office-sharepoint-server-2007-search.aspx

Summary

In this article we have seen how to create a crawl schedule.

Posted in C# | Tagged: , | Leave a Comment »

Manage Search Scope

Posted by JP on June 29, 2012

In this article we can experiment with managing search scope.

Search Scope allows the user to search within a particular scope. By default SharePoint provides entire site collection search. If the user knows the search item is within a file system, he/she can specify the scope to narrow the search results. This will allows in faster locating of the context item.

The default search scope is All Sites.

Adding a new Search Scope

1. Open SharePoint Central Administration > Manage Service Applications > Search Service Application page

image

2. Click on the Scopes link as highlighted above

image

3. Click on the New Scope link from the appearing page. Enter the details as shown below and click the OK button.

image

4. Click the Add rules for our newly created scope as shown below

image

5. Set the properties as shown below (Pointing to our File System Content Source)

image

Click the OK button to continue. Now we are ready with a Scope set with rules. But in order to view the scope in Search drop down list, we need to do the following steps.

6. Click Search Administration > Start Updating Now link as shown below

image

7. Now open our default SharePoint site and open the Site Settings > Search scopes

image

8. Click the Display Groups button from the top bar as shown below

image

9. Select the Edit Display Group option as shown below.

image

10. Select the File System Scope and click the OK button

image

Now the Search Scope is ready within our site. You can experiment it by opening a site and selecting the scope from the scope drop down list.

image

References

http://office.microsoft.com/en-us/sharepoint-server-help/managing-search-scopes-HA001160438.aspx

Summary

In this article we can experimented the manage search scope feature of SharePoint. In the real world scenario Administrators need to configure different search scopes for different site collections.

Posted in C# | Tagged: , | Leave a Comment »

SharePoint 2010 Project – Foster – Part 1

Posted by JP on June 24, 2012

As promised please find the Part 1 of the project named Foster.

Part 1: Requirement Specification

(In this document I have not included complex business rules/attributes to stay more focused on SharePoint skills)

image

Please download the above link and read it 2-3 times to get an overview of the project.

I will be coming up with the next part soon!

Note: After downloading you might need to Unblock the file to start reading.

Posted in C# | Tagged: , , | Leave a Comment »

Coming Soon: SharePoint 2010 Projects!!!

Posted by JP on June 21, 2012

Hello Friends, Thank You all for supporting me through the community posts and replies.

image

Now I would like to go ahead one level more by creating real world SharePoint Projects.  The motivation was given from my colleagues and friends who wanted to see SharePoint in Action in real world scenarios.

image

Above All it will be based on the SDLC format of:

  1. Requirement Specification
  2. Design Document
  3. Implementation
  4. Documentation

As always i am open for queries, helps and discussing your opinions on architectural decisions.

Hope You will enjoy it!

Posted in C# | Tagged: , , | 4 Comments »

Search – Content Sources

Posted by JP on June 20, 2012

In this article we can explore Content Sources and how to add a new Content Source.

Content Sources

Content Source represents the origin of content. As SharePoint handles various contents like Database, File System etc. there should be a Indexing Service to handle all these sources.

Please have a note that SQL Server is having Full Text Search index, but SharePoint has its own Indexing engines.

By default SharePoint searches in the site collection and document libraries.

Using Custom Content Source configuration we can make SharePoint search the possible areas:

· File System Drives

· Network Drives

· Lotus Notes Data

· Web Sites

Adding new Content Source

In this example we are trying to add a File System content source. After adding, the user will be able to search on the files and contents inside it.

Following are the steps involved:

1. Create a Share Folder named Contents with a Text File inside it and make Read/Write permissions to Everyone

clip_image002

Ensure that the above folder contains a text file with data for eg: MyTodo

2. Open the Central Administration web site and click on Manage Service Applications link

clip_image004

3. Click on Search Service Applications from the appearing page

clip_image006

4. Click the Content Sources link from the left pane

clip_image008

5. Click on the New Content Source link from the appearing page

clip_image010

6. Enter the following details in the Content Source page

clip_image012

Click the OK button and the Crawler will be performing a crawl.

7. Go back to the main site and enter the keyword to search for (MyToDo). You can view the following results.

clip_image014

This concludes our article on adding Content Source and doing a sample search.

Viewing Crawl History

We can always view the crawl log to check the activity was successful and view the errors if not. Use the View Crawl Log command to view this.

clip_image016

Starting Crawls

We can start / stop / pause crawls manually by using the command bar as shown below. Please note that only after a full crawl the data will be searchable.

clip_image018

Summary

In this article we have explored how to add a content source inside SharePoint site.

Posted in C# | Tagged: , | Leave a Comment »

SharePoint 2010 – Search

Posted by JP on June 20, 2012

In this article we can explore one of the core features of SharePoint. It is considered to be the Enterprise Feature of SharePoint. SharePoint allows configuration of Search based on different parameters. In short we can configure the breadth and depth of the search.

Search Architecture

Inside SharePoint 2010 Search is built as a service application. The Search Engine can Index SharePoint Sites, External contents, Files, Web sites etc.

Following are the server roles inside the SharePoint Search:

1. Crawler

2. Indexer

3. Query Servers

4. Search Center

Crawlers represent small programs which are scheduled to run on specific intervals. The Crawlers pass through each Content Source and Index the words in one location. These programs will be scanning Documents, Files and other Content Sources. Crawling consists of Full Crawl and Incremental Crawl. We can manually start the crawling process as well as schedule it.

The Indexer will create index files which contains the words and corresponding content source information for easier access. The indexing server can be configured to be a separate machine in a farm.

As the crawler will be encountering lots of file types like Word Document, PDF Document, Excel Document, Web sites, Text Files etc. it will be run out of logic on indexing these. We need to specify external Index Filters to tell how to index those file types. These Index Filters are also known as IFilter. The IFilter reads the contents of the file, creates the index keywords based on the content. Administrators need to configure each file type with an appropriate IFilter.

The Query Server is responsible for handling user search queries. In a farm environment query server can be configured to be a separate machine. The query serve operates on the index files for returning search results.

Search Center is a site inside SharePoint 2010 oriented towards Search. It allows configuring of Results, Advanced Search options, Navigation Elements etc. The user can create his own Search Site by using the Basic Search Center template.

Experimenting with Search

Now we can start experimenting with the Search User Interface and the functionality. The default Search box is available on the site as shown below:

clip_image002

Now we can try searching some text. Enter the address word of a contact and click the search button.

clip_image004

You can see the following results showing the data from Manager List and Edit form.

clip_image006

The search result fetched the contents of all list items inside the site. Now we can try searching with keyword Manager. The result will include the Manager list item name too.

clip_image008

References

http://technet.microsoft.com/en-us/sharepoint/ee518667

http://technet.microsoft.com/en-us/library/cc263144(office.12).aspx

http://msdn.microsoft.com/en-us/library/ms545957(v=office.12).aspx

Summary

In this article we have learnt the Search feature of SharePoint. Although Search is configured by SharePoint Administrators still the Developer can use the extended Search web services, Programmatic retrieval of content using Object Model etc.

Posted in C# | Tagged: , | Leave a Comment »

SharePoint 2010 – Client Object Model – C#, Silverlight, JavaScript supported

Posted by JP on June 20, 2012

In this article I would like to discuss about the Client Object Model feature of SharePoint 2010.

Overview

Client Object Model is a new feature of SharePoint 2010. It provides programming against SharePoint site using .Net Managed Code or JavaScript.

The Client Object Model provides almost all the Programming features of Server Object Model plus advantages on Deployment. The Client OM (Client Object Model) is being used as the core programming aid for SharePoint 2010 and thus widely used in market.

Advantages

1. Less Deployment Hassles: Using Client OM, you do not need to install the components required by Server Object Model. Thus Client OM provides much ease to the end user.

2. Language Flexibility: We can use the following languages to work with Client OM:

a. Microsoft .Net

b. Silverlight

c. ECMA Script (JavaScript / Jscript)

3. Query Speed Optimizations: In the Client OM, reduced network traffic is attained using Query Optimizations. Thus the user will feel reduced round trips and other advantages like paged results etc.

How it works?

The Client OM works by sending an XML Request. The server will be returning a JSON response which is the converted to the appropriate Object Model.
image

Supported Languages

Following are the programming language/platform supported for Client Object Model.

· .Net Languages (C#, VB.NET etc.)

· Silverlight

· Scripting Languages (JavaScript, Jscript)

Core Assemblies

There are 2 assemblies to be referred for working with Client Object Model.

1. Microsoft.SharePoint.Client.dll

2. Microsoft.SharePoint.Client.Runtime.dll

These assemblies can be found in the 14 Hive folder:

%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\ISAPI

image

Classes inside Client Object Model

In C#, comparing with the classes of Server Object Model we can see that Client Object Model have similar classes with a suffix in the namespace and no SP prefix in the class name.

For example: An SPSite in Server Object Model is represented in Client OM as Site with namespace Microsoft.SharePoint.Client.

Client Object Model

Server Object Model

Microsoft.SharePoint.Client.ClientContext

SPContext

Microsoft.SharePoint.Client.Site

SPSite

Microsoft.SharePoint.Client.Web

SPWeb

Microsoft.SharePoint.Client.List

SPList

Example

Following is the example of retrieving a list from server using Client OM:

ClientContext context = new ClientContext("http://hp");

List list = context.Web.Lists.GetByTitle("Tasks");

context.Load(list);

context.ExecuteQuery();

Console.WriteLine(list.Title);

Console.ReadKey(false);

I should remark something about the above code:

· Even though there are multiple calls, they are send to Server until ExecuteQuery() is called

· Network round trips between client and server is reduced combining multiple calls into one

· Object Identity is used to setup the queries. Object Identities are those which refer to the Server Object Model. Object Identities are valid only for the current client context

More Examples with Client Object Model

Here I would like to list some of the examples using Client Object Model. For starting with the examples please do the following:

1. Create a Windows Application

2. Change the Target Framework to .Net 4.0

3. Add reference to Microsoft.SharePoint.Client, Microsoft.SharePoint.Client.Runtime

Before continuing with the examples please ensure the site have valid data items in the Tasks list. We will be changing the data items during our session.

1. Get List Items

Here we are querying the list items of Tasks list.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection items = list.GetItems(query);

context.Load(list);

context.Load(items);

context.ExecuteQuery();

After executing the code, the result can be stored into a DataTable as shown below.

DataTable table = new DataTable();

table.Columns.Add("Id");

table.Columns.Add("Title");

foreach (ListItem item in items)

table.Rows.Add(item.Id, item["Title"]);

datagrid.DataSource = table;

On my machine the data retrieves is shown below:

image

2. Update List Items

Here I would like to show the modification code. All the Title is appended with two asterisks who’s Id are of even number.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection items = list.GetItems(query);

context.Load(items);

context.ExecuteQuery();

foreach(ListItem item in items)

if ((item.Id % 2) == 0)

{

item["Title"] += "**";

item.Update();

}

context.ExecuteQuery();

After executing the query, please refresh the data grid using the Get Data button. You can see the following result.

You can see that the Titles are modified for those with Id are an even number.

 

image

3. Get By Row Limit

Here we can experiment with the Row Limit tag inside CAML queries. You can note that while accessing list we are actually using a CAMLQuery class instance. Inside the query it is possible to set the RowLimit tag as well.

The RowLimit tag restricts the number of items retrieved from the server. Thus we can save a lot of bandwidth by reducing the rows while doing search.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

List list = web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View><RowLimit>3</RowLimit></View>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems);

context.ExecuteQuery();

You can see that the RowLimit is set to 3. On executing the query and displaying the results to a data grid you can see 3 items as shown below.

image

4. Get By Search Criteria

Now we can try selecting the list items using search criteria. Here we are trying to get the items of Status as ‘In Progress’.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = @"<View>

<Query>

<Where>

<Eq>

<FieldRef Name=’Status’/>

<Value Type=’Text’>In Progress</Value>

</Eq>

</Where>

</Query>

</View>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems, items => items.Include(

item => item["Id"],

item => item["Title"],

item => item["Status"]

));

context.ExecuteQuery();

On executing the code above you will get the results filtered by the Status field.

image

5. Insert an Item

Here we can try with inserting a new item into the Tasks list.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

List list = web.Lists.GetByTitle("Tasks");

ListItemCreationInformation newItem = new ListItemCreationInformation();

ListItem listItem = list.AddItem(newItem);

listItem["Title"] = "New Item Created through C#";

listItem.Update();

context.ExecuteQuery();

You can see that we are using a new class named ListItemCreationInformation along with the ListItem class. This information will be recorded and passed to the server once the ExecuteQuery() method is called.

On executing the above code and retrieving the results you can see the output as below:

image

6. Update an Item

The Update operation is next in the series of the CRUD pattern. Already we have seen updating the Title. Here you can see updating the Status.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems);

context.ExecuteQuery();

ListItem item = listItems[listItems.Count – 1];

item["Status"] = "In Progress";

item.Update();

context.ExecuteQuery();

On executing the code you can see that the last item was updated.

image

7. Delete an Item

Now we can try deleting an item from the List. Here is the code to achieve that.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

ListItemCollection listItems = list.GetItems(new CamlQuery() { ViewXml = "<View/>" });

context.Load(listItems);

context.ExecuteQuery();

listItems[listItems.Count – 1].DeleteObject();

context.ExecuteQuery();

We need to call the DeleteObject() method of the item followed by the ExecuteQuery().

8. Reducing the Result Size by Specifying Properties

So what if you wanted only 1 property value for an item with 10 properties. There will be unwanted transferring of 9 columns. Here we can see how to specify only the needed columns for an item.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

context.Load(web, w => w.Title);

context.ExecuteQuery();

MessageBox.Show("The title is: " + web.Title);

MessageBox.Show("Now trying to access a field not in Result Set (expect exception)");

try

{

MessageBox.Show(web.Description); // You will get Error here

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

Here we can see that only the Title property has been specified for retrieval. Accessing the Description column throws an exception.

9. Reducing the Result Size in List

In the case of list the problem is worse as there are n number of columns for the list. The result will be multiplied n times. So if we need only 1 column and retrieve 10 columns for a list of 1000 items, we end up in getting 9 x 1000 unwanted column values.

So to specify the list columns in the Result Set the syntax will be slightly different.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems, items => items.Include(item => item["Id"]));

context.ExecuteQuery();

Please note the way Id is specified. While filling the results you should take care that only the Id column value is accessed.

DataTable table = new DataTable();

table.Columns.Add("Id");

foreach (ListItem item in listItems)

table.Rows.Add(item.Id);

datagrid.DataSource = table;

10. Specifying Credentials

You can specify user Credentials while accessing the SharePoint server. The property Credentials is for this purpose.

ClientContext context = new ClientContext(ServerText.Text);

context.Credentials = new NetworkCredential("User", "Password");

Web web = context.Web;

context.Load(web);

context.ExecuteQuery();

MessageBox.Show(web.Title);

Please specify the correct user name and password of your site otherwise Unauthorized Exception will be thrown.

So this concludes the article with Client Object Model examples for the most common scenarios. In the real world you will need much more complicated steps and I believe these will provide a base to achieve it.

When to use Server Object Model?

We can use it on the SharePoint server where the Server Object Model binaries are available. Typical example would be inside Web Parts / Workflows.

When to use Client Object Model?

We can use it from client machines where the entire SharePoint binaries are not available. A typical example would be from Windows Form application in a client machine.

References

MSDN on Client Object Model

Technet Blog on Client Object Model

Summary

In this article we have seen an overview about Client Object Model in SharePoint 2010. The source code attached contains various samples of working with the Client Object Model.

Posted in C# | Tagged: , , | 1 Comment »

SharePoint 2010 – Web Services

Posted by JP on June 16, 2012

SharePoint Web Services provides is a good feature that allows us to access or change the SharePoint items remotely. We can use the Web Services to add more power to our application.

Following are the core features of SharePoint Web Services:

· Foundation and Server Web Services

· More Interoperability compared with Server Object Model

· Above 25 Web Services

· Manage Sites, Lists, Libraries, and Picture Libraries etc.

· Run queries against the server

· Custom Web Service creation possible

The following table contains some of the web services inside SharePoint 2010.

Service

Description

ASMX

WebSvcAdmin

Creation and Deletion of sites

Admin.asmx

WebSvcLists

List Management service

Lists.asmx

WebSvcAlerts

List Item Events service

Alerts.asmx

WebSvcAuthentication

Authentication based service

Authentication.asmx

WebSvcsites

Web sites management service

Sites.asmx

WebSvcspsearch

Searching service

Search.asmx

A more detailed list can be found here:

http://msdn.microsoft.com/en-us/library/ee705814.aspx

How to find the url of a Service?

The url of a service can be located inside _vti_bin folder of the site or site collection. Each site or site collection will be having this folder with all the web services inside it with .asmx extension.

Example: To use the search service use the following url:

http://YOURPCNAME/_vti_bin/search.asmx

clip_image002

Using http://appes-pc/_vti_bin/Lists.asmx

clip_image004

Adding Reference to Project

Now we can try adding reference to the service inside Visual Studio application. Create a new Ordinary Console Application (please note that we are not using SharePoint Console Application)

clip_image006

Now we need to Add Web Reference. In Visual Studio 2010 this option is available under the Add Service Reference option as shown below.

clip_image008

In the appearing dialog click the Advanced button.

clip_image010

In the next dialog, choose Add Web Reference option.

clip_image012

You will get the following dialog. This dialog is suitable for adding web service references.

clip_image014

Enter the url of the Lists.asmx as shown above. You need to replace the pc name with yours.

Set a Web reference name in the second highlighted box. This serves as the namespace.

Click the Add Reference button and your proxy class and related classes will be ready within a while. Inside the Program.cs enter the namespace and you can see the classes inside it as shown below:

clip_image016

Invoking the Proxy Class

Our class of interest is the Lists proxy. You can create an instance of it using the following code:

SPReference.Lists client = new SPReference.Lists();

Setting Credentials

Whenever we open a SharePoint site (without anonymous login enabled) the site will be prompting with user credentials. As we are invoking through web service the prompt dialog won’t be working. We need to pass the credentials using the property named Credentials.

client.Credentials = new NetworkCredential("appes", "password"); / // using System.Net;

Getting Reference to a List

We can try getting a reference to the Manager List inside our site. The Managers list contains items with columns:

· Title

· Name

· Address

clip_image018

Use the following code to fetch the data and display it to the console:

SPReference.Lists client = new SPReference.Lists();

client.Credentials = new NetworkCredential("appes", "PWD");

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");

viewFields.InnerXml = "<FieldRef Name=\"Title\" />" +

"<FieldRef Name=\"Name\" />" +

"<FieldRef Name=\"Address\" />";

XmlNode listItems = client.GetListItems("Manager", null, null, viewFields, null, null, null);

foreach (XmlNode node in listItems)

if (node.Name == "rs:data")

for (int f = 0; f < node.ChildNodes.Count; f++)

{

if (node.ChildNodes[f].Name == "z:row")

{

string title = node.ChildNodes[f].Attributes["ows_Title"].Value;

string name = node.ChildNodes[f].Attributes["ows_Name"].Value;

string address = node.ChildNodes[f].Attributes["ows_Address"].Value;

Console.WriteLine(title + " " + name + " " + address);

}

}

Console.ReadKey(false);

On executing the application we can see the following result:

clip_image020

Following are the steps involved in getting list item data:

1. Create List Proxy client

2. Set Credentials

3. Set the View Columns

4. Invoke GetListItems() method

5. Iterate through the nodes

6. Get value of node having name z:row

Note

Using web services, xml is used to represent the data. For advanced programming using properties please refer to the Server Object Model and SharePoint LINQ articles.

References

http://msdn.microsoft.com/en-us/library/ee705814.aspx

http://msdn.microsoft.com/en-us/library/ms583494.aspx

http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems(v=office.12).aspx

Summary

In this article we have seen the Web Services feature of SharePoint 2010. It provides the flexibility of interoperability compared with the Server Object Model. Developers can access and manage SharePoint site from non .Net platforms like Java. The attached source code contains the example we discussed.

Posted in C# | Tagged: , | 2 Comments »

SharePoint 2010 – LINQ and SPMetal

Posted by JP on June 16, 2012

In this article we can explore some of the advanced programming areas.

·         LINQ to SharePoint

·         SPMetal

LINQ to SharePoint is a new feature of SharePoint 2010.  LINQ stands for Language Integrated Query which is a part of .NET Language. The aim of LINQ is to support different data sources using the same Typed Query Syntax.  Presently it supports Objects, Datasets, SQL, Entities, XML etc.

Why we need LINQ?

You might have noted that the previous List Programming examples did not used proper column name access.  LINQ allows us to access the List in a Typed manner.  Adding more clarity we can access the list items based on the column names which we usually do with the databases.

Example: var result = from c in Citizen where c.Name == “John” select c;

What is SPMetal?

As we will be creating custom lists having custom column names, we need to generate the Entity Model.  The SPMetal.exe is the tool which helps in generating the Model classes.

Although we can create the Model classes manually, it will be a tedious job and error prone.  Using SPMetal would be the right approach to model classes.

Activities

Following are the activities performed in this article:

1.      Manager List Creation

2.      Entity Creation

3.      Read using LINQ

4.      Insert Entity

5.      Update Entity

6.      Delete Entity

 

 

Experimenting with LINQ and SPMetal

To start with create a custom list inheriting from Custom List and name it as Manager.  Add the following custom columns and data:

image

Generating the Entity Models

Now we can generate the Entity Model for the above List.

You can get the SPMetal.exe inside the following folder:

            C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

Open a command prompt and go to the specified folder:

image

Now run the following command:

            SPMetal.exe /web:http://YOURSITE /code:SiteEntities.cs

(remember: no spaces before / after the colon(:))

Wait for a while and you will be ready with the new file.  Open the file SiteEntities and you can see the Manager class is contained inside.

image

Create Application

Create a new SharePoint > 2010 > Console Application (targeting .Net 3.5 framework) and add the SiteEntities.cs file into it.

image

Add reference to the following assembly:

image

You can try with the following operations Read, Insert, Update, Delete using LINQ to SharePoint

 

Selecting an Item

Now we are trying to select the managers with country as USA:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    var result = context.Manager.Where(m => m.Country == “USA”);

 

    foreach (ManagerItem manager in result)

    {

        Console.WriteLine(manager.Name);

    }

}

 

Note: You can use LINQ or Lambda Expression to do the query.  In the above example I have used Lambda.

On executing the application you can see the following results.

image

Inserting an Item

For inserting a new item into the Manager list, use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = new ManagerItem();

    manager.Name = “New Manager”;

    manager.Address = “New Address”;

    manager.Country = “New Country”;

 

    context.Manager.InsertOnSubmit(manager);

    context.SubmitChanges();

}

 

After executing the application, open the Manager list inside SharePoint as shown below:

image

Updating an Item

For updating an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = context.Manager.Where(m => 

                          string.IsNullOrEmpty(m.Title)).FirstOrDefault();

    if (manager != null)

        manager.Title = “New Title”;

 

    context.SubmitChanges();

}

You can see the updated entity inside SharePoint:

image

Deleting an Item

For deleting an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = context.Manager.Where(m => m.Title.Length > 3).FirstOrDefault();

    if (manager != null)

        context.Manager.DeleteOnSubmit(manager);

 

    context.SubmitChanges();

}

 

You can see that the item is deleted inside SharePoint:

image

This concludes our Read, Insert, Update, Delete operations using LINQ to SharePoint.  Hope the topics are understood by the reader.

References

            http://msdn.microsoft.com/en-us/library/ee535491.aspx

            http://msdn.microsoft.com/en-us/library/ee538255.aspx

Summary

In this article we have explored LINQ and SPMetal tool.  This information is necessary in the real world programming scenarios.  The attachment contains the source code we discussed.

Posted in C# | Tagged: , | Leave a Comment »