Multiple base addresses for WCF Service

If we do not want to explicitly set address for each EndPoint in our service then we define BASE ADDRESS for the EndPoint exposed for our service

clip_image002

And we use it in service configuration as below,

clip_image004

The advantage of having base address is that, if we are changing the service URL, we need to change at only one place instead of going and changing address of each endpoint.

WCF allow us to give multiple base addresses for each type of protocol. And at the run time corresponding endpoint will take the base address.

clip_image006

In above configuration, we added one more base address using net.tcp protocol.

Now at endpoint configuration, we will configure it as below

clip_image008

At the run time WCF automatically will map base address to corresponding endpoint with matched protocol.

For reference full Web.Config will look like


<system.serviceModel>
 <behaviors>
 <serviceBehaviors>
 <behavior name="MyBeh">
 <serviceMetadata httpGetEnabled="true"/>
 <serviceDebug includeExceptionDetailInFaults="false"/>
 </behavior>
 </serviceBehaviors>
 </behaviors>
 <services>
 <service name="WcfService1.Service1"  behaviorConfiguration="MyBeh">
 <endpoint address=""
 binding="basicHttpBinding"
 contract="WcfService1.IService1"/>
 <endpoint address="nete"
 binding ="netTcpBinding"
 contract ="WcfService1.IService1"/>
 <endpoint address="mex"
 binding="mexHttpBinding"
 contract="IMetadataExchange"/>
 <endpoint address="mex1"
 binding="mexTcpBinding"
 contract="IMetadataExchange"/>
 <host>
 <baseAddresses>
 <add baseAddress="<a href="http://localhost:8181/Service1.svc/&quot;/">http://localhost:8181/Service1.svc/"/</a>>
 <add baseAddress="net.tcp://localhost:9876/Service1.svc/"/>
 </baseAddresses>
 </host>
 </service>
 </services>
 </system.serviceModel>

 

Enabling JavaScript IntelliSense on Visual Web Part in SharePoint 2010

Open Visual Studio 2010 and create a Visual Web Part project as selecting from SharePoint 2010 tab

clip_image002

Now provide name of the site where you want to deploy the web part

clip_image003

Click on Validate button to validate the site. If you are able to connect and get below message then we are we are good to go.

clip_image004

Open VisualWebPart1UserControl.ascx and add below script

clip_image006

After adding above script add

clip_image007

Now add below script,

clip_image009

Inside script tag , write a function

clip_image011

And now u can see that in this function IntelliSense is working

clip_image001

So in JavaScript function it would be working like below

clip_image013

Walkthrough creating REST Service in WCF 4.0

Objective

This article will explain step to step explanation of, how to create a REST based service and how to consume that in a managed client.

Step 1`

Create a new project as WCF Service application type.

clip_image002

Step 2

Delete all the default code from IService.cs and Service.svc.cs

Now open Web.Config file and delete <system.serviceModel>

If you are using VS2010 then delete below code from Web.Config

clip_image004

Step 3

Right click on Service.svc and open View markup.

clip_image005

In Markup of RestService.cs , add below code there

Factory=”System.ServiceModel.Activation.WebServiceHostFactory”

So after adding code the markup would look like

Markup of RestService.cs

clip_image007

Step 4

Add following references to the WCF Service Application project, if you are using VS2010

Microsoft.Http.dll

Microsoft.Http.Extension.dll

System.ServiceModel.Web.dll

Step 5

Add a new project as of type class library and give it name UtilityClasses.

clip_image009

Add a class Number to this class library.

Number.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UtilityClasses
{
 [Serializable]
 public class NumberService
 {
 public int Number1 { get; set; }
 public int Number2 { get; set; }
 }
}

 

Step 6

Define the Service Contract as below,

IService1.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using UtilityClasses;

namespace WcfService3
{

 [ServiceContract]
 public interface IService1
 {
 [OperationContract(Name="AddParameter")]
 [WebInvoke(UriTemplate = "/Add/MyAdd",Method="POST")]
 int  Add(NumberService n1);
 [OperationContract(Name = "Add")]
 [WebGet(UriTemplate = "/")]
 int Add();

}

}

 

This code is used to construct URI for REST service.

clip_image010

Method parameter says what type of HTTP request; this URI is going to entertain. In this case it is Http POST.

UriTemplate parameter says, what would be URI for this particular method. In this case it is one back slash means; it is root URI of this service.

So, to invoke this method add (), the URI address would be

http://localhost:3602/RestService.svc/

Where 3602 is port number of web server, where this service is running.

Let, if the above code is modified as

clip_image012

Then it would be invoked as

http://localhost:3602/RestService.svc/ADD/MyAdd

Step 7

Now we need to implement the service

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 UtilityClasses;

namespace WcfService3
{

 public class Service1 : IService1
 {
 public int res = 100;

public int Add(NumberService n1)
 {

res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
 return res;
 }
 public int Add()
 {
 return res;
 }
 }
}

&nbsp;

 

Step 8

Test the Service in Browser

1. Build the Service

2. Right click on Service1.svc and select view in browser.

clip_image014

Output 100 is returned in the browser by the service. It is because, below service method. URI of below GET method is mapped to root of the URI. And this method is returning 100.

clip_image015

Step 9

Consume the service

Add new console project in solution and give it name as ConsoleTestProject.

clip_image017

Add reference of project UtilityClasses Add following references to the console project.

Microsoft.Http.dll

Microsoft.Http.Extension.dll

System.ServiceModel.Web.dll

Step 10

Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Microsoft.Http;
using Microsoft.ServiceModel.Web;
using Microsoft.ServiceModel.Web.SpecializedServices;
using System.Runtime.Serialization;
using UtilityClasses;

namespace ConsoleTestProject
{
 class Program
 {
 static void Main(string[] args)
 {

uri = "<a href="http://localhost:3602/RestService.svc/">http://localhost:3602/RestService.svc/</a>";
 // Calling without parameter
 Console.WriteLine(AddWithoutParameter());
 Console.Read();
 //Calling with parameter
 NumberService obj = new NumberService() { Number1 = 7, Number2 = 2 };
 Console.WriteLine(AddWithParameter(obj));
 Console.Read();

}
 public static string  AddWithoutParameter()
 {
 using (HttpResponseMessage response = new HttpClient().Get(uri))
 {

 int res = response.Content.ReadAsDataContract<int>();
 return res.ToString();
 }
 }
 public static string  AddWithParameter(NumberService obj)
 {
 using (HttpResponseMessage  response = new HttpClient().Post(uri,HttpContentExtensions.CreateDataContract(obj)))
 {

 int res = response.Content.ReadAsDataContract<int>();
 return res.ToString();

}

}

}
 }
}

&nbsp;

 

There are two static methods

AddWithoutParameter() -> To Invoke HTTP Get on Service URI. {In Green}

AddWithParameter() -> To Invoke HTTP POST on Service URI. {In Yellow}

Output

clip_image019

Navigation between pages in Windows 7 Phone

To see how could we do navigation between pages in Windows 7 Phone application , I am going to create a new page . I am giving name of the page as NewPage.Xaml

Now we will navigate as

clip_image001

Let us put a button on MainPage.xaml and on click of that button we will navigate tp NewPage.Xaml

clip_image003

On click event,


void btnToNavigate_Click(object sender, RoutedEventArgs e)
 {

 NavigationService.Navigate(new Uri("/NewPage.xaml", UriKind.Relative));

 }

 

There is one more way to navigate to other page

 


void btnToNavigate_Click(object sender, RoutedEventArgs e)
 {

 PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
 frame.Navigate(new Uri("/NewPage.xaml", UriKind.Relative));
 }

 

 

Now if we want to pass value from one page to another page then,


void btnToNavigate_Click(object sender, RoutedEventArgs e)
 {
 string param1="Value1";
 string param2="Value2";
 NavigationService.Navigate(new Uri(string.Format("/NewPage.xaml?val1={0}&val2={1}",param1 ,param2), UriKind.Relative));

 }

 

In above code, we are passing param1 and param2 to next page.

Now to fetch these values from query parameter on NewPage.Xaml.cs , we need to override the onNavigated() method.

And code would be like

 protected  override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs  e)
 {
 base.OnNavigatedTo(e);
 string value1 = "";
 string value2 = "";
 NavigationContext.QueryString.TryGetValue("val1", out value1);
 NavigationContext.QueryString.TryGetValue("val2", out value2);
 MessageBox.Show(value1);
 MessageBox.Show(value2);
 }

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.