Tuesday, December 29, 2015

How to add user to SharePoint group using REST & SPServices

Using REST:-

function AddUserToSPGroup()
{
var vCurrentLoggedUser2=$().SPServices.SPGetCurrentUser({fieldName: "UserName",debug: false});

vCurrentLoggedUser2= "KL\\" + vCurrentLoggedUser2;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(57)/users";
$.ajax({
url: requestUri,
type: "POST",
data: JSON.stringify({'__metadata': { 'type': 'SP.User' }, 'LoginName': vCurrentLoggedUser2}),
headers:
{
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});//End of ajax
function onSuccess(data)
{
alert('User Added');
}
function onError(error)
{
alert(JSON.stringify(error));
}
}


Using SPServices:-

function SetContributeAccess()
{
var vCurrentLoggedUser=$().SPServices.SPGetCurrentUser({fieldName: "Title",debug: false});

$().SPServices({
   operation: "AddUserToGroup",
   groupName: "Users",
   userLoginName: vCurrentLoggedUser,
   async: false,
   completefunc: function(data,status){
      alert("User added to group");
   }// End of completefunc
}); //End  of SPServices
}//End of SetContributeAccess

Monday, December 28, 2015

How to get logged user using SPService

var vCurrentLoggedUser2=$().SPServices.SPGetCurrentUser({fieldName: "Title",debug: false});

How to set Managed Metadata field using Jquery

<script src="../../Style Library/spjs-utility.js" type="text/javascript"> </script> 

var vSet = 'abc';
setFieldValue("ManagedMetaDataFieldInternalName",vSet);

</script>

Check out link here to see more on setFieldValue().

How to disable Managed Meta Data field and Browser button

$("div[title='FieldDisplayName1']").prop("disabled",true);//This will disable Managed Metadata textbox.

//Disable Managed Meta Data Browse button
var vNode = $(document.getElementById('FieldInternal_$containercontrolHolder')).prop("disabled",true);
$(vNode ).find("img[title='Browse for a valid choice']").prop("disabled",true);

Hide New and Edit button on Ribbon using JQuery.

Put below CSS file on content editor web part of your page.

<style type="text/css">
#Ribbon\.ListItem\.Manage\.EditProperties-Large
{
   display:none;
}


#Ribbon\.ListItem\.New\.NewListItem-Large
{
  display:none;
}


</style>

Ribbon\.ListItem\.Manage\.EditProperties-Large is the ID of Edit control on Ribbon. Similarly, You can get ID of View and New button as well using Developer tools.

Note: back slash (\) before dot (.) before each class names. Without putting back slash, you wont get the result.

Thursday, November 26, 2015

How to display workflow related tasks in the item display page where the workflow is currently running on in SharePoint2013

https://ybbest.wordpress.com/2013/05/30/how-to-display-workflow-related-tasks-in-the-item-display-page-where-the-workflow-is-currently-running-on-in-sharepoint2013/

Wednesday, November 25, 2015

How to load Javascript file properly

  1. The path may not be resolved correctly (sometimes relative urls seem just not to work correctly in SharePoint context)
  2. When using jQuery in Javascript within e.g. a SharePoint webpart try to use jQuery.noConflict() before using the SP-Services. In most cases I had issues with using $ or jQuery because of the already loaded JQuery within SharePoint.
  3. When using javascript in SharePoint $(document).ready might cause problems because this doesn´t actually mean that all content is loaded. You can try to use _spBodyOnLoadFunctionNames.push("myfunction") instead.
  4. Use ExecuteOrDelayUntilScriptLoaded(temp(), "jquery-1.10.1.min.js");
  5. $.getScript("jquery.SPServices-0.7.2.min.js",[optionalFunction() { }]); OptionalFunction() will execute after jquery in 1st parameter loaded successfully

Friday, November 20, 2015

How to update/insert item in SharePoint list or list form using SPService



function UpdateItem(fieldInternalName,fieldValue)
{
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "Update",
listName: "Sub Investment",
valuepairs: [[fieldInternalName, fieldValue]],
completefunc: function(xData, Status)
{ alert("Yahoo! Item updated"); }
});
}

batchCmd: "Update" or "New".
listName: display name of list.

How to get item from list using SPServices

<script src="../../Style Library/jquery.SPServices-0.7.2.min.js" type="text/javascript"> </script>
<script>
var v = GetLatestSubInvestmentID();

function GetLatestSubInvestmentID()
{

var myQuery = "<Query><Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where><OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy></Query>";
$().SPServices({
   webUrl: "http://skl241:25625/sites/InvestmentDB/",
   operation: "GetListItems",
   async: false,
   listName: "Sub Investment IDs",
   CAMLQuery: myQuery,
   CAMLRowLimit:1,
   CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='InvestmentInfo' /></ViewFields>",
   completefunc: function (xData, Status)
   {
   
       $(xData.responseXML).SPFilterNode("z:row").each(function()
       {
        vGetLatestSubInvestmentID= $(this).attr("ows_InvestmentInfo");
        $("input[Title='Total Amount Alloted']").val(vGetLatestSubInvestmentID);

      });//End of each()
   }//End of completefunc
 
 });//End of SPServices
return vGetLatestSubInvestmentID;
}//End of GenerateSubInvestmentID
</script>

Pad a number with leading zeros in JavaScript or Jquery

var v = pad(10,4); output as 0010


function pad(n, width, z)
{
 z = z || '0';
 n = n + '';
 return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

Wednesday, July 1, 2015

Monday, June 29, 2015

Load Balancer in SharePoint 2013


  • In computing, load balancing distributes workloads across multiple computing resources, such as computers, a computer cluster, network links, central processing units or disk drives. Load balancing aims to optimize resource use, maximize throughput, minimize response time, and avoid overload of any single resource
  • Load Balancer is used to balance & send user request load and send it to Web Front End server for continues supplying of service to user
  • Load Balancer is separate server dedicated for load balancing. Load Balancer is configured in all Web Front End server.
  • Load Balancer are by default configured in application server, so there is no need to configure external load balancer.

Load balancers use different algorithms to control traffic. The goal of these algorithms is to intelligently distribute load and/or maximize the utilization of all servers within the cluster. Some examples of these algorithms include:
  • Round-robin. A round-robin algorithm distributes the load equally to each server, regardless of the current number of connections or the response time. Round-robin is suitable when the servers in the cluster have equal processing capabilities; otherwise, some servers may receive more requests than they can process while others are using only part of their resources.
  • Weighted round-robin. A weighted round-robin algorithm accounts for the different processing capabilities of each server. Administrators manually assign a performance weight to each server, and a scheduling sequence is automatically generated according to the server weight. Requests are then directed to the different servers according to a round-robin scheduling sequence.
  • Least-connection. A least-connection algorithm sends requests to servers in a cluster, based on which server is currently serving the fewest connections.
  • Load-based. A load-based algorithm sends requests to servers in a cluster, based on which server currently has the lowest load.
Also check out Clustering VS Load Balancer here.

Friday, June 26, 2015

Workflow Manager 1.0 (SharePoint 2013)

Workflow Manager in SharePoint 2013



SharePoint 2013 Workflow platform diagram


  • Workflow Manager (WM) provides the management of workflow.
  • Workflow Manager (WM) is a separate entity outside SharePoint 2013 Server. WM doesn't install automatically with SP 2013 installer. First install Window Platform Installer (64 bit) and then with the help of WPI, you can install Workflow Manager 1.0. Download WPI over here. Once you install WPI, Open Application Tab and search for Workflow. Add "Workflow Client" component. Install it. Check out full video below. Note: Workflow Engine is still a part of SharePoint 2013 Server same like SharePoint 2010 Server. 

  • Workflow Manager is built on top of Windows Workflow Foundation (check screen above).
  • Workflow Manager has its own dedicated DB & Farm in server where WM is installed. 
  • Service Bus is also an entity resides along with WM on WM Server. Service bus also has its own dedicated DB in server where WM is installed. This Service Bus is use to take SharePoint events like itemCreated, ItemUpdated and give it to WM.
  • The SharePoint 2013 Workflow platform uses the new Workflow Manager service. 
  • WM also hosts the execution processes for workflow instances. This process is called as ServiceHost.exe. ServiceHost.exe is the process use to debug Workflow in SharePoint 2013.
  • Since WM is now a separate entity outside SP, it can be used by different application also (non SharePoint application) to enhance its ability. This was not the case in SP2010, where WF is used only for SharePoint purpose.
  • The SharePoint 2010 Workflow platform that came with SharePoint Server 2010 like Sequential and State Machine is still available in SharePoint Server 2013.
  • Window Workflow Foundation and WCF are hosted on Workflow Manager.
  • Workflow Manager Client 1.0 is represented in SharePoint 2013 in the form of the Workflow Manager Client 1.0 Service Application Proxy.
  • SharePoint events for which a workflow is listening, like itemCreated, itemUpdated, and so on,      are routed to Workflow Manager Client 1.0 using the Microsoft Azure service bus. For the return trip, the platform uses the SharePoint Representational State Transfer (REST) API to call back into SharePoint.
References:-

K2 Workflow VS Visual Studio Workflow

Category K2 Workflow SP Workflow
Monitoring You can find ‘Flow Diagram’ for the current status in graphical mode. You can also do real time monitoring of each task. No Real time monitoring for each task.
Code Simple No code solution. Business user can also use it. Developer need to code. Business user cannot code it. 
Scope It can live also on non sharepoint platform like SAP, CRM etc. It live only on SharePoint. 
Error handling K2 introduces a ‘BlackPearl Workspace’ site which  manages all for Error handing of each instance, managing workflow permission and tracking workflow process etc. We need to write custom code for Error handling.
Browser K2 support browser based workflow No browser support for designing custom workflow. Yes, SharePoint do have OOTB browser support workflow but can't satisfy all variety of requirment
Cost K2 product is very expensive. Need their own dedicated server for running their processes SharePoint too is very costly, but SharePoint provides couple of other feature too apart from workflow like webparts, web application etc. 
Enterprise wide tool Tool for SharePoint as well as enterprise wide need. Tool for SharePoint applications. It need other tool to satisfy enterprise need. Like InfoPath for fultilling form ability. Exel charts to fultill reports need etc.
K2 has their own logging mechanism which log data in DB for infinite nos. of days.
Delivery cycle Speed up development and delivery cycle. Since, developer has to code it, it may take time for huge change in requirment.

Saturday, April 18, 2015

__doPostBack()

__doPostBack()

Define - Use to trigger post back event MANUALLY (and NOT by ASP.NET)  for any ASP.NET control.

Good link to understand it
http://www.codedigest.com/Articles/ASPNET/320_Doing_or_Raising_Postback_using___doPostBack()_function_from_Javascript_in_AspNet.aspx

Sunday, April 5, 2015

Simple Jquery Dialog or Input box



Code in *.ascx file
<link href="/sites/9999/_layouts/dialog.css" rel="stylesheet"/>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/ui-darkness/jquery-ui.css" rel="stylesheet"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<script src="/sites/9999/_layouts/dialog.js" type="text/javascript" />

<script type="text/javascript"></script>
<table>

<table>
    <tr>
        <td>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="OpenMyDialog(); return false" />
        </td>
    </tr>
</table>

<div class="container">
    <div class="main">
        <div id="dialog" title="Profile Input">
            <form action="" method="post">
            <label>
                Enter Profile Name:</label>
            <input id="name" name="name" type="text" />
            <br />
            <br />
            <input id="submit" type="submit" value="Ok" class="PopUpOkButton" />
            <input id="close" type="button" value="Close" class="PopUpCloseButton" />
            </form>
        </div>
    </div>
</div>


dialog.js

$(document).ready(function () {
    $(function () {
        $("#dialog").dialog({
            autoOpen: true
        });
    });

    $("#submit").click(function (e) {
        alert($("#name").val());
        return false;
    });
    $("#close").click(function (e) {
        $("#name").val("");
        $("#dialog").dialog("close");
    });
});

function OpenMyDialog() {
    $("#dialog").dialog("open");
}

dialog.css

.PopUpOkButton
{
    border:1px solid #59b4d4;
    background:#0078a3;
    color:#eee;
    padding:3px 0;
    border-radius:5px;
    margin-left:0%;
    cursor:pointer;
    width:80px
}

.PopUpCloseButton
{
    border:1px solid #59b4d4;
    background:#0078a3;
    color:#eee;
    padding:3px 0;
    border-radius:5px;
    margin-left:0%;
    cursor:pointer;
    width:80px
}

Detail reference over here.

Tuesday, March 24, 2015

Client Object Model Limitation


There are few limitation for Client Object Model especially JSOM.
  • We cannot perform any SharPoint administrative functionality.
  • It's functionality is restricted upto website. This is meant to restrict any cross-site scripting vulnerabilities. Think of it as sandboxed SharePoint code.
  • It's functionality will work only If javascript is turned on in browser. Hence, CSOM is better  used on intranet portal and lesser used on internet facing site.

Wednesday, March 18, 2015

Setup Javascript Object Model (JSOM) and its references enviroment

I recently started learning JSOM and was bit frustrated setting up the environment. Hence, I thought to write the detail in setting up environment so other folks can save their time.
  • Manually adding *.js files in Visual Studio
  • Setting up *.js file to enable Intellisense in Visual Studio.

Manually adding *.js files in Visual Studio:

After adding Visual WebPart, We need to mapped Layouts folder in Visual Studio. Please note that Layouts folder will directly mapped to Layouts folder under 15 hives. You can find all *.js files under 15 hive's Layouts folder.
C:\program files\common files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS

Steps
Right click on Project name -> Add -> SharePoint Layouts mapped folder. This will add Layout folder under project hierarchy in Visual Studio and Project folder in file system.

In this case, we will add Scripts folder under Layouts folder. Add below *.js files under Scripts folder. 
  • SP.js
  • SP.Runtime.js
  • init.js
  • MicrosoftAjax.js
  • jquery-1.11.2.js (optional, in case you are using any jquery functionality)
Setting up *.js file to enable Intellisense by referring them in ASCX or ASPX file.

<script src="../Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../Scripts/INIT.js" type="text/javascript"></script>
<script src="../Scripts/SP.Runtime.js" type="text/javascript"></script>
<script src="../Scripts/SP.js" type="text/javascript"></script>

Complete code is as under.
<script src="../Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../Scripts/INIT.js" type="text/javascript"></script>
<script src="../Scripts/SP.Runtime.js" type="text/javascript"></script>
<script src="../Scripts/SP.js" type="text/javascript"></script>
<SharePoint:FormDigest ID="FormDigest1" runat="server"/>

<asp:Button ID="Button1" runat="server" Text="Create Item" OnClientClick="Create();" />
<asp:Button ID="Button2" runat="server" Text="Edit Item" OnClientClick="Update();" />
<asp:Button ID="Button3" runat="server" Text="Delete Item" OnClientClick="Delete();" />
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
<script type="text/javascript">
    var web;
    var user;
    var listItem;
    var list;
    
    function Create() {
        debugger;
        var url = _spPageContextInfo.webAbsoluteUrl;
        SP.SOD.executeFunc('SP.js', 'SP.ClientContext', createListItem);
        
        function createListItem() {
            debugger;
            try {
                var clientContext = new SP.ClientContext(url);
                web = clientContext.get_web();
                list = web.get_lists().getByTitle('CustomList');

                var itemCreation = new SP.ListItemCreationInformation();
                listItem = list.addItem(itemCreation);

                listItem.set_item('Title', 'New Item...');//field internal name
               
                listItem.update();

                clientContext.load(listItem);
                clientContext.executeQueryAsync(function () {
                    alert("success-" + listItem.get_id());

                }, function (sender,args) {
                    alert("fail " + args.get_message());

                });
            }
            catch (err) {
                alert("Error " + err);
            }
        }

    }

    function Update() {
        $(document).ready(function(){
            var url = _spPageContextInfo.webAbsoluteUrl;
            SP.SOD.executeFunc('SP.js', 'SP.ClientContext', updateListItem);

            function updateListItem() {
                try {
                    var ctx = new SP.ClientContext(url);
                    list = ctx.get_web().get_lists().getByTitle('CustomList');
                    debugger;
                    var txt = $('#ctl00_ctl40_g_49535078_3b19_431f_aaf9_fec512858a8a_txt').val();//internal name of txt field taken from developer tools.
                    listItem = list.getItemById(txt);
                    listItem.set_item('Title', 'Title updated');
                    listItem.update();

                    ctx.load(list);
                    ctx.load(listItem);
                    ctx.executeQueryAsync(function () { alert("Item updated"); }, function () { alert("Item fail to update"); });

                }
                catch (err) {
                    alert("Error " + err.message);
                }
            }
        });
            
           
    }

    function Delete() {
        var url = _spPageContextInfo.webAbsoluteUrl;
        SP.SOD.executeFunc('SP.js', 'SP.ClientContext', Del);

        function Del() {
            try{
                var ctx = new SP.ClientContext(url);
                list = ctx.get_web().get_lists().getByTitle('CustomList');
                var txt = $("#ctl00_ctl40_g_49535078_3b19_431f_aaf9_fec512858a8a_txt").val();
                listItem = list.getItemById(txt);
                listItem.deleteObject();

                ctx.load(list);
                ctx.load(listItem);
                ctx.executeQueryAsync(function () { alert("deleted"); }, function () { alert("Problem deleting this item"); });
            }
            catch (err) {
                alert("Error - " + err.message);
            }
        }
     

    }

       

</script>



Friday, March 6, 2015

Creating SharePoint Hosted App from Visual Studio 2012

I am new to Apps and today I tried creating "Hello World!" stuffs through App. This URL (check out section Configure an isolated app domain to create and deploy SharePoint-hosted apps)  will give precise info. on configuration we need to make on Domain / Browser / Central Admin. before using App for first time.

Check out YouTube video for basic programming for App.

Wednesday, March 4, 2015

CSWP vs CQWP

Content Search By WebPart VS Content Query by WebPart

  1. CSWP search through out SharePoint sites (farm level). CQWP search through out SiteCollection.
  2. CSWP gets crawled result. Hence, recently updated item may not be displayed. CQWP gets immediate result. Hence, recently updated item is displayed with ease.

Monday, March 2, 2015

What is OData?

I was always confuse between OData and RESTFul API. After few hours of googling, I found below info. 

Definition 
OData (Open Data Protocol) is a protocol which allow to creates and consume querable and interoperable RESTful API in a SIMPLE and STANDARD way. In short, OData consume RESTFul API and allow developer to focus only on their business logic rather than focusing on details of request/respond like type of request, methods, header, URL & Media type etc.

OData VS RESTFul Service?
OData talks about "what" the messages look like (the content). REST is the architecture of "how "those messages get sent back and forth.

OData support operations above CRUD. OData also specifies a very rich query language to enable consumers query your services for precise information they are looking for - with the help of $filter, $orderby, $skip, $top, $expand.

OData helps you describe your entire Data Model - Entities and their Relationships and support all kinds of operations like CREATE, UPDATE, DELETE, GET, MERGE and even CUSTOM OPERATIONS on these Entities and/or Relationships.

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

    Saturday, January 17, 2015

    Referencing javascript file from SharePoint ASCX page

    We can refer *.js file from SharePoint visual part (*.ascx) file via <SharePoint:ScriptLink> tag. Example

    <SharePoint:ScriptLink ID="ScriptLink1" runat="server" Language="javascript" Name="/_layouts/15/css/clienttemplates.js" />

    OR

    <script src="/_layouts/15/autofill.js" type="text/javascript"> </script>