Sivarajan's Blog

SharePoint | Office 365 | Azure | JavaScript

SharePoint 2013 Responsive WebPart using Knockout with WCF REST Service - Part 1

How to create the SharePoint client WebPart based on MVVM concepts. I plan to use Knockout.Js (for MVVM) and Knockout External Template (for Responsive design) and WCF REST Services.

Advantages

The main advantage of the concepts is that there is no PostBack or ViewState and the same implementation will be applicable to SharePoint Server/ foundation, Office 365.

The main topics

  • Creating a custom WCF REST Services (Deployment using ServiceHost and Web.Config changes is not required)
  • Creating a Data Services for consume WCF REST Services
  • Creating a Knockout View Model object
  • Client Data Binding
  • Create a HTML templates
  • Responsive View

Prerequisites

For this code walkthrough, we need a following JavaScript libraries

1. Toastr JavaScript framework

2. Knockout.Js and Knockout External Template

Creating a custom WCF REST Services

I plan to expose the custom database data (SQL Server) using WCF REST Service.

1. Create a SharePoint – Empty project and change the following values

wcf1-1

2. Add a Layouts folder for deploying WCF Services

3. In Visual Studio 2012, there is not any direct way to create WCF REST Service using template. For workaround, add the text file (available in General section) and then rename it as ProductService.svc

3. Create a folder Code and then add the following class files IProductService.cs, ProductService.cs and Product.cs

4. Add the System.ServiceModel and System.ServiceModel.Web namespace

5. Add the SQLHelper.cs file for database operations and you can download this file at the end of the post. And also you can find the SQL scripts to create a Product table.

wcf1-2

6. The solution structure will be like below,

wcf1-3

7. Add the following code in the ProductService.svc file

ProductService.svc
<%@ServiceHost language="C#"
    Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressDataServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
    Service="SharePointMVVM.ProductService" %>

 

8. Add the following code in the Product.cs file

Product.cs
namespace SharePointMVVM
{
    public class Product
    {
        public string ProductId { get; set; }

        public string CategoryId { get; set; }

        public string ProductName { get; set; }

        public string ProductDesc { get; set; }

        public string ImagePath { get; set; }
    }
}

 

9. Add the following code in the IProductService.cs file

IProductService.cs
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace SharePointMVVM
{
    [ServiceContract]
    public interface IProductService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "Products/{categoryId}")]
        List<Product> GetProducts(string categoryId);
    }
}

 

10. Finally add the following code in the ProductService.cs file and also I added [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  for enabled ASP.NET compatibility mode to use session or cache inside service.

Code Snippet
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ProductService : IProductService
    {
        public List<Product> GetProducts(string categoryId)
        {            
            string sqlQuery = string.Format("SELECT ProductId, CategoryId, Name, Descn as ProductDesc, [Image] as ImagePath FROM Product WHERE CategoryId = '{0}'",categoryId);

            List<Product> products = new List<Product>();

            using (SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionString, CommandType.Text, sqlQuery, null))
            {
                while (rdr.Read())
                {
                    products.Add(new Product()
                        {
                            ProductId  = rdr.GetString(0),  
                            CategoryId = rdr.GetString(1),
                            ProductName = rdr.GetString(2),
                            ProductDesc = rdr.GetString(3),
                            ImagePath = rdr.GetString(4)                        
                        });
                }
            }
            return products;
        }
    }

 

11. Deploy the solution and test the ProductService.svc file

wcf1-4

 

 

 

 

 

 

Summary 

In Part 1, we have created the custom WCF REST service to expose the data to client and will see that how to create the MVVM client model to bind the data using Knockout in the next post.

You can find the sample source code here.

Comments (1) -

  • Eddine

    7/14/2013 6:31:59 AM | Reply

    Hey Sir,
    it does'nt work for me, i worked with CKS in VS 2010 that worked fine but it doesn't exists yet for SP 2013, so your method gives me an error and i cannot open your solution.

    I 've VS 2012 ultimate, it says to me that your code has been done with another version of VS.

    Can you give me more details.

    Thank you

Pingbacks and trackbacks (1)+

Add comment

Loading