Calling a WCF Service using jQuery in SharePoint (Anweshi Deverasetty)
2011-07-25 15:33
766 查看
转[http://blogs.msdn.com/b/sharepointdev/archive/2011/02/22/calling-a-wcf-service-using-jquery-in-sharepoint.aspx]
This blog post explains how a WCF service can be called using jQuery in a SharePoint application. I won’t cover all of the implementation details. This post will highlight the relevant parts of configuring a WCF service to be accessible using jQuery in SharePoint.
[Update – 2/23/2011 – The original post contained some poor deployment practices and erroneous code. We apologize for the errors and want to give a big thank you to Wictor Wilen for pointing them out. The best practices for deployment and development using Visual Studio 2010 are available on his blog post . We are working to create a technical article that will show the best practices and Visual Studio 2010 tools.]
Creating a WCF Service
Let us start with the creation of Data Access Layer. This consists of the ProductsManager class and the associated methods.
Create a class library with the name DatabaseManager.
Add a class called ProductsManager.
Add function to ProductsManager called GetProducts. This will get the list of all Products from the database as given below. The code will look like the following:
Add a strong name to this assembly.
Now, we will create the WCF Service. This will serve the data to our page. Since this will be deployed to SharePoint, make sure the target framework is .NET Framework 3.5.
Click on File, Add, New Project.
In the Add New Project dialog, choose the WCF templates and choose the WCF Service Application template. Type the name SampleWCFService. Make sure you choose .NET Framework 3.5 in this dialog.
When the project is created, add a reference to the previously created DatabaseManager class library.
Rename the IService1.cs file to IProductsService.
Rename the Service1.svc file to ProductsService.
Add a strong name to this assembly.
Now, we will configure the Web.config entries as well as the attributes for the services.
Add a reference to Microsoft.SharePoint.Client.ServerRuntime.dll. If you don’t see this in the Add a Reference dialog, you will have to manually add it from the Windows\Assembly\GAC_MSIL\ directory. More information can be found on Microsoft Support.
Open ProductsService.cs using the View Markup option. Insert the following declaration. (Important: This has been broken into two lines for readability. Make sure this declaration is on one line in your file.)
Add the following two using statements to the ProductService.cs file.
Add the following attributes to the class declaration in the ProductService.cs file.
Add the following method to ProductService.cs.
Add a new contract for GetProducts in the IProductsService.csfile.
Deploying WCF Service in SharePoint environment
[Update – 2/23/2011 - Our original post contained manual instructions for copying files to the front-end, and this is not a best practice. Deployment should be handled using the tools provided in Visual Studio 2010 or through the use of a redistributable solution package. Wictor Wilen covers this topic on his blog post. Please refer to his post for help with deploying the files using Visual Studio 2010.]
Testing WCF Service
In order to check whether the Service is up, navigate to http://siteurl/_layouts/ProductService.svc from your browser. You will see a message “No End Point” on the screen. Now, let’s try to access the method GetProducts by navigating to http://siteurl/_layouts/ProductService.svc/GetProducts from the browser again. It pops up the resultant file.
Accessing WCF Service using jQuery from a SharePoint site
Now, it’s time to access this WCF service using jQuery. Create a JS file with name CallWCFService.Js and use the following snippets to call the service.
Create a function object called Product to hold each product details.
Call the WCF service using an AJAX call.
Implement the successful call handler to populate the result set into a products array object.
Now, include this JS file into your SharePoint page by adding the following declaration to the page. Make sure you have included references to the jQuery files as well.
This blog post explains how a WCF service can be called using jQuery in a SharePoint application. I won’t cover all of the implementation details. This post will highlight the relevant parts of configuring a WCF service to be accessible using jQuery in SharePoint.
[Update – 2/23/2011 – The original post contained some poor deployment practices and erroneous code. We apologize for the errors and want to give a big thank you to Wictor Wilen for pointing them out. The best practices for deployment and development using Visual Studio 2010 are available on his blog post . We are working to create a technical article that will show the best practices and Visual Studio 2010 tools.]
Creating a WCF Service
Let us start with the creation of Data Access Layer. This consists of the ProductsManager class and the associated methods.
Create a class library with the name DatabaseManager.
Add a class called ProductsManager.
Add function to ProductsManager called GetProducts. This will get the list of all Products from the database as given below. The code will look like the following:
public List<Products> GetProducts() { List<Products> productsList = new List<Products>(); Database DatabaseInstance = DatabaseFactory.CreateDatabase(ConnectionStringkey); DbCommand DatabaseCommand; using (DatabaseCommand = DatabaseInstance.GetStoredProcCommand(SP_GetProducts)) { using (IDataReader reader = DatabaseInstance.ExecuteReader(DatabaseCommand)) { while (reader.Read()) { Products products = new Products(); products.ProductName = reader["ProductName"].ToString(); products.ProductDesc = reader["ProductDesc"].ToString(); products.Price = reader["Price"].ToString(); products.Quantity = reader["Quantity"].ToString(); productsList.Add(products); } } return productsList; } }
Add a strong name to this assembly.
Now, we will create the WCF Service. This will serve the data to our page. Since this will be deployed to SharePoint, make sure the target framework is .NET Framework 3.5.
Click on File, Add, New Project.
In the Add New Project dialog, choose the WCF templates and choose the WCF Service Application template. Type the name SampleWCFService. Make sure you choose .NET Framework 3.5 in this dialog.
When the project is created, add a reference to the previously created DatabaseManager class library.
Rename the IService1.cs file to IProductsService.
Rename the Service1.svc file to ProductsService.
Add a strong name to this assembly.
Now, we will configure the Web.config entries as well as the attributes for the services.
Add a reference to Microsoft.SharePoint.Client.ServerRuntime.dll. If you don’t see this in the Add a Reference dialog, you will have to manually add it from the Windows\Assembly\GAC_MSIL\ directory. More information can be found on Microsoft Support.
Open ProductsService.cs using the View Markup option. Insert the following declaration. (Important: This has been broken into two lines for readability. Make sure this declaration is on one line in your file.)
<%@ ServiceHost Language="C#" Debug="true" Service="SampleWCFService.ProductService" CodeBehind="ProductService.svc.cs" Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
Add the following two using statements to the ProductService.cs file.
using Microsoft.SharePoint.Client.Services; using System.ServiceModel.Activation;
Add the following attributes to the class declaration in the ProductService.cs file.
[BasicHttpBindingServiceMetadataExchangeEndpoint] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
Add the following method to ProductService.cs.
/// <summary> /// Gets the list of Products /// </summary> /// <returns>Returns the List of Products</returns> public List<Products> GetProducts() { ProductsManager productsManager = new ProductsManager(); return productsManager.GetProducts(); }
Add a new contract for GetProducts in the IProductsService.csfile.
[OperationContract] [WebGet(UriTemplate = "/GetProducts", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] List<Products> GetProducts();
Deploying WCF Service in SharePoint environment
[Update – 2/23/2011 - Our original post contained manual instructions for copying files to the front-end, and this is not a best practice. Deployment should be handled using the tools provided in Visual Studio 2010 or through the use of a redistributable solution package. Wictor Wilen covers this topic on his blog post. Please refer to his post for help with deploying the files using Visual Studio 2010.]
Testing WCF Service
In order to check whether the Service is up, navigate to http://siteurl/_layouts/ProductService.svc from your browser. You will see a message “No End Point” on the screen. Now, let’s try to access the method GetProducts by navigating to http://siteurl/_layouts/ProductService.svc/GetProducts from the browser again. It pops up the resultant file.
Accessing WCF Service using jQuery from a SharePoint site
Now, it’s time to access this WCF service using jQuery. Create a JS file with name CallWCFService.Js and use the following snippets to call the service.
Create a function object called Product to hold each product details.
function Product(ProductName, ProductDesc, Price, Quantity) { this.ProductName = ProductName; this.ProductDesc = ProductDesc; this.Price = Price; this.Quantity = Quantity; }
Call the WCF service using an AJAX call.
function CallWCFService(WCFServiceURL) { $.ajax({ type: "GET", url: WCFServiceURL, contentType: "application/json; charset=utf-8", dataType: 'json', processdata: true, success: function (msg) { WCFServiceSucceeded(msg); }, error: WCFServiceFailed }); }
Implement the successful call handler to populate the result set into a products array object.
//On Successful WCF Service call function WCFServiceSucceeded(result) { var productsArray = new Array(); //Gets the Products $.each(result, function (i, Product) { productsArray[i]=Product; }); //Print all the product details $.each(productsArray,function(i,Product) { alert(Product.ProductName + ' ' + Product.ProductDesc + ' ' + Product.Price + ' ' + Product.Quantity) }); }
Now, include this JS file into your SharePoint page by adding the following declaration to the page. Make sure you have included references to the jQuery files as well.
<script src="/Style Library/callwcfservice.js" type="text/javascript"></script>
相关文章推荐
- Calling a WCF Service using jQuery in SharePoint - the correct way
- Quickstart: Embed a Power BI Report Server report using an iFrame in SharePoint Server
- 【转】Calling Cross Domain WCF Service using Jquery
- SharePoint 2010之部署WCF(deploy WCF service to SharePoint 2010 via VS 2010 step by step)
- Get tasks assigned to user or to current user groups in SharePoint using CAML query
- How to copy files between sites using JavaScript REST in Office365 / SharePoint 2013
- How to change service accounts and service account passwords in SharePoint Server 2007 and in Windows SharePoint Services 3.0
- Remove an Event Receiver in SharePoint
- Fix SharePoint 2013 Site in Read only mode after an interrupted backup
- Using resource files in SharePoint 2010
- Work Management Service application in SharePoint 2016
- Using Reporting Services SharePoint Web Parts in SQL Server
- 深入浅出SharePoint——利用jQuery访问SharePoint Web Service获取用户信息
- Force stop and then start a full crawl on all content sources in a SharePoint 2010 farm using PowerShell(转)
- Hosting WCF in SharePoint 2007 (Part 1) 基本部署(转)
- Fix SharePoint 2013 Site in Read only mode after an interrupted backup
- How to Modify the web.config file in SharePoint using SPWebConfigModification?
- using the CopyIntoItems method of the SharePoint Copy web service
- There is not a header with name ServiceContext and namespace http://schemas.microsoft.com/sharepoint/servicecontext in the messa
- Configuring the User Profile Service in SharePoint 2010