Jean Paul's Blog

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

    Advertisements
  • 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
  • Advertisements

Posts Tagged ‘programming’

SharePoint 2010 – Create Document Library

Posted by Paul on June 4, 2012

In this article we can explore the creation of Document Library through code. Here we are using existing Document Templates inside SharePoint to create a new document library.

Following are the activities involved in Document Library creation:

· Find the List Template

· Find the Document Template

· Create Document Library

Inside Visual Studio

Create a new console application and name it as DocLibCreation. Make sure you change the target framework to .Net 3.5.

Add the following code into the Program.cs file:

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet"))

{

using (SPWeb web = site.OpenWeb())

{

SPListTemplate listTemplate = web.ListTemplates["Document Library"];

SPDocTemplate docTemplate = (from SPDocTemplate dt in web.DocTemplates

where dt.Type == 122

select dt).FirstOrDefault();

Guid guid = web.Lists.Add("My Docs", "My Documents", listTemplate, docTemplate);

SPDocumentLibrary library = web.Lists[guid] as SPDocumentLibrary;

library.OnQuickLaunch = true;

library.Update();

}

}

Now run the application and you can see the new Document Library created inside SharePoint.

clip_image002


Document Templates

Following are the SharePoint 2010 document templates available:

Template ID

Description

100

No Template

101

Word 2003 document

103

Excel 2003 document

104

PowerPoint 2003 document

121

Word document

122

Excel document

123

PowerPoint document

111

OneNote Notebook

102

SharePoint Designer HTML document

105

ASPX Web Page

106

ASPX Web Part Page

1000

InfoPath document

Uploading Document

Now we can try uploading a document to the above library programmatically. Use the following code to upload an excel file. Make sure the application bin folder contains a file named sample.xlsx.

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet"))

{

using (SPWeb web = site.OpenWeb())

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary;

SPFile file = library.RootFolder.Files.Add("sample.xlsx", File.ReadAllBytes("sample.xlsx"));

}

}

You can see that the file is uploaded into SharePoint:

clip_image004

Downloading Document

Now we can try downloading a document from the above library programmatically. Use the following code:

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet"))

{

using (SPWeb web = site.OpenWeb())

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary;

SPFile file = web.GetFile(library.RootFolder.Url + "/sample.xlsx");

Stream stream = file.OpenBinaryStream();

FileStream fileStream = new FileStream("out.xlsx", FileMode.OpenOrCreate, FileAccess.Write);

int buffer = 4096;

int read = buffer;

byte[] bytes = new byte[buffer];

while (read == buffer)

{

read = stream.Read(bytes, 0, buffer);

fileStream.Write(bytes, 0, read);

if (read < buffer) break;

}

stream.Dispose();

fileStream.Dispose();

}

}

After running the program, you can see that the file is created in the bin folder.

clip_image006

This concludes the following activities:

1. Create Document Library

2. Upload a Document

3. Download a Document

References

http://www.learningsharepoint.com/2010/06/30/programatically-creating-document-sets-in-sharepoint-2010/

Summary

In this article we have the creation of document library through code. Please note that using the Document Type we can create different types of document library.

Advertisements

Posted in C#, SharePoint | Tagged: , , , | 6 Comments »

SharePoint 2010 – Create Document Library

Posted by Paul on June 4, 2012

In this article we can explore the creation of Document Library through code. Here we are using existing Document Templates inside SharePoint to create a new document library.

Following are the activities involved in Document Library creation:

· Find the List Template

· Find the Document Template

· Create Document Library

Inside Visual Studio

Create a new console application and name it as DocLibCreation. Make sure you change the target framework to .Net 3.5.

Add the following code into the Program.cs file:

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPListTemplate listTemplate = web.ListTemplates["Document Library"];

SPDocTemplate docTemplate = (from SPDocTemplate dt in web.DocTemplates

where dt.Type == 122

select dt).FirstOrDefault();

Guid guid = web.Lists.Add("My Docs", "My Documents", listTemplate, docTemplate);

SPDocumentLibrary library = web.Lists[guid] as SPDocumentLibrary;

library.OnQuickLaunch = true;

library.Update();

}

}

Now run the application and you can see the new Document Library created inside SharePoint.

clip_image002


Document Templates

Following are the SharePoint 2010 document templates available:

Template ID

Description

100

No Template

101

Word 2003 document

103

Excel 2003 document

104

PowerPoint 2003 document

121

Word document

122

Excel document

123

PowerPoint document

111

OneNote Notebook

102

SharePoint Designer HTML document

105

ASPX Web Page

106

ASPX Web Part Page

1000

InfoPath document

Uploading Document

Now we can try uploading a document to the above library programmatically. Use the following code to upload an excel file. Make sure the application bin folder contains a file named sample.xlsx.

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary;

SPFile file = library.RootFolder.Files.Add("sample.xlsx", File.ReadAllBytes("sample.xlsx"));

}

}

You can see that the file is uploaded into SharePoint:

clip_image004

Downloading Document

Now we can try downloading a document from the above library programmatically. Use the following code:

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary;

SPFile file = web.GetFile(library.RootFolder.Url + "/sample.xlsx");

Stream stream = file.OpenBinaryStream();

FileStream fileStream = new FileStream("out.xlsx", FileMode.OpenOrCreate, FileAccess.Write);

int buffer = 4096;

int read = buffer;

byte[] bytes = new byte[buffer];

while (read == buffer)

{

read = stream.Read(bytes, 0, buffer);

fileStream.Write(bytes, 0, read);

if (read < buffer) break;

}

stream.Dispose();

fileStream.Dispose();

}

}

After running the program, you can see that the file is created in the bin folder.

clip_image006

This concludes the following activities:

1. Create Document Library

2. Upload a Document

3. Download a Document

References

http://www.learningsharepoint.com/2010/06/30/programatically-creating-document-sets-in-sharepoint-2010/

Summary

In this article we have the creation of document library through code. Please note that using the Document Type we can create different types of document library.

Posted in C#, SharePoint | Tagged: , , , | 6 Comments »

SharePoint 2010 – Create List Definition using Visual Studio

Posted by Paul on June 4, 2012

In this article we can explore the List Definition creation using Visual Studio. Please note that the same can be achieved through SharePoint Designer as well.

Create List Definition Project

For starting use the List Definition project inside New Project dialog.

clip_image002

Enter the name as Coders. Select the site from the wizard as shown below.

clip_image004

Choose Custom List in the next step.

clip_image006

Enter the details as shown above and click the Finish button to close the wizard. Now the Solution Explorer looks like below:

clip_image008

Open the ListDefinition1>ListInstance1>Elements.xml (Please note that there are 2 Elements.xml inside the Solution Explorer)

Change the Title and Url attributes as following:

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/"&gt;

<ListInstance Title="Coders"

OnQuickLaunch="TRUE"

TemplateType="10000"

Url="Lists/Coders"

Description="My List Instance">

</ListInstance>

</Elements>

Now click the Build button and on succeed, right click the Project and click Deploy. If no error messages are there, the Deployment succeeded and you can see the new List inside SharePoint.

clip_image010

On clicking the Coders list you can see the new list opened in SharePoint.

Now we need to add a custom column to the List Definition. Our column is of Single line and name as CoderName. Following are the activities included in the Column Creation.

· Create a new Field

· Specify the properties like ID (GUID), Name etc.

· Add the Field Reference inside Default View

Inside the Fields section of Schema.xml add the following Field definition

<Field Type="Note" Name="CoderName" DisplayName="CoderName" Required="FALSE" ID="{1D54AAC6-DBB8-4454-91B7-E2FAE7697D6A}"></Field>

Inside the ViewFields section of the second View, add the following FieldRef node.

<FieldRef Name="CoderName"></FieldRef>

You can go back to SharePoint and Refresh the Coders List. The changes are visible there:

clip_image012

The new CoderName property is visible now. This concludes our List creation using Visual Studio. For adding more columns, use the Schema.xml file.

References

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

http://onlinecoder.blogspot.com/2011/03/simple-way-of-creating-sharepoint-2010.html

Summary

In this article we have explored the List Definition creation using Visual Studio. The attached source code contains the example we discussed. You can try building and deploying it.

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

SharePoint 2010 – Create List Definition using Visual Studio

Posted by Paul on June 4, 2012

In this article we can explore the List Definition creation using Visual Studio. Please note that the same can be achieved through SharePoint Designer as well.

Create List Definition Project

For starting use the List Definition project inside New Project dialog.

clip_image002

Enter the name as Coders. Select the site from the wizard as shown below.

clip_image004

Choose Custom List in the next step.

clip_image006

Enter the details as shown above and click the Finish button to close the wizard. Now the Solution Explorer looks like below:

clip_image008

Open the ListDefinition1>ListInstance1>Elements.xml (Please note that there are 2 Elements.xml inside the Solution Explorer)

Change the Title and Url attributes as following:

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/"&gt;

<ListInstance Title="Coders"

OnQuickLaunch="TRUE"

TemplateType="10000"

Url="Lists/Coders"

Description="My List Instance">

</ListInstance>

</Elements>

Now click the Build button and on succeed, right click the Project and click Deploy. If no error messages are there, the Deployment succeeded and you can see the new List inside SharePoint.

clip_image010

On clicking the Coders list you can see the new list opened in SharePoint.

Now we need to add a custom column to the List Definition. Our column is of Single line and name as CoderName. Following are the activities included in the Column Creation.

· Create a new Field

· Specify the properties like ID (GUID), Name etc.

· Add the Field Reference inside Default View

Inside the Fields section of Schema.xml add the following Field definition

<Field Type="Note" Name="CoderName" DisplayName="CoderName" Required="FALSE" ID="{1D54AAC6-DBB8-4454-91B7-E2FAE7697D6A}"></Field>

Inside the ViewFields section of the second View, add the following FieldRef node.

<FieldRef Name="CoderName"></FieldRef>

You can go back to SharePoint and Refresh the Coders List. The changes are visible there:

clip_image012

The new CoderName property is visible now. This concludes our List creation using Visual Studio. For adding more columns, use the Schema.xml file.

References

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

http://onlinecoder.blogspot.com/2011/03/simple-way-of-creating-sharepoint-2010.html

Summary

In this article we have explored the List Definition creation using Visual Studio. The attached source code contains the example we discussed. You can try building and deploying it.

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

SharePoint 2010 – List – Add, Edit, Delete using code

Posted by Paul on June 4, 2012

In this article we can experiment List manipulations through code. Following are the list operations to perform:

1. Add

2. Edit

3. Delete

Pre-Requisite

For proceeding with we need to create a List named Tasks using template Tasks.

clip_image002

Now create a new SharePoint Console Application project inside Visual Studio.

clip_image004

Make sure you changed the Application Target Framework to .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items.Add();

item["Title"] = "New Task";

item["Description"] = "Description of Task";

item.Update();

}

}

Now you can check the Tasks list inside SharePoint and you can see the new item there.

clip_image006

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item["Title"] = "Edited Task";

item["Description"] = "Description of Task (edited)";

item.Update();

}

}

Going back to SharePoint you can see the Edited Task

clip_image008

Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item.Delete();

}

}

Now you can go back to SharePoint and see that the item was deleted.

clip_image010

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented List manipulations Add, Edit, Delete through code. In real life we will be needed to automate List manipulations and programming will be a help in this regard.

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

SharePoint 2010 – List – Add, Edit, Delete using code

Posted by Paul on June 4, 2012

In this article we can experiment List manipulations through code. Following are the list operations to perform:

1. Add

2. Edit

3. Delete

Pre-Requisite

For proceeding with we need to create a List named Tasks using template Tasks.

clip_image002

Now create a new SharePoint Console Application project inside Visual Studio.

clip_image004

Make sure you changed the Application Target Framework to .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items.Add();

item["Title"] = "New Task";

item["Description"] = "Description of Task";

item.Update();

}

}

Now you can check the Tasks list inside SharePoint and you can see the new item there.

clip_image006

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item["Title"] = "Edited Task";

item["Description"] = "Description of Task (edited)";

item.Update();

}

}

Going back to SharePoint you can see the Edited Task

clip_image008

Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item.Delete();

}

}

Now you can go back to SharePoint and see that the item was deleted.

clip_image010

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented List manipulations Add, Edit, Delete through code. In real life we will be needed to automate List manipulations and programming will be a help in this regard.

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

SharePoint 2010 – List – Add, Edit, Delete using code

Posted by Paul on June 2, 2012

In this article we can experiment List manipulations through code. Following are the list operations to perform:

1. Add

2. Edit

3. Delete

Pre-Requisite

For proceeding with we need to create a List named Tasks using template Tasks.

clip_image002

Now create a new SharePoint Console Application project inside Visual Studio.

clip_image004

Make sure you changed the Application Target Framework to .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items.Add();

item["Title"] = "New Task";

item["Description"] = "Description of Task";

item.Update();

}

}

Now you can check the Tasks list inside SharePoint and you can see the new item there.

clip_image006

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item["Title"] = "Edited Task";

item["Description"] = "Description of Task (edited)";

item.Update();

}

}

Going back to SharePoint you can see the Edited Task

clip_image008

Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item.Delete();

}

}

Now you can go back to SharePoint and see that the item was deleted.

clip_image010

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented List manipulations Add, Edit, Delete through code. In real life we will be needed to automate List manipulations and programming will be a help in this regard.

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

SharePoint 2010 – List – Add, Edit, Delete using code

Posted by Paul on June 2, 2012

In this article we can experiment List manipulations through code. Following are the list operations to perform:

1. Add

2. Edit

3. Delete

Pre-Requisite

For proceeding with we need to create a List named Tasks using template Tasks.

clip_image002

Now create a new SharePoint Console Application project inside Visual Studio.

clip_image004

Make sure you changed the Application Target Framework to .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items.Add();

item["Title"] = "New Task";

item["Description"] = "Description of Task";

item.Update();

}

}

Now you can check the Tasks list inside SharePoint and you can see the new item there.

clip_image006

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item["Title"] = "Edited Task";

item["Description"] = "Description of Task (edited)";

item.Update();

}

}

Going back to SharePoint you can see the Edited Task

clip_image008

Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item.Delete();

}

}

Now you can go back to SharePoint and see that the item was deleted.

clip_image010

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented List manipulations Add, Edit, Delete through code. In real life we will be needed to automate List manipulations and programming will be a help in this regard.

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

SharePoint 2010 – LINQ and SPMetal

Posted by Paul on June 1, 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:

clip_image002

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 FilesCommon FilesMicrosoft SharedWeb Server Extensions14BIN

Open a command prompt and go to the specified folder:

clip_image004

Now run the following command:

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

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.

clip_image006

Create Application

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

clip_image008

Add reference to the following assembly:

clip_image010

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.

clip_image012

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:

clip_image014

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:

clip_image016

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:

clip_image018

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#, SharePoint | Tagged: , , , , | 2 Comments »

SharePoint 2010 – LINQ and SPMetal

Posted by Paul on June 1, 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:

clip_image002

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:

clip_image004

Now run the following command:

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

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.

clip_image006

Create Application

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

clip_image008

Add reference to the following assembly:

clip_image010

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.

clip_image012

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:

clip_image014

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:

clip_image016

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:

clip_image018

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#, SharePoint | Tagged: , , , , | 2 Comments »