Monday, 21 March 2016

Load Vs LoadQuery

Load vs Loadquery

The LoadQuery method works in much the same way as the Load method, but it allows the client to process the queries more efficiently. The main difference is that the Load method populates the client object or client object collection that is passed into it. The LoadQuery method instead returns an entirely new collection of client objects. To get a clarification of these differences, examine the following examples for .NET managed code.
Retrieving the Number of Lists via the Load Method
class Program
{
static void Main(string[] args)
{
ClientContext ctx = new ClientContext(“http://server”);
ctx.Load(ctx.Web.Lists);
ctx.ExecuteQuery();
Console.WriteLine(“” + ctx.Web.Lists.Count);
Console.ReadLine(“Press RETURN…”);
}
}
In the above example Console.WriteLine(“” + ctx.Web.Lists.Count); will write the count of lists in the web since the ctx.Web.Lists gets loaded with the lists in the context.
Now lets see the other example, which uses the LoadQuery method, which is also initialized with the ctx.Web.Lists object. However, after the query is executed, the lists are returned as a completely new client object collection. If you try to directly access the property ctx.Web.Lists.Count, a CollectionNotInitialized exception is raised. This implies that, unlike in the above code, the original ctx.Web.Lists property has not been populated. Instead, a new allLists collection has been created and populated.
Retrieving the Number of Lists via the LoadQuery Method
class Program
{
static void Main(string[] args)
{
ClientContext ctx = new ClientContext(“http://server”);
IEnumerable allLists = ctx.LoadQuery(ctx.Web.Lists);
ctx.ExecuteQuery();
Console.WriteLine(“” + allLists.Count());
Console.ReadLine(“Press RETURN…”);
}
}
The advantage of LoadQuery over the Load method is its flexibility, especially when working with more than one query. It gives you better control over memory consumption, and query processing is more efficient. Consider garbage collection: the Load method populates objects that reside within the ClientContext instance. Those objects can only be cleaned up when the ClientContext instance is destroyed. Conversely, objects created by LoadQuery are separate from the ClientContext instance and can be destroyed much more readily, for example by setting them to NULL.

Step by step guide on upgrading a SharePoint 2010 site to a SharePoint 2013

  1. Add and deploy any required O14 custom solutions in your SharePoint 2013 farm, notice that all O14 solutions being deployed under 14 hive but eventually it’s recommended to migrate the custom code to O15.
  2. Backup and restore the SharePoint 2010 content database to your SQL Server hosting SharePoint 2013 farm.
  3. Run Test-SPContentDatabase cmdlet to identify missing components along with potential errors and related warnings. Check the upgrade log and deploy any missing components and re run the cmdlet to verify.
  4. Attach the content database to the desired web application using Mount-SPContentDatabase cmdlet.
  5. After successfully mounting the content database to web application, the site should be accessible in 14 mode.
  6. To upgrade the site simply click on “Start now” link on the toolbar, you can also go to SiteUpgrade page from Site Setting page as well.
  7. Click on “TRY A DEMO UPGRADE” link to verify the site collection upgrade (This step can be performed by Site Collection Administrators, farm admins can run
    Request-SPUpgradeEvaluationSiteCollection cmdlet as well).
  8. Provision a temporary site collection to validate the site post-upgrade.
  9. An email should be sent out to Site Collection admin when the temporary site is provisioned.
  10. After validating the temporary site we upgrade the site by going to SiteUpgrade.aspx page and clicking on “Upgrade the Site Collection” button (Farm admins can run Upgrade-SPSite cmdlet as well).
  11. During the upgrade The SiteUpgrade.aspx page shows the progress and provides a link to an upgrade log for troubleshooting purposes.
  12. Your site collection should now be accessible in 15 mode along with all new capabilities enabled in the farm and for the hosting web application such as Social and Office Web Apps.
Note: If there are any reference you manually added to CSS, JS, Images or any other files in your custom solutions which are in Layouts, you need to change the path of these references to point it to 15 hive layout.
e.g.
14 Hive – _/layouts/myPlugin.js
15 Hive – _/layouts/15/myPlugin.js



Sunday, 20 March 2016

Send Email Using SMTP Client

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("ToEmailAddress");
message.Subject = "The subject";
message.From = new System.Net.Mail.MailAddress("FromEmailAddress");
message.Body = "Email Body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("Address to your SMPT server");
smtp.Send(message);

Friday, 21 November 2014

SPServices UpdateListItems batchUpdate

Below code is updating AssignedTo field in Task List for multiple items in List

//for updating multiple items in tasks list
var update_string="<Batch OnError='Continue'>";
var count=0;

for(var i=0;i<ArrayTest.length;i++)  // ArrayTest is having list items IDs
{
count++;
update_string = update_string+"<Method ID='"+count+"' Cmd='Update'>" +
"<Field Name='ID'>"+ArrayTest[i]+"</Field>" +
"<Field Name='AssignedTo'>TestUser</Field>" +
"</Method>";  
}
update_string = update_string+"</Batch>";

$().SPServices({
operation: "UpdateListItems",
async: true,
batchCmd: "Update",
listName: "Tasks",
updates: update_string,
completefunc: function(xData, Status)
{
//alert(xData.responseText);
}
});

SPServices GetListItems Operation

//Add reference in js file
<script src="/js/jquery.SPServices-0.7.2.min.js"type="text/javascript"></script>

//CAML Query that will be used in SPServices GetListItems Operation
var funderQuery = "<Query>" +
"<Where>" +
                                "<Eq>"+
"<FieldRef Name='ID' /><Value Type='Text'>"+thisItemID+"</Value>"+
"</Eq>"+
"</Where>" +
"</Query>";

$().SPServices(
{
operation: "GetListItems",  
async: false,        
listName: "ListName",
CAMLViewFields: "<ViewFields><FieldRef Name='FieldInternalName' />     </ViewFields>",
CAMLQuery: funderQuery,
completefunc: function (xData, Status)
{      
if (Status == "success")
{      
//alert(xData.responseText);
$(xData.responseXML).SPFilterNode("z:row").each(function()
{
var field = $(this).attr("ows_FieldInternalName");
});
}
}
});

Wednesday, 22 October 2014

REST Services CRUD Operations in Sharepoint 2013

REST Services – High Level Overview

Let’s start out with our basic get commands in REST. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.

COMMAND

URL
Get All Lists
http://server/site/_api/lists
Get All List Items From a Single List
http://server/site/_api/lists/getbytitle(‘listname’)/items
Get a Single List Item
http://server/site/_api/lists/getbytitle(‘listname’)/items
Get Back Certain Columns
http://server/site/_api/lists/getbytitle(‘listname’)/items?$select=Title,Id
Order Your Results
 http://server/site/_api/lists/getbytitle(‘listname’)/items?$orderby=Title

CRUD operations using REST in Sharepoint 2013

Get a Single List Item

function getListItem(url, listname, id, complete, failure) 
{
        // Getting our list items
        $.ajax({
                url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {
                        // Returning the results
                        complete(data);
                },
                error: function (data) {
                        failure(data);
                }
                });
        }
}


Creating list items gets a little bit tricky, because you’ll need a few key pieces of information:
- The List Item type 
- REQUESTDIGEST value to prevent replay attacks
- An object containing your List Item Values
// Adding a list item with the metadata provided
function addListItem(url, listname, metadata, success, failure) 
{
    // Prepping our update
    var item = $.extend({
        "__metadata": { "type": getListItemType(listname)}
    }, metadata);

    // Executing our add
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data); // Returns the newly created list item information
        },
        error: function (data) {
            failure(data);
        }
    });
}


Updating list items is very similar to the task of creating list items when using jQuery Ajax calls.  You’ll need the same information you used then you created your list item, with one more piece of information: 
- The List Item Type 
- REQUESTDIGEST 
- An object containing your List Item Values & Item Type 
- The REST URL to your List Item (We use our getListItem function to get this reliably, See Above)
- Stored in: data.d.__metadata.uri
function updateListItem(url, listname, id, metadata, success, failure)
{
    // Prepping our update
    var item = $.extend({
        "__metadata": { "type": getListItemType(listname) }
    }, metadata);

    getListItem(url, listname, id, function (data) {
        $.ajax({
            url: data.d.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.d.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });

    }, function (data) {
        failure(data);
    });
}
Deleting a list item also requires the REST URL that leads to the List Item you would like to delete.  Again, we get this through our getListItem function (See Above).  So you’ll need: 
- The List Item Type 
- REQUESTDIGEST 
- REST URL to your List Item (via our getListItem function)
// Deleting a List Item based on the ID
function deleteListItem(url, listname, id, success, failure) 
{
    // getting our item to delete, then executing a delete once it's been returned
    getListItem(url, listname, id, function (data) {
        $.ajax({
            url: data.d.__metadata.uri,
            type: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-Http-Method": "DELETE",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "If-Match": data.d.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    });
};

Thursday, 16 October 2014

CRUD operation using SPServices

Get List Items Using SPServices


$().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Listname",
    CAMLQuery: "<Query><Where><IsNotNull><FieldRef Name='Phase' /></IsNotNull></Where>                           <GroupBy Collapse='True'><FieldRef Name='Phase'></FieldRef></GroupBy>                                   </Query>";
    CAMLViewFields: ""<ViewFields><FieldRef Name='ID' /><FieldRef Name='Phase' /><FieldRef                                 Name='DueDate' />",
    completefunc: function (xData, Status)
{      
if (Status == "success")
{                                    
$(xData.responseXML).SPFilterNode("z:row").each(function()
{
var Phase = $(this).attr("ows_Phase");
var DueDate = $(this).attr("ows_DueDate");
});
}
}
});



Delete All Items from List

function DeleteAllItemsFromList()
  {
    $.SPServices.SPUpdateMultipleListItems({
    listName: "Listname",
    CAMLQuery: "<Query><Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where></Query>",
    batchCmd: "Delete"});
  }



Add Item to List

$.SPServices({
   operation: 'UpdateListItems',
   listName: "Listname",
   updates: '<Batch OnError="Continue">' +
             '<Method ID="1" Cmd="Update">' +
  '<Field Name="ID">'+ ItemID +'</Field>' +
             '<Field Name="Title">'+ title +'</Field>' +
             '</Method>' +
             '</Batch>',
   completefunc: function(xData, Status)
        {}
});