Search This Blog

Friday, August 12, 2016

RESTful web service body format

Assume that you have some contract with XML request/response and some simple data contract:

[ServiceContract]
public interface IService
{
    ...
    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped)]
    Entity DoWork(Entity entity);
    ...
}

[DataContract]
public class Entity
{
    [DataMember]
    public string Name;

    [DataMember]
    public string Value;
}

Depending on the combination of BodyStyle, RequestFormat and ResponseFormat you will have different formats but in general:

JSON and WebMessageBodyStyle.Bare request and response will be:

Request:

{"Name":"name","Value":"value"}
Response:

{"Name":"ResultName:name","Value":"ResultValue:value"}
JSON and WebMessageBodyStyle.Wrapped request and response will be:

Request:

{"entity":{"Name":"name","Value":"value"}}

Response:

{"DoWorkResult":{"Name":"name","Value":"value"}}
Note: you can change default DoWorkResult name to you own:

[return: MessageParameter(Name = "MyResult")]
Entity DoWork(Entity entity);`
so from now this will be:

{"MyResult":{"Name":"name","Value":"value"}}
XML and WebMessageBodyStyle.Bare request and response will be:

Request:

<Entity xmlns="http://schemas.datacontract.org/2004/07/WcfService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   <Name>name</Name>
   <Value>value</Value>
</Entity>

Response:

<Entity xmlns="http://schemas.datacontract.org/2004/07/WcfService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   <Name>name</Name>
   <Value>value</Value>
</Entity>
XML and WebMessageBodyStyle.Wrapped request and response will be:

Request:

 <DoWork xmlns="http://tempuri.org/">
   <entity>
      <Name>name</Name>
      <Value>value</Value>
   </entity>
 </DoWork>

Response:

 <DoWorkResponse xmlns="http://tempuri.org/">
   <DoWorkResult xmlns:a="http://schemas.datacontract.org/2004/07/WcfService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <a:Name>name</a:Name>
      <a:Value>value</a:Value>
   </DoWorkResult>
 </DoWorkResponse>
Note: you can also change default DoWorkResult name with the return: MessageParameter

To answer to your question, which WebMessageBodyStyle you should use depends on your needs and there is no golden rule here. For interoperability, one or another format can be sometimes required. But keep in mind about one limitation of bare body style: as there is only one root in XML format and one object in JSON format, only one parameter can be passed to a method. In fact, if you changed a service contract to something like:

[OperationContract]
[WebInvoke(Method = "POST",
    ResponseFormat = WebMessageFormat.Json,
    RequestFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare)]
Entity DoWork(string id, Entity entity);
a service would throw a exception:

Operation '' of contract '' specifies multiple request body parameters to be serialized without any wrapper elements. At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped.

Sources : http://stackoverflow.com/questions/20206069/restful-web-service-body-format

How to find latitude and longitude values from google maps using c#

 public static DataTable GetGeoLocation(string Address)
 {
            DataTable dtCoordinates = new DataTable();
            string url = "http://maps.google.com/maps/api/geocode/xml?address=" + Address + "&sensor=false";
            WebRequest request = WebRequest.Create(url);
            using (WebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    DataSet dsResult = new DataSet();
                    dsResult.ReadXml(reader);

                    dtCoordinates.Columns.AddRange(new DataColumn[4]
                    { new DataColumn("Id", typeof(int)),
                    new DataColumn("Address", typeof(string)),
                    new DataColumn("Latitude",typeof(string)),
                    new DataColumn("Longitude",typeof(string)) });
                    foreach (DataRow row in dsResult.Tables["result"].Rows)
                    {
                        string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString();
                        DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0];
                        dtCoordinates.Rows.Add(row["result_id"], row["formatted_address"], location["lat"], location["lng"]);
                    }
                }
                return dtCoordinates;
            }
}

Thursday, July 21, 2016

Selecting first 10 records, then next 10, paging using Linq

var total = dtDetails.Rows.Count;
var pageSize = 10; // set your page size, which is number of records per page

var page = 1; // set current page number, must be >= 1

var skip = pageSize * (page-1);

var canPage = skip < total;

if (canPage) // do what you wish if you can page no further
   return;

DataTable dtFilteredData= dtDetails.AsEnumerable().Skip(skip).Take(pageSize).CopyToDataTable();

How to create C# variables dynamically?

In some cases we have scenario like have to create variables dynamically.To achieve this we have to use dictionary.I have shown some sample example with this post.

Sample variables
String strvar_1=null;
String strvar_2=null;
String strvar_3=null;

strvar_1="DynamicValue_1";
strvar_2="DynamicValue_2";
strvar_3="DynamicValue_3";

//below is the code to dynamically create above variable and assigning the values 

//Create dictionary to create variable names
//In this first string would be the variable name and second string would be the value for that variable we are assigning null initially
Dictionary<String, String> dynstr = new Dictionary<String, String>();
for(int i = 1; i < 4; i++) {
  dynstr .Add("strvar_" + i, null);
  }

//we are assigning value to those variables
  for(int i = 1; i < 4; i++) {
    dogs["strvar_" + i] = "DynamicValue_" + i;
  }

Saturday, July 2, 2016

Create Retrieve Update and Delete SharePoint List Item using REST API and JQuery

In this article, it is showed you how to  utilizing SharePoint REST API and JQuery to Create, Retrieve, Update and Delete SharePoint list item.

Pre-Requisite

Reference to latest jquery.min.js
For this example purposes, create custom List called “MyList” with default “Title” column.
Create

// occurs when a user clicks the create button

function CreateNew() {
    var listName = "MyList";
    var newItemTitle = "New Title Item";
    CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, newItemTitle, function () {
        alert("New Item has been created successfully.");
 }, function () {
     alert("Ooops, an error occured. Please try again.");
 });
}

CREATE Operation

// listName: The name of the list you want to get items from
// weburl: The url of the web that the list is in. 
// newItemTitle: New Item title.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function CreateListItemWithDetails(listName, webUrl, newItemTitle, success, failure) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": newItemTitle
    };

    $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_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);
        },
        error: function (data) {
            failure(data);
        }
    });
}

Get List Item Type metadata

function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

Retrieve Item

 READ SPECIFIC ITEM operation

// itemId: The id of the item to get
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. 
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function getListItemWithId(itemId, listName, siteurl, success, failure) {
    var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId;
    $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            if (data.d.results.length == 1) {
                success(data.d.results[0]);
            }
            else {
                failure("Multiple results obtained for the specified Id value");
            }
        },
        error: function (data) {
            failure(data);
        }
    });
}


Retrieve All Items

// occurs when a user clicks the read button

function Read() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;

    getListItems(listName, url, function (data) {
        var items = data.d.results;

        // Add all the new items
        for (var i = 0; i < items.length; i++) {
            alert(items[i].Title + ":" + items[i].Id);
        }
    }, function (data) {
        alert("Ooops, an error occured. Please try again");
    });
}

 READ operation

// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. 
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function getListItems(listName, siteurl, success, failure) {
    $.ajax({
        url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

Update

// occurs when a user clicks the update button

function Update() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "1"; // Update Item Id here
    var title = "New Updated Title";
    updateListItem(itemId, listName, url, title, function () {
        alert("Item updated, refreshing avilable items");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

Update Operation

/ listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. // title: The value of the title field for the new item
// itemId: the id of the item to update
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function updateListItem(itemId, listName, siteUrl, title, success, failure) {
    var itemType = GetItemTypeForListName(listName);

    var item = {
        "__metadata": { "type": itemType },
        "Title": title
    };

    getListItemWithId(itemId, listName, siteUrl, function (data) {
        $.ajax({
            url: data.__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.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    }, function (data) {
        failure(data);
    });
}


Delete

// occurs when a user clicks the delete button

function Delete() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "1"; // Update Item ID here
    deleteListItem(itemId, listName, url, function () {
        alert("Item deleted successfully");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

// Delete Operation
// itemId: the id of the item to delete
// listName: The name of the list you want to delete the item from
// siteurl: The url of the site that the list is in.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function deleteListItem(itemId, listName, siteUrl, success, failure) {
    getListItemWithId(itemId, listName, siteUrl, function (data) {
        $.ajax({
            url: data.__metadata.uri,
            type: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-Http-Method": "DELETE",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "If-Match": data.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    },
   function (data) {
       failure(data);
   });
}


Source url : https://tjendarta.wordpress.com/2014/02/20/create-retrieve-update-and-delete-sharepoint-list-item-using-rest-api-and-jquery/ 

Wednesday, June 22, 2016

How to add Items in sharepoint list using CSOM

public void AddNewItemToList(string Title,string Subject)
{
   using(ClientContext objCtx = new ClientContext("http://Sharepoint.com"))
   {
       List oList = ctx.Web.Lists.GetByTitle("TestList");
       ListItemCreationInformation objItemCreateInfo = new ListItemCreationInformation();
       ListItemnewItem = oList.AddItem(objItemCreateInfo);
       newItem["Title"] = Title;
       newItem["Subject"] = Subject;
       newItem.Update();
       context.ExecuteQuery();
    }
}

Wednesday, June 8, 2016