Walkthrough on using LINQ to SharePoint from within a SharePoint 2010 custom visual web part

Objective

In this article we will see,

1. How to create custom WebPart.

2. How to use SPGridView on visual WebPart.

3. How to use LINQ to SharePoint

4. How to deploy the WebPart in SharePoint site.

Step 1

Open Visual studio 2010 and create new project. From SharePoint 2010 project template select Visual Web Part project.

clip_image002

Step 2

Provide the SharePoint site URL, where you want to debug and deploy the Visual Web Part.

clip_image004

Before clicking on Finish, click on Validate button to validate whether you are able to successfully connect SharePoint site or not.

clip_image005

Step 3

Create DataContext class or LINQ to SharePoint proxy class.

Open the command prompt and change directory to

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

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

clip_image007

Now we need to create the context class for corresponding list definitions.

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

tal.exe /web:http://dhananjay-pc/my/personal/Test1 /namespace:nwind /code:Product.cs

In above command we are passing few parameters to spmetal.exe, they are as below

a. /web:Url

Here we need to provide URL of SharePoint site

/web:http://dhananjay-pc/my/personal/Test1 /

://dhananjay-pc/my/personal/Test1 / is URL of SharePoint site, I created for myself. You need to provide your SharePoint site URL here.

b. /namespace:nwind

This would be the namespace under which class of the list will get created. In my case name of the namespace would be nwind.

c. /code:Product.cs

This is the file name of the generated class. Since we are giving name Product for the file then class generated will be ProductDataContext

Step 4

Add created DataContext class to the Project or LINQ to SharePoint proxy class.

Now add this class to the project. To do this, right click on the visual web part project and select Add existing item. Then browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN and select Product.cs

Add references to the Project

Microsoft.SharePoint

Microsoft.SharePoint.Linq

Right click on Reference and select Add Reference. To locate Microsoft.SharePoint and Microsoft.SharePoint.Linq dll browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI. All the SharePoint dll are here in this location.

clip_image008

Step 5

Add SPGridView on the Web Part

Now open the Visual Web Part project and open VisualWebPart1Usercontrol.ascx

clip_image009

Add the below markup to create one SPGridView

clip_image011

In markup in DataField we need to provide column name of SharePoint list to bind the list items to SPGridView column

VisualWebPart1UserControl.ascx

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs" Inherits="VisualWebPartProject1.VisualWebPart1.VisualWebPart1UserControl" %>
<%@ Import Namespace="Microsoft.SharePoint.WebControls" %>
<SharePoint:SPGridView ID="sp1" runat="server" AutoGenerateColumns="false" >
<HeaderStyle HorizontalAlign="Left" ForeColor="Blue" Font-Bold="true" />
<Columns>
<SharePoint:SPBoundField DataField="ProductId" HeaderText="Product ID" ></SharePoint:SPBoundField>
<SharePoint:SPBoundField DataField="ProductName" HeaderText="Product Name" ></SharePoint:SPBoundField>
<SharePoint:SPBoundField DataField="ProductPrice" HeaderText="Product Price" ></SharePoint:SPBoundField>
</Columns>
</SharePoint:SPGridView>

Step 6

Now write code behind for SPGridView

Add the namespaces

clip_image012

Write the below code to fetch the List items from SharePoint list using LINQ to SharePoint

VisualWebPart1UserControl.ascx.cs

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Linq;
using nwind;
using System.Linq;

namespace VisualWebPartProject1.VisualWebPart1
{
 public partial class VisualWebPart1UserControl : UserControl
 {
 protected void Page_Load(object sender, EventArgs e)
 {

ProductDataContext context = new ProductDataContext(SPContext.Current.Web.Url);
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 var result = from r in products select r;
 sp1.DataSource = result;
 sp1.DataBind();
 }
 }
}

In above code Test1_Product is name of the SharePoint list.

Step 7

Deploy the WebPart to SharePoint site. For that we need to right click on the Visual Web Part project and click Deploy.

clip_image013

Step 8

Open the SharePoint site where you have deployed the visual web part and select the Edit page option .

After that select Insert

clip_image015

After clicking Insert select WebPart to insert

clip_image017

From the custom category select visual web Part.

clip_image018

Note: Name of the project we created in first step. Name I gave was VisualWebPart1 . In custom category you will find name you gave of the project in step1.

After selecting the WebPart click on Add button. And after clicking button on the home page you will get the custom WebPart populated with Test_Product list items.

clip_image020

LINQ to SharePoint with WCF 4.0

Objective

How could we perform CRUD operations on SharePoint 2010 List from a WCF Service? Assume we need to create a WCF Service and that service will perform CRUD operation on SharePoint 2010 list. We are going to see that in this article.

Flow Diagram

clip_image001

Now we will follow the below steps to perform all above operations.

Step 1: Setting up the SharePoint list

We have a custom list

1. Name of the list is Test_Product.

2. Columns of the list is as below ,

clip_image003

3. There are two items in the list

clip_image005

4. URL of the SharePoint site is

http://dhananjay-pc/my/personal/Test1

Now we will access the SharePoint site on above URL.

Step 2 Creating WCF Service

Now we will create a WCF Service. WCF Service will have four operation contracts for CRUD operation on list.

To create WCF service, open visual studio and from WCF tab select WCF Service application.

clip_image007

Now to make sure that we would able to use SPLinq or LINQ to SharePoint we need to change the target framework and Platform target

So to do those follow as below,

1. Right click and click on Properties of WCF Service

clip_image008

2. Click on the Build tab and change Platform Target to Any CPU.

clip_image010

3. Click on the Application tab and change the Target framework type to .Net Framework 3.5

clip_image012

Now we need to create DataContext class of SharePoint list such that we can perform LINQ against that class to perform CRUD operation. To create context class we need to perform below steps.

1. Open the command prompt and change directory to

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

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

clip_image014

2. Now we need to create the class for corresponding list definitions.

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

tal.exe /web:http://dhananjay-pc/my/personal/Test1 /namespace:nwind /code:Product.cs

In above command we are passing few parameters to spmetal.exe, they are as below

a. /web:Url

Here we need to provide URL of SharePoint site

/web:http://dhananjay-pc/my/personal/Test1 /

://dhananjay-pc/my/personal/Test1 / is URL of SharePoint site, I created for myself. You need to provide your SharePoint site URL here.

b. /namespace:nwind

This would be the namespace under which class of the list will get created. In my case name of the namespace would be nwind.

c. /code:Product.cs

This is the file name of the generated class. Since we are giving name Product for the file then class generated will be ProductDataContext

The classes default gets saved in the same folder with SPMetal.exe. So to see where the class got created we need to navigate to folder

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

Add created class to the WCF Service project

Now add this class to the project. To do this, right click on the WCF Service project and select Add existing item. Then browse to above path and select Product.cs

Host the WCF Service in IIS

To work with SPLInq in WCF service, we need to host the service in IIS with the same application pool SharePoint is running.

See the below link for step by step explanation on how to host WCF 4.0 Service in IIS 7.5

http://dhananjaykumar.net/2010/09/07/walkthrough-on-creating-wcf-4-0-service-and-hosting-in-iis-7-5/

Only we need to make sure that,

Hosted WCF service is sharing the same application pool with SharePoint.

clip_image015

Select the Application pool to SharePoint-80

Create Contracts

We need to create DataContract or Data Transfer object. This class will represent the Product Data context class (We generated this class in previous step) 0

Create Data Contract,

[DataContract]
 public class ProductDTO
 {
 [DataMember]
 public string ProductName;
 [DataMember]
 public string ProductId;
 [DataMember]
 public string ProductPrice;
 }

Add References to work with LINQ to SharePoint

Microsoft.SharePoint

Microsoft.SharePoint.Linq

Right click on Reference and select Add Reference. To locate Microsoft.SharePoint and Microsoft.SharePoint.Linq dll browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI. All the SharePoint dll are here in this location.

Add the namespace

clip_image016

Nwind is the name of the namespace of the data context class we created in previous steps. We need to make sure that we have added Product class to the WCF Service application project as Add an Existing item.

Create Service Contract

We need to create Service contract. There would be four operation contracts each for one operation on Sharepoint list.

IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Description;

namespace WcfService1
{
 [ServiceContract ]
 public  interface IService1
 {

[OperationContract]
 List<ProductDTO> GetProduct();

[OperationContract]
 bool InsertProduct(ProductDTO product);

[OperationContract]
 bool UpdateProduct(ProductDTO product);

[OperationContract]
 bool DeleteProduct(ProductDTO product);

 }

In above code

1. Creating instance of ProductDataContext.

2. Using LINQ to SharePoint retrieving all the list items.

3. Creating instance of ProductDTO class with values fetched from SharePoint list

4. Adding the instance of ProductDTO class in List of ProductDTO.

5. Returning list of ProductDTO

Inserting an element in List

 public bool InsertProduct(ProductDTO product)
 {
 try
 {
 using(ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 Test1_ProductItem itemToInsert = new Test1_ProductItem()
 {
 ProductId = product.ProductId ,
 ProductName = product.ProductName ,
 ProductPrice = Convert.ToDouble(product.ProductPrice)
 };
 products.InsertOnSubmit(itemToInsert);
 context.SubmitChanges();
 return true;
 }
 }
 catch (Exception ex)
 {
 return false;
 }

}

In above code

1. Boolean is being returned. If item will get saved successful then true will return by the service else false.

2. Instance of ProductDataContext being created and submitchanges() will be called on instance of ProductDataContext.

3. Instance of Test_ProductItem is being created and we are passing values from ProductDTO to create instance of Test_ProductItem. Point we need to note here is that Test_Product is name of the SharePoint list.

4. Calling InsertOnSubmit() to submit a list to item to get inserted.

Updating an Element in the List

 public bool UpdateProduct(ProductDTO product)
 {
 try
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 var itemToUpdate = (from r in context.Test1_Product where r.ProductId == product.ProductId select r).First();
 itemToUpdate.ProductName = product.ProductName;
 itemToUpdate.ProductPrice = Convert.ToDouble(product.ProductPrice);
 context.SubmitChanges();
 return true;
 }
 }
 catch(Exception ex)
 {
 return false;
 }

 }

In above code

1. We are fetching list item to be updated on basis of ProductId of ProductDTO.

2. Assigning the new values

3. Performing the submitchnages on instance of ProductContext class.

Deleting an Element from the List

 public bool DeleteProduct(ProductDTO product)
 {
 try
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 var itemToDelete = (from r in context.Test1_Product where r.ProductId == product.ProductId  select r).First();
 products.DeleteOnSubmit(itemToDelete);
 context.SubmitChanges();
 return true;
 }
 }
 catch (Exception ex)
 {
 return false;
 }
 }

In above code

1. We are fetching the list item to be deleted.

2. Calling DeleteOnSubmit() and passing the item to be deleted.

3. Calling SubmitChanges() on instance of ProductContext.

Modify the Web.Config

1. We will put Binding as basicHttpBinding.

2. In ServiceBehavior attribute , we will enable the servicemetadata

3. In ServiceBehavior , we will make IncludeserviceException as false.

4. We will configure MetadataExchnagePoint in the service

So, Now in Web.Config Service configuration will look like

 <system.serviceModel>
 <behaviors>
 <serviceBehaviors>

 <behavior name="MyBeh">
 <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

 <serviceMetadata httpGetEnabled="true"/>
 <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
 <serviceDebug includeExceptionDetailInFaults="false"/>
 </behavior>
 </serviceBehaviors>
 </behaviors>
 <services>
 <service name="WcfService1.Service1"  behaviorConfiguration="MyBeh">
 <endpoint address="" binding="basicHttpBinding" contract="WcfService1.IService1"/>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
 <host>
 <baseAddresses>
 <add baseAddress="<a href="http://localhost:8181/Service1.svc/&quot;/">http://localhost:8181/Service1.svc/"/</a>>
 </baseAddresses>
 </host>
 </service>
 </services>
 <!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>-->
 </system.serviceModel>

Now our service is created. We will be hosting this service in IIS as we discussed in previous step. From IIS we will browse to test whether service is up and running or not.

For reference, full source code for service implementation is as below ,

Service1.svc.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;
using nwind;
namespace WcfService1
{

 public class Service1 : IService1
 {
 public  List<ProductDTO> GetProduct()
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {

ProductDTO product;
 List<ProductDTO> lstProducts = new List<ProductDTO>();
 var result = from r in context.Test1_Product select r;
 foreach (var r in result)
 {

product = new ProductDTO { ProductId = r.ProductId, ProductName = r.ProductName, ProductPrice = r.ProductPrice.ToString () };

lstProducts.Add(product);
 }

&nbsp;

return lstProducts;
 }

 }
 public bool InsertProduct(ProductDTO product)
 {
 try
 {
 using(ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 Test1_ProductItem itemToInsert = new Test1_ProductItem()
 {
 ProductId = product.ProductId ,
 ProductName = product.ProductName ,
 ProductPrice = Convert.ToDouble(product.ProductPrice)
 };
 products.InsertOnSubmit(itemToInsert);
 context.SubmitChanges();
 return true;
 }
 }
 catch (Exception ex)
 {
 return false;
 }

}
 public bool UpdateProduct(ProductDTO product)
 {
 try
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 var itemToUpdate = (from r in context.Test1_Product where r.ProductId == product.ProductId select r).First();
 itemToUpdate.ProductName = product.ProductName;
 itemToUpdate.ProductPrice = Convert.ToDouble(product.ProductPrice);
 context.SubmitChanges();
 return true;
 }
 }
 catch(Exception ex)
 {
 return false;
 }

 }

public bool DeleteProduct(ProductDTO product)
 {
 try
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 var itemToDelete = (from r in context.Test1_Product where r.ProductId == product.ProductId  select r).First();
 products.DeleteOnSubmit(itemToDelete);
 context.SubmitChanges();
 return true;
 }
 }
 catch (Exception ex)
 {
 return false;
 }
 }

 }
}

Creating a Managed Application (Console client to consume Service)

Now we will create a new project by selecting console application as project type. Right click on the project and add a service reference. Give the URL of the WCF Service hosted in IIS.

We need to call the service to perform the CRUD operation on SharePoint list from the console client.

Program.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using ConsoleApplication1.ServiceReference1;
using System.Collections.Generic;
namespace ConsoleApplication1
{
 class Program
 {
 static void Main(string[] args)
 {
 try
 {
 Service1Client proxy = new Service1Client();

// Insertion
 ProductDTO productToInsert = new ProductDTO { ProductId = "99", ProductName = "Ball", ProductPrice = "700" };
 if (proxy.InsertProduct(productToInsert))
 Console.WriteLine("Inserted successfully ");
 else
 Console.WriteLine("Opps some problem in Insertion ");

// Update

ProductDTO productToUpdate = new ProductDTO { ProductId = "99", ProductName = "Ball for New game ", ProductPrice = "7000" };
 if (proxy.InsertProduct(productToInsert))
 Console.WriteLine("Updated  successfully ");
 else
 Console.WriteLine("Opps some problem in Updation ");

//Delete
 ProductDTO productToDelete = new ProductDTO { ProductId = "99" };
 if (proxy.InsertProduct(productToInsert))
 Console.WriteLine("Deleted  successfully ");
 else
 Console.WriteLine("Opps some problem in Deletion ");

&nbsp;

//Reterive

Console.WriteLine("Records are as below ");
 List<ProductDTO>  p = proxy.GetProduct().ToList();
 foreach (var r in p)
 {
 Console.WriteLine(r.ProductName + r.ProductId + r.ProductPrice);
 }
 Console.ReadKey(true);
 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message);
 }

&nbsp;

Console.ReadKey(true);
 }

 }
}

Calling service is very simple. Just we need to create proxy of the service and call the methods on the service as normal function with required parameter.

Output

clip_image018

The Web Application could not be found .verify that you have typed the URL correctly error: SharePoint 2010 object model

The below exception is very frustrating when we start working with SharePoint object model. Let us investigate how to solve below exception

clip_image001

Above Exception can encounter in two scenarios

1. Trying to use SharePoint 2010 object model in managed application like console or windows application.

2. Trying to use SharePoint 2010 object model in WCF Service or Web services.

Scenario # 1: The above Exception in console or windows application

Right click on Console/Windows Application project and select properties.

clip_image002

Click on Application tab and choose the target framework to .Net Framework 3.5

clip_image004

After changing Target framework to .NET Framework 3.5, click on Build tab

clip_image006

Change the Platform target to Any CPU.

Now when you run the application, you should not get the above exception

Scenario # 2: Above Exception when using SharePoint 2010 object model in WCF

If you are getting above exception while using SharePoint object model in WCF or any Web service. You need to perform below operations

Host WCF service in IIS. See the below link for step by step explanation on how to host WCF 4.0 Service in IIS 7.5

http://dhananjaykumar.net/2010/09/07/walkthrough-on-creating-wcf-4-0-service-and-hosting-in-iis-7-5/

Only we need to make sure that,

Hosted WCF service is sharing the same application pool with SharePoint.

clip_image007

Select the Application pool to SharePoint-80

Try to apply both when you use SharePoint 2010object model. I hope this discussion will help you.

LINQ to SharePoint: CRUD operation on SharePoint 2010 list using SPLinq

Objective

In this article, we will see how to work with LINQ to SharePoint. I have tried to address all the common errors we encounter when first time we start using LINQ against SharePoint.

We will see ,

1. How to insert an item in SharePoint list using SPLinq

2. How to update an item in SharePoint list using SPLinq

3. How to delete an item in SharePoint list using SPLinq

4. How to fetch items from SharePoint list using SPLinq.

Advantage

1. SPLinq supports visual studio intellisense

2. SPLinq provides strong typecasting and data typing

3. SPLinq works without CAML query.

4. Using SPLinq , existing knowledge of LINQ could be apply to SharePoint development .

5. SPLinq provides completely language dependent development of SharePoint

6. Multiple list item insertion and deletion can be performed very easily with one syntax.

7. Join operation can be performed very easily on the related list

Using CAML when performing operation against SharePoint list was biggest challenge. CAML does not provide developer friendly syntaxes. SPLinq helps us to get rid of CAML.

SPLinq can be used with

1. Managed application , like windows or console or WPF

2. With SharePoint client object models.

3. With SharePoint webparts.

4. With SPGridView.

Challenge

The main challenge working with SPLInq is creation of entity class on command prompt. SPMetal creates a partial Entity class to apply Linq against that.

Assumption

We have a custom list

1. Name of the list is Test_Product.

2. Columns of the list is as below ,

clip_image002

3. There are two items in the list

clip_image004

4. URL of the SharePoint site is

http://dhananjay-pc/my/personal/Test1

Now we need to fetch the list items in a managed console application using Linq to Sharepoint or SPLinq.

Follow the below steps,

Step1

Open the command prompt and change directory to

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

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

clip_image006

Step2

Now we need to create the class for corresponding list definitions.

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

tal.exe /web:http://dhananjay-pc/my/personal/Test1 /namespace:nwind /code:Product.cs

In above command we are passing few parameters to spmetal.exe, they are as below

1. /web:Url

Here we need to provide URL of SharePoint site

/web:http://dhananjay-pc/my/personal/Test1 /

://dhananjay-pc/my/personal/Test1 / is URL of SharePoint site, I created for myself. You need to provide your SharePoint site URL here.

2. /namespace:nwind

This would be the namespace under which class of the list will get created. In my case name of the namespace would be nwind.

3. /code:Product.cs

This is the file name of the generated class. Since we are giving name Product for the file then class generated will be ProductDataContext

Step3

Open visual studio and create a new project of type console. Right click on the Project and select Properties

clip_image007

Click on the Build tab and change Platform Target to Any CPU.

clip_image009

Click on the Application tab and change the Target framework type to .Net Framework 3.5

clip_image011

Step4

The class we created in Step2 will by default get saved in the same folder with SPMetal.exe. So to see where the class got created we need to navigate to folder

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

Add created class to the Project

Now add this class to the project. To do this, right click on the project and select Add existing item. Then browse to above path and select Product.cs

Add references to the Project

Microsoft.SharePoint

Microsoft.SharePoint.Linq

Right click on Reference and select Add Reference. To locate Microsoft.SharePoint and Microsoft.SharePoint.Linq dll browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI. All the SharePoint dll are here in this location.

Step5

Add the namespace

clip_image012

Nwind is the name of the namespace of the class we created in Step2.

Now console application project is ready for the CRUD operation on SharePoint 2010 list using SPLinq

Fetch the items from list using SPLinq

a. First we need to create instance of ProductContext class

clip_image014

Here we need to provide URL of the SharePoint site as parameter to constructor.

b. Now we can apply simple LINQ to access the list, like below.

clip_image016

c. There is one more way to access the list

clip_image018

Code for fetching list items


ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>");
 var result = from r in context.Test1_Product select r;
 foreach (var r in result)
 {
 Console.WriteLine(r.ProductId + ":" + r.ProductName + ":" + r.ProductPrice);
 }
 Console.ReadKey(true);

Output

clip_image020

Insert to SharePoint list using SPLinq

1. Create the instance of Data Context

clip_image022

2. Get the entity list where item would get inserted

clip_image024

3. Create instance of List item to be inserted

clip_image026

4. Call the InsertOnsubmit on the instance of Entity list.

clip_image027

5. Call sumitchange on the context

clip_image028

Code for inserting a list item


ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>");
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 Test1_ProductItem itemToInsert = new Test1_ProductItem()
 {
 ProductId = "9",
 ProductName = "Soccer Ball",
 ProductPrice = 600
 };
 products.InsertOnSubmit(itemToInsert);
 context.SubmitChanges();

Update a Particular list item in SharePoint list

1. Create instance of Data Context

clip_image030

2. Fetch the list item to be updated using SPLInq

clip_image032

3. Modify the list item property wished to be updated. I am updating Product name to Dhananjay of Product Id 1

clip_image033

4. Call the submit change on the context

clip_image034

Code for updating a list item


ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>");
 var itemToUpdate = (from r in context.Test1_Product where r.ProductId == "1" select r).First();
 itemToUpdate.ProductName = "Dhananjay";
 context.SubmitChanges();

Delete a Particular item from the list

1. Create the instance of Data Context

clip_image022[1]

2. Get the entity list where item would get inserted

clip_image024[1]

3. Fetch the list item to be deleted using SPLInq

clip_image032[1]

4. Call deleteonsubmit to delete a particular item from SharePoint list

clip_image035

5. Call the submit change on the context

clip_image034[1]

Code for deleting a list item


ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>");
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 var itemToDelete = (from r in context.Test1_Product where r.ProductId == "1" select r).First();
 products.DeleteOnSubmit(itemToDelete);
 context.SubmitChanges();

LINQ to SharePoint: SPLinq in SharePoint2010

Objective

In this article, we will see how to work with LINQ to SharePoint. I have tried to address all the common errors we encounter when first time we start using LINQ against SharePoint.

Assumption

We have a custom list

1. Name of the list is Test_Product.

2. Columns of the list is as below ,

clip_image002

3. There are two items in the list

clip_image004

4. URL of the SharePoint site is

http://dhananjay-pc/my/personal/Test1

Now we need to fetch the list items in a managed console application using Linq to Sharepoint or SPLinq.

Follow the below steps,

Step1

Open the command prompt and change directory to

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

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

clip_image006

Step2

Now we need to create the class for corresponding list definitions.

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

tal.exe /web:http://dhananjay-pc/my/personal/Test1 /namespace:nwind /code:Product.cs

In above command we are passing few parameters to spmetal.exe, they are as below

1. /web:Url

Here we need to provide URL of SharePoint site

/web:http://dhananjay-pc/my/personal/Test1 /

://dhananjay-pc/my/personal/Test1 / is URL of SharePoint site, I created for myself. You need to provide your SharePoint site URL here.

2. /namespace:nwind

This would be the namespace under which class of the list will get created. In my case name of the namespace would be nwind.

3. /code:Product.cs

This is the file name of the generated class. Since we are giving name Product for the file then class generated will be ProductDataContext

Step3

Open visual studio and create a new project of type console. Right click on the Project and select Properties

clip_image007

Click on the Build tab and change Platform Target to Any CPU.

clip_image009

Click on the Application tab and change the Target framework type to .Net Framework 3.5

clip_image011

Step4

The class we created in Step2 will by default get saved in the same folder with SPMetal.exe. So to see where the class got created we need to navigate to folder

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

Add created class to the Project

Now add this class to the project. To do this, right click on the project and select Add existing item. Then browse to above path and select Product.cs

Add references to the Project

Microsoft.SharePoint

Microsoft.SharePoint.Linq

Right click on Reference and select Add Reference. To locate Microsoft.SharePoint and Microsoft.SharePoint.Linq dll browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI. All the SharePoint dll are here in this location.

Step5

Add the namespace

clip_image012

Nwind is the name of the namespace of the class we created in Step2.

Step6

Now we will write the code to access the SharePoint list using Linq to SharePoint.

a. First we need to create instance of ProductContext class

clip_image014

Here we need to provide URL of the SharePoint site as parameter to constructor.

b. Now we can apply simple LINQ to access the list, like below.

clip_image016

c. There is one more way to access the list

clip_image018

Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;
using nwind;

namespace SPLinqTest1
{
    class Program
    {
        static void Main(string[] args)
        {
            
            ProductDataContext context = new ProductDataContext("http://dhananjay-pc/my/personal/Test1");
            //EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
            var res = from r in context.Test1_Product   select r;
            foreach (var r in res)
            {
                Console.WriteLine(r.ProductId + ":" + r.ProductName + ":" + r.ProductPrice);
            }
            Console.ReadKey(true);
        }
    }
}

Output

clip_image020

Seven quick points in Understanding SharePoint 2007 list definition

 Objective
This article will give basic 7 theatrical points on SharePoint List definition.

  1. When we create a new site in SharePoint, it gets created as instance of SharePoint Site Definition. Each instance of Site Definition is having List Definitions. So when we create a list in SharePoint site, it gets created as instance of List Definition of the site. 
  2. Each list gets its definition from the two files. These files are applied globally to the site.

    Two files are as below,

  3. Each List folder is having 5 files. They are as follows

    These files can be found at 

    Local_Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\60\TEMPLATE\Locale_ID\Site_Definition\LISTS
    directory

  4. All the three XML files for a list use CAML language to define how list instance should be created.
  5. Never modify content of FLDTYPES.XML.
    Because wrong updating or modification in this file can break the entire site definition for particular front end server.
  6. All ASPX page of a list item contains same Page Directive, Meta Data, Script, and Server controls.
  7. Each ASPX page contains a table with three rows.

TOP Navigation

Title

Left Navigation

Content

 

In next articles; I will show how to customize above four parts of a SharePoint List form. Thanks for reading.

Forms on SharePoint lists

Objective

This article will give a very high level description on various forms on a SharePoint list.  

When we create a new custom list in SharePoint, SharePoint creates three forms (*.aspx) for the custom list. In fact for all list these forms are provided by SharePoint.

 

 

Let us say, there is a list called TestList in your SharePoint site. Columns of list are as follows;

 

Adding New Item

Now when you add new item in the list, NewForm.aspx will get open. You can see the below URL in your browser while adding new item in the list.

http://ABCSERVER:9722/sites/Test4/Lists/TestList/NewForm.aspx?RootFolder=%2Fsites%2FTest1%2FTest4%2FLists%2FTestList&Source=http%3A%2F%2Fc849uss%3A9722%2Fsites%2FTest1%2FTest4%2FLists%2FTestList%2FAllItems%2Easpx

There are two query parameters,

  1. RootFolder: This parameter defines, in which folder Item will get saved.
  2. Source: This parameter defines after completion of action where to navigate.

Note: More on these two parameters in next articles.

 

Editing Existing Item

Now when you edit existing item in the list, EditForm.aspx will get open. You can see the below URL in your browser while editing existing item in the list.

http://ABCSERVER:9722/sites/Test1/Lists/TestList/EditForm.aspx?ID=3&Source=http%3A%2F%2Fc849uss%3A9722%2Fsites%2FTest1%2FTest4%2FLists%2FTestList%2FAllItems%2Easpx

There are two query parameters,

  1. ID: This parameter takes id of the item in list to be edited. If you pass ID which does not exist in the list, SharePoint will throw you below error.
No item exists at http://c849uss:9722/sites/Test1/Test4/Lists/TestList/EditForm.aspx?ID=300&Source=http://c849uss:9722/sites/Test1/Test4/Lists/TestList/AllItems.aspx.  It may have been deleted or renamed by another user.Web Parts Maintenance Page: If you have permission, you can use this page to temporarily close Web Parts or remove personal settings. For more information, contact your site administrator.

Troubleshoot issues with Windows SharePoint Services.

  1. Source: This parameter defines after completion of action where to navigate.

     

Displaying Existing Item

Now when you display existing item in the list, DispForm.aspx will get open. You can see the below URL in your browser while editing existing item in the list.

http://ABCSERVER:9722/sites/Test1/Lists/TestList/DispForm.aspx?ID=3&Source=http%3A%2F%2Fc849uss%3A9722%2Fsites%2FTest1%2FTest4%2FLists%2FTestList%2FAllItems%2Easpx&RootFolder=%2Fsites%2FTest1%2FTest4%2FLists%2FTestList

There are two query parameters,

  1. ID: This parameter takes id of the item in list to be displayed.
  2. Source: This parameter defines after completion of action where to navigate.

Creating message body by parsing document from Document Library and sending mail in SharePoint 2007

Objective

This article will give an idea of,

  1. How to parse a document from Document Library and replace with dynamic values at run time.
  2. How to send mail in SharePoint using SPUtility class.
  3. Introduction of a real time problem to use above said features of SharePoint.

Background
There was a requirement in one of my project. I will divide requirement as follows

  1. There are documents in Document Library.
  2. Content of documents will be sending as body of Email.
  3. Document will be containing static data as well as dynamic data.
  4. Value for dynamic data will be replaced at the run time.

So, requirement could be summarized as; we need to fetch a document from document library and parse that. While parsing, we will replace dynamic variables with real value and then we will be sending the mail. Content of the document will be parsed as string and will be sent as body of the mail.

Let us say, we are having a document named Notification.txt in SharePoint Document library. Content of document is as follows

Notification.txt

Hi [Name], 

This is Notification Mail From SharePoint server. You are supposing to Report to [ManagerName] on [Date] for the [ProjectName].  

[UriToNavigate] to Navigate.  

Thanks with Regards.  

***Do not reply to this mail***

 Note: Dynamic variables are enclosed in square braces.

  1. We need to read this document from SharePoint Document library using object model.
  2. Replace dynamic variables enclosed with square braces with values at run time.
  3. Parse content of document and return a string. This string will be used as body of the mail.

Finally after creating body from document of document library, we will send mail using SPUtility.

Creating Body from Document of SharePoint Document Library

Step 1: Create Hash Table

Hash table will contain values for all the dynamic variables.

public
Hashtable CreateHashTableForMessageBody(string name, string managerName,string date, string projectName, string linkToNavigate)

{

Hashtable hashTableForMessageBody = new
Hashtable();

link = String.Format(“<a href = {0} >click here.</a>”, linkToNavigate);

hashTableForMessageBody.Add(“Name”, name);

hashTableForMessageBody.Add(“ManagerName”, managerName);

hashTableForMessageBody.Add(“Date”, date);

hashTableForMessageBody.Add(“ProjectName”, projectName);

hashTableForMessageBody.Add(“UriToNavigate”,link);

return hashTableForMessageBody;

}

  1. We are passing all the required values for dynamic variables as input parameter to function.
  2. We are creating a Hash table.
  3. Function is returning a hash table.
  4. Make sure name of the key is exactly the same as of name of the dynamic variables. Dynamic variables are enclosed in square braces. Cases of the Dynamic variables and key of hash table must be same. For example key “Name” in Hash table will be parsed and replaced for [Name] dynamic variable in document.

Step 2: Parsing content of document to return a string as message body.

Public static
string GetEmailBody(String spSite, Hashtable emailAttribute, string templateName)
{

string templateStr = “”;
string bottomMessage = “”;

try
{
using (SPSite site = new SPSite(spSite)){
using (SPWeb uspWeb = site.OpenWeb())
{
this.emailAttributes = emailAttributes;
SPList emailTemplates = uspWeb.Lists[“NotificationTemplate”];
SPQuery qry = new SPQuery();
qry.Query = string.Format(“<Where><Eq><FieldRef Name=’FileLeafRef’ /><Value Type=’File’>{0}</Value></Eq></Where>”, templateName);
SPListItemCollection templateCollection = emailTemplates.GetItems(qry);
if (templateCollection.Count > 0){
SPListItem template = templateCollection[0];
byte[] templateByte = template.File.OpenBinary();
System.Text.Encoding enc = System.Text.Encoding.ASCII;
templateStr = enc.GetString(templateByte);
foreach (object obj in emailAttribute.Keys)
{
if (emailAttribute[obj] != null)
{
templateStr = templateStr.Replace(“[“ + obj.ToString() + “]”, emailAttribute[obj].ToString());
}}
bottomMessage = “*** This is system-generated email. Do not reply. *** “;
templateStr = templateStr +“\n” + bottomMessage;
}
return templateStr;}

  1. Function takes three input parameters. First parameter is URL as string to create instance of SPSIte. Second parameter is Hash table. Third parameter is name of the template to be parsed.
  2. NotificationTemplate is name of the Document Library in SharePoint site.
  3. We are iterating through the Document library using CAML query and searching for the template name (.txt file uploaded)
  4. We are iterating through all the keys in hash table and replacing the keys with values while getting matched with dynamic variable in document of document library.
  5. We are returning string message as body of the mail.

Sending mail using SPUtility

So far, we have created the body of the mail; we are going to send. In this section we will see how we can send Email using SPUtility class on Windows.SharePoint.Services.dll

  1. Creating hashtable to create message body.
  2. Passing hashtable in function creating messagebody.
  3. Creating a dictionary to set To, From, Subject and Body of the mail.
  4. SendMail static function of SPUtility class is used to send mail.

Function to send Email using SPUtility

 

String name = “Dhananjay Kumar”

Striing subject = String.Empty;


String managername =“Anoj P”


String linktonavigate = “Default.apsx”;


String date = String.Empty;


String projectname = “My Project”;

String messageBody = String.Empty;


Hashtable hashTableForMessageBody = null;

hashTableForMessageBody = CreateHashTableForMessageBody(name, managername, date, projectname,linktonavigate);

messageBody = GetEmailBody(spsite, hashTableForMessageBody,
Notification.txt);

#region sending Mail

subject = “This is Test Mail”
try

{StringDictionary headers = new StringDictionary();

headers.Add(“subject”, subject);
headers.Add(“from”, GetFromAddress(spsite));

headers.Add(“to”,”abc@abc.com”);


SPUtility.SendEmail(web, headers, messageBody);

}


catch (Exception ex)

{

web.Dispose();

site.Dispose();


ErrorLogger.LogError(“Creating message Body – sending mail”, ex);

}

#endregion

Cascading drop down column in a SharePoint 2007 List

Objective

This article will show how to use codeplex project to achieve Cascading drop down columns in SharePoint list. This article will show how to achieve parent child relationship in column of SharePoint list.

Step 1Download the project from codeplex. Choose WSP file to download. To download the project

Click here

Step 2

After downloading the WSP add the solution using STSADM command. Navigate to BIN folder and add the solution.

Command

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\BIN> stsa

dm -o addsolution -filename c:\Stoneshare.CascadingDropDown.WithFilter.wsp

Step 3

Open Central ADMIN and deploy solution. Navigate to Operation -> Global Configuration -> Solution Management. Select the Global Deployment option.

Step 4

After globally deployed the solution; check the GAC; type Assembly at Run; there would be a DLL added.

Step 5

Let us say; three lists as follows.

Continent List

  1. This list is having only one column called Title.
  2. Title column is single line of text.

 

Countries List

  1. This List contains three columns.
  2. Title column is single line of text.
  3. Country column is single line of text.
  4. Continent column is Look up column from Continent list. See the diagram below.

 

Cities List

     This List contains three columns.

  1. Title column is single line of text.
  2. City column is single line of text.
  3. Country column is Look up column from Countries list. See the diagram below.

 

Step 6

Creating MyLocation list. This list will have cascading dropdown column.

  1. There are four columns in this list.
  2. Title is Single line of text column.

    MyContinent column


Point to be noted

  1. Name of column is MyContinent
  2. Type is Cascading drop down list. This type will come after adding downloaded WSP as solution for the server.
  3. This is a required column.
  4. Give name of the Cascading drop down list detail as MyContinent
  5. There is no parent for this column.
  6. Give Child Name as MyCountry. This column will get created as next column for this list. MyContinent will act as parent for MyCountry column.
  7. In Site URL give URL of the site where Continent, Country and City list is part of. And then click on Load Lists.
  8. As a list name select Continent
  9. As column of the value select Title.
  10. As column for the text select Title.
  11. Column to join to parent can be null. Because there is Parent for the column.
  12. Select column to filter as title.
  13. As an operator choose Show All. We want to display all continent names.

MyCountry column

 Points to be noted

  1. Parent name is MyContinent. This column got created previously.
  2. Child name is MyCity. This column will get created next.
  3. Column to join parent is Continent because this column is holding value for Continent in Countries list.
  4. Column to filter is Continent
  5. Select operator as Show All.
  6. Value to filter is MyContinent .MyContinent is name of the parent column.

     MyCity column


Points to be noted

  1. Parent name is MyCountry. This column got created previously.
  2. Column to join parent is Country because this column is holding value for Country in City list.
  3. Column to filter is Country
  4. Select operator as Show All.
  5. Value to filter is MyCountry. MyCountry is name of the parent column.

After creating above four columns structure of MyLocation list will look like.

 

Step 7

Creating new Item in MyLOcation list.

MyContinent drop down has the entire continent from the list.

 

After selecting ASIA for MyContinent . MyCountry drop down is loaded with India

 

While selecting India in MyCountry drop down MyCity will be loaded with Delhi.

Giving Title as South extension. The new Item would be like below.

HyperLinkField in SPGridView using Moss 2007 Object model

Objective

This article is going to explain

  1. How to work with SPGridView
  2. How to add HypeLinkField on a SPGridView.
  3. How to Put SPGridView on a web part.
  4. How to deploy the web part on a sharepoint site.

Assumption

I have a SharePoint list called TestingHyperLink. Columns of SharePoint list are as below.

  1. Name column is of type Single Line of Text.
  2. Favorite WebSite column is of type HyperLink or Picture
  3. Favorite Site column is of type HyperLink or Picture

     


 


When opening task T1


I have created a SharePoint view for the List. View contains only columns Name,Favorite WebSite and Favorite List. I have given the name of the view as MyView.

Displaying in SPGridView in Web Part

Note : I am using Visual Studio Extension 2008 for WSS 3.0 . If you don’t have installed on your visual studio download and install that.

  1. Create a New Web Part by selecting File –> New -> SharePoint -> Web Part
  2. Add Reference of System.Data
  3. Write coding to fetch data

Code

using System;

using System.Runtime.InteropServices;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Serialization;

using System.Data;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.WebPartPages;

namespace WebPart1

{

[Guid(“b60d63e9-0784-4904-9aa3-9a3d25932441”)]


public
class
WebPart1 : System.Web.UI.WebControls.WebParts.WebPart

{


SPSite mySite;


SPWeb myWeb;


SPList myList;


SPGridView myView;


public WebPart1()

{

}


protected
override
void CreateChildControls()

{


base.CreateChildControls();


SPSite mySite = new
SPSite(http://adfsaccount:2222/&#8221;);


SPWeb myWeb = mySite.OpenWeb();

myList = myWeb.Lists[“TestingHyperLink”];

myView = new
SPGridView();


SPGridView sp = BindToGrid(myList, myView );


Panel panel1= new
Panel() ;

panel1.Controls.Add(sp);

}


private
SPGridView BindToGrid(SPList myList,SPGridView myView)

{


//myView = new SPGridView();


SPView sharepointview = myList.Views[“MyView”];


SPListItemCollection listCollection = myList.GetItems(sharepointview);


DataTable dt = new
DataTable();

dt.Columns.Add(“Name”, typeof(string));

dt.Columns.Add(“FavWebSite”);

dt.Columns.Add(“FavList”);


DataRow dtRow;


foreach (SPListItem listitem in listCollection)

{

dtRow = dt.Rows.Add();

dtRow[“Name”] = listitem[“Name”];


string favwebsite = (string)listitem[“Favorite WebSite”];


string favwebsiteUri = GetUri(favwebsite);

dtRow[“FavWebSite”] = favwebsiteUri;


string favlist = (string)listitem[“Favorite List”];


string favlistUri = GetUri(favlist);

dtRow[“FavList”] = favlistUri;

}


SPBoundField boundfield = new
SPBoundField();

boundfield.HeaderText = “Name”;

boundfield.DataField = “Name”;

myView.Columns.Add(boundfield);


HyperLinkField hyperFieldfavsite = new
HyperLinkField();


string[] favsitearray = new
string[1];

favsitearray[0] = “FavWebSite”;

hyperFieldfavsite.DataTextField = “FavWebSite”;

hyperFieldfavsite.DataNavigateUrlFields = favsitearray;

hyperFieldfavsite.DataNavigateUrlFormatString = “{0}”;

myView.Columns.Add(hyperFieldfavsite);


HyperLinkField hyperFieldfavlist = new
HyperLinkField();


string[] favlistarray = new
string[1];

favsitearray[0] = “FavList”;

hyperFieldfavsite.DataTextField = “FavList”;

hyperFieldfavsite.DataNavigateUrlFields = favlistarray;

hyperFieldfavsite.DataNavigateUrlFormatString = “{0}”;

myView.Columns.Add(hyperFieldfavlist);

myView.AutoGenerateColumns = false;

myView.DataSource = dt.DefaultView;

myView.DataBind();


// Panel1.Controls.Add(myView);


return myView;

}


private
string GetUri(string str)

{


string[] stemp = str.Split(“,”.ToCharArray());


string s1 = stemp[0];


string s2 = stemp[1];


HyperLink h = new
HyperLink();

h.NavigateUrl = s1;


return h.NavigateUrl;

}

}

}

Explanation

  1. TestingHyperLink is name of the list.
  2. MyView is name of the view.
  3. BindToGrid method is just creating Data table. Adding the column to data table and populating the row.
  4. HypeLinkField is used to populate the column as link.
  5. GetUri method is constructing URI from the string.
  6. Complie the solution.
  7. To deploy put the link of the site collection. Where you want to deploy the web part. Right click on Solution then properties then click on Debug tab. In Start Browser field put URL of site collection.

     


  8. Recompile the code.
  9. Right click and Package the solution


  10. Deploy the solution. Again right click on solution and click Deploy.


  1. Do an IISRESET. Go to command prompt and type this IISRESET. This is to restart the IIS.
  2. Open the SharePoint site.
  3. Go to Site Action then Site Setting
  4. Go to Site Collection Feature under Site Collection Administration tab. You should able to see the web part with SPGridView you deployed now.


  5. Add web part from Edit mode to view the Grid View.

Conclusion

I have shown in this article, how to add HyperLink field in SPGridView and then deply SPGridView on a webpart. Thanks for reading.