Thursday, February 26, 2015

SOAP vs REST. Which one to choose when?



  1. REST naturally fits for Web/Cloud API's, whilst SOAP fits for distributed computing scenarios.
  2.  JSON is a widely-recognized and simple standard for data exchange, and is easily read by browsers and client code, which is why most RESTful API's (Facebook and Twitter API is a good example of RESTFul API) offer JSON.
  3. The RESTful Web services are completely stateless (every request is separate and not dependent on earlier request). This can be tested by restarting the server and checking if the interactions are able to survive. While, SOAP service are stateful (each request is dependent on earlier request. Hence, sometime server has to persist few request to get few info. for future  request).
  4. REST is meant for caching/scalability of application. Whilst, SOAP is meant for security/contract between Client/Server.
  5. REST-based implementation is simple compared to SOAP.Programming in REST is easy compare to SOAP.
Problem with SOAP (Simple Object Access Protocol):
  1. Works with XML to exchange information between entities.The XML used to make requests and receive responses in SOAP can become extremely complex. In some programming languages, you need to build those requests manually, which becomes problematic because SOAP is intolerant of errors. However, other languages can use shortcuts that SOAP provides; that can help you reduce the effort required to create the request and to parse the response. In fact, when working with .NET languages, you never even see the XML. Part of the magic is the Web Services Description Language (WSDL). This is another file that’s associated with SOAP. It provides a definition of how the Web service works, so that when you create a reference to it, the IDE can completely automate the process. So, the difficulty of using SOAP depends to a large degree on the language you use. In short, Many developers found SOAP cumbersome and hard to use. For example, working with SOAP in JavaScript means writing a ton of code to perform extremely simple tasks because you must create the required XML structure absolutely every time.While, REST provides a lighter weight alternative. Instead of using XML to make a request, REST relies on a simple URL in many cases.
  2. Unlike SOAP, REST doesn’t have to use XML to provide the response. You can find REST-based Web services that output the data in Command Separated Value (CSV), JavaScript Object Notation (JSON) and Really Simple Syndication (RSS). The point is that you can obtain the output you need in a form that’s easy to parse within the language you need for your application.


Deciding Between SOAP and REST

SOAP is definitely the heavyweight choice for Web service access. It provides the following advantages when compared to REST:
  • Language, platform, and transport independent (HTTP / SMTP / FTP) (While, REST requires use of HTTP)
  • Works well in distributed enterprise environments (REST assumes direct point-to-point communication)
  • Standardized
  • Provides significant pre-build extensibility in the form of the WS* standards
  • Built-in error handling
  • Automation when used with certain language (like .Net) products.
  • Mainly meant for enterprise application (bank website, organisation website etc.) since SOAP provide advantage of security feature (WS-Transaction specification).
REST is easier to use for the most part and is more flexible. It has the following advantages when compared to SOAP:
  • No expensive tools require to interact with the Web service
  • Smaller learning curve
  • Efficient (SOAP uses XML for all messages, REST can use smaller message formats)
  • Fast (no extensive processing required)
  • Closer to other Web technologies in design philosophy
  • Support more interoperability compare to SOAP. Check here.
  • Mainly used for Internet facing application (Facebook, Twitter) since REST brings advantage of scalabilty and speed.Check here (After all that information, aren't you telling me that REST is good for Internet-facing applications, and SOAP for enterprise applications?)



Reference document (best article to understand SOAP and REST in few min.) Thanks to John Mueller.


Wednesday, February 25, 2015

What is REST?

Official Definition of REST
REST is an architecture style (concepts / theory) built on certain principle of web. REST is a PROTOCOL design on HTTP. REST is an architecture for how to send messages back and forth from a client to server using HTTP.

Define Protocol: 
Set of rules for requesting information from server using special technique.

Representational state transfer is using WEB feature in simple and effective way. It take advantage of 40 years old matured HTTP protocol features/methods and apply its own PRINCIPLES. 


HTTP features like 

  • GET/PUT/POST/Delete methods on resources, 
  • http protocol is stateless.
  • URI - locate anything on web.

REST Principles:

  1. RESOURCES - Everything is RESOURCE from REST point of view e.g. images / files / videos etc. So think everything as RESOURCE.
  2. IDENTIFIER - REST always GET the resource by UNIQUE identifies. e.g. http://www.google.com/Customers/Chintan OR http://www.google.com/Customers/items(111)
  3. INTERFACE - Keep your interface simple and uniform to achieve CRUD operations like it uses HTTP METHODS GET / PUT / DELETE / POST to do the operations rather than allowing user to create their own methods and spread confusion. Hence, REST will use HTTP methods to work with resource to maintain uniformity.
  4. REPRESENTATION - All communication happen between client and server and vice-versa is called as  REPRESENTATION. The server might respond it in XML or JSON format depending on what developer has specify on their application.
  5. STATELESS - Every request is stateless. Every request which you send is independent of earlier request. Server need not have to remember the state of every request. e.g. if client try to access server for the first time, server ask for authentication. Once successfully authenticated, if client make 2nd request, then server along with request, client also send SUCCESS authentication message so server need not ask for authentication.
Why REST?
It take advantage of HTTP and allow to boost application performance and scalibility.

Command to add before executing PowerShell

Before you run any Poweshell scripts, you should add its DLL which include all API necessary to run the scripts.

Add-PSSnapin Microsoft.SharePoint.PowerShell

Sunday, February 22, 2015

SharePoint 2013 App model with real life example


SharePoint Hosted App

  • Explaining with e.g. If Admin. sell app to 100 persons
  • Each person has single instance running on their client.
  • App install/run on respective client. Data runs/access on respective client.
  • No access to Admin on the app which is running by 100 persons.
  • Isolated from each persons context because they app run on respective client.
  • No problem of multi-tenancy
  • Real life example - Maruti company (means Admin. on SharePoint) sold maruti car (means App on SharePoint) to 100 customers (means Client machine on SharePoint). Each customer has their respective maruti car. Maruti company once sold need not do any maintenance / access rights for sold maruti car. Maruti car once sold is a an isolated entity.
SharePoint Hosted App

Provider Hosted App (It could be "any" server on windows / linux / Unix etc.)


  • Explaining with e.g. If Admin. sell app to 100 persons
  • Each App talk to "single" web server
  • Admin. has to govern multi-tenancy.Admin has to know which client the request belongs to.

  • Admin. should govern that client is given access to their respective data requested by client.


  • Real life example - Milk man (means Web Server) selling the milk (means App on SharePoint) to 100 customers. Each customer has to depend on Milk man to supply milk to their houses. Here, Milk man (means Web server) has to govern milk (means app) delivery and orders from customer (means Client). In order to fulfill his job, Milk man should know how much liter each customer require every day and accordingly he will supply the milk. Customer should get service from Milk man on daily basis and Milk man should supply service on daily basis. They are not isolated but has to depend on Milk man to get the milk.

  • Provider Hosted App

    Auto Hosted App (Azure web server only, work a bit same like SharePoint Hosted App)

    • Explaining with e.g. If Admin. sell app to 100 persons
    • It create separate 100 azure websites for each client/user. However, this websites are hosted on Azure server.
    • Admin. do not have access on these azure websites.
    • No problem of multi-tenancy because each client have their own azure websites.
    • Real life example - Tower ( means Azure server) on lease having 5 floors (means Azure WebSites) given to 5 difference companies ( means SharePoint Apps) on each floor. Here, xyz owner (means Azure Admin.) owns the tower and 5 companies take each floor on lease. All companies have their dedicated space to run their jobs. Neither owner nor other company has access to enter company premises. Once on lease, owner don't have to worry on governing them. Company has to govern their premises include electricity, water, furniture, security, CCTV etc.

    Auto Hosted App

    Friday, February 20, 2015

    LINQ to SP and LookUp operation

    Below code will get the actual look up value from look up list. There is no way out to get look up value from the list which has look up column. We should get this value with look up list reference avail. in Entity Class.


    We have Emp (Child list) and Dept (lookup list). Emp list has Dept lookup column pointing to Dept list's Title column.

    EmpDataContext dc = new EmpDataContext("http://ramsqlbi:47407/sites/test/");

                    EntityList<EmpEntity> empList = dc.GetList<EmpEntity>("Emp");

                    var getName = (from emp in empList
                                             where emp.Dept.Title == "IT"
                                             select emp).First();

                    string lstrFirstName = getName.Title;

    Above code will seek Dept "IT" in Dept list and display First Name from Emp list. Take a look at code "emp.Dept.Title". Emp object has Dept reference which points to Dept list and match Title column in Dept. list. This is the way to query lookup value.

    Thursday, February 19, 2015

    SPMetal command to generate Entity Class for specific list

    SPMetal tool is use to generate Entity Classes and reduce developer work drastically. SPMetail resides at location -

    C:\program files\common files\microsoft shared\Web Server Extensions\15\BIN

     Hence, below command will do the job and generate Entity class for us.


    C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN>spmetal.exe /web:http://ram:40705/sites/site1 /namespace:LINQToSP /code:EmployeeEntities.cs

    However, above command will generate Entity classes for all the list available in given website (/web). Generating N nos. of entity classes is of no use till we need it. However, we can too generate entity class for specific list.

    Get all the details over here.


    Handling Conflicts changes in Linq To SharePoint

    EmployeeEntitiesDataContext dc =null;
                try
                {
                    EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ramsqlbi:40705/sites/gqs/");
                 
                        EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
                        var updatedResult = (from empToUpd in emp
                                             where empToUpd.FirstName == "Yagnesh"
                                             select empToUpd).First();

                        updatedResult.FirstName = "Yagnesh2";
                        updatedResult.Title = "Kotecha";
                        dc.SubmitChanges();
                }

                catch (Microsoft.SharePoint.Linq.ChangeConflictException exc)
                {
                    foreach (ObjectChangeConflict conflicts in dc.ChangeConflicts)
                    {
                        //conflicts.Resolve(RefreshMode.KeepCurrentValues);//Keep current value and override anything in DB with this value
                        //conflicts.Resolve(RefreshMode.OverwriteCurrentValues);//Keep Database version
                        conflicts.Resolve(RefreshMode.KeepChanges);
                    }

                    dc.SubmitChanges();
                }

    LINQ to SharePoint to work with CRUD operation

    LINQ is the best to work on list and its operations and avoiding SPSite, SPList and SPListItem stuffs.

    Add item in list with LINQ to SharePoint

    using (EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ram:40705/sites/site1/"))
                {
                    EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
                    EmployeeItem newItem = new EmployeeItem()
                    {
                        FirstName = "deepak",
                        Title = "desai",
                    };
                    emp.InsertOnSubmit(newItem);
                    dc.SubmitChanges();
                }

    Update item

    EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext ("http://ram:40705/sites/site1/");
                   
                        EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
                        var updatedResult = (from empToUpd in emp
                                             where empToUpd.FirstName == "Yagnesh"
                                             select empToUpd).First();

                        updatedResult.FirstName = "Yagnesh2";
                        updatedResult.Title = "Kotecha";

                        dc.SubmitChanges();

    Delete item

    using (EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ram:40705/sites/site1/"))
                {
                    EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
                    var result = (from empToDel in dc.Employee
                                      where empToDel.FirstName.StartsWith("c", +
                                      StringComparison.CurrentCultureIgnoreCase)
                                      select empToDel);
                    emp.DeleteAllOnSubmit(result);
                    dc.SubmitChanges();

                }

    LINQ to SharePoint to seek name

    One of the good feature of LINQ is to provide functinality to interact with SharePoint. LINQ is not only to "query" SharePoint list but also to provide CRUD operation on SharePoint list (known as LINQ to SP)

    Noteworthy:

    • LINQ to SharePoint queries are translated to proper CAML queries
    • CAML queries are in turn later translated to SQL queries


    Technically, the purpose of LINQ to SP is to replace the weird syntax of CAML query and provide user with Object Oriented way to do operations with SharePoint which is much easy to read / code and allow intelligence in Visual Studio during debug which was not feasible while working with CAML.

    Lets begin with simple example.

    Employee List


    Here, I have created 1 example with employee list. We will write LINQ to SharePoint code to retrieve employee with name "Yagnesh".

    Note: Use SPMetal exe which will generate Entity classes for DataContext. Get more info. on SPMetal here. If not, then developer has to create and decorate classes and its property by him self.

    EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ram:40705/sites/site1/");
    EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
    var updatedResult = (from empToUpd in emp
                                     where empToUpd.FirstName == "Yagnesh"
                                     select empToUpd).First();

    First, we need to retrieve Data Context object. Data context object represent subset of content database which holds and work on list and list items.

    EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ram:40705/sites/site1");

    Then, Getting reference to the list:

    EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");

    EntityList<> Generice class is use to get any type of list available in SharePoint. Note, EmployeeItem is the class which represent all fields in Employee list.

    Finally, LINQ query to seek employee name "Yagnesh".





    Thursday, February 12, 2015

    Adding data to list in a Batch in SharePoint


    SharePoint provide a functionality to perform CRUD operation in "bulk" with SPWeb's Batch Process methods. Below is the sample to ADD items in bulk.

    //Hard Coded e.g. This I have just describe to learn the CAML query thoroughly.
    <ows:Batch OnError="Return">1</ows:Batch>//1=itemID.
    <Method ID="1">//1=itemID. Note - itemID is in double quotes.
        <SetList>2222-22222222-2222</SetList>//ListID
        <SetVar Name="Cmd">Save</SetVar>
        <SetVar Name="ID">1</SetVar>//1=itemID
        <SetVar Name="urn:schemas-microsoft-com:office:office#Title">Title 1</SetVar>
    </Method>

    //Dynamic Code e.g.
    <ows:Batch OnError="Return">{0}</ows:Batch>//1=itemID.
    <Method ID=\"{0}\">//1=itemID. Note - itemID is in double quotes.
        <SetList>{1}</SetList>//ListID
        <SetVar Name="Cmd">Save</SetVar>//Use Delete keyword to delete item, Save keyword to update item
        <SetVar Name="ID">{2}</SetVar>//1=itemID
        <SetVar Name="urn:schemas-microsoft-com:office:office#Title">{3}</SetVar>
    </Method>

    ---------------------------------------------------------------------------------------------------------
    Real time application e.g. with bulk updates.

                   
                    using (SPSite site = new SPSite(gstrURL))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList listBatch = web.Lists["BatchTest"];
                            string lstrBatchFormat = string.Empty, lstrMethodFormat = string.Empty;
                            StringBuilder methodBuilder = new StringBuilder();
                           
                            lstrBatchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                  "<ows:Batch OnError=\"Return\">{0}</ows:Batch>";

                            lstrMethodFormat ="<Method><SetList>{1}</SetList>" +
                                    "<SetVar Name=\"ID\">New</SetVar>" +
                                    "<SetVar Name=\"Cmd\">Save</SetVar>" +
                                    "<SetVar Name=\"urn:schemas-microsoft-com:office:office#Title\">" +
                                    "{2}</SetVar>" +
                                     "<SetVar Name=\"urn:schemas-microsoft-com:office:office#aaa\">" +
                                    "{3}</SetVar>" +
                                    "</Method>";

                            for (int i = 0; i < listBatch.Items.Count; i++)
                            {
                                SPListItem item =listBatch.Items[i];
                                methodBuilder.AppendFormat(lstrMethodFormat,  listBatch.Items.Count++, listBatch.ID.ToString(), "Title-" + i, "aaa-" + i);
                            }

                            string lstrBulkBatch = string.Format(lstrBatchFormat,methodBuilder);
                            string lstrResult = web.ProcessBatchData(lstrBulkBatch);

                        }
                    }

    MSDN Reference:
    Article 1