CRUD operation on ASP.NET Web API from .NET client

In this post we will learn to work with CRUD operation on ASP.NET Web API. We will learn

  • To create CRUD operation on ASP.NET Web API
  • Using Entity model to create model
  • Creating repository to perform CRUD operation
  • Consuming service in .NET Console Client

I can draw architecture of this blog post as following,

image

Let us follow step by step approach to perform CRUD operation using ASP.NET Web API service.

Create ASP.Net Web API

In this part of blog, we will learn to create ASP.NET Web API. To create launch Visual Studio and create a project by choosing ASP.NET MVC 4 Web Application template.

image

Next you select Web API from the existing project template. Make sure to select Razor as View engine in drop down.

clip_image002

Next we need to add model. We will use ADO.Net Entity model to create model out of database. To add model, right click on the Models folder and select Add New Item. Next from Data tab select ADO.NET Entity Data Model

clip_image004

Next select Generate from database option and click on Next.

clip_image005

In next dialog box, you need to configure Connection Properties. Here select Northwind database after giving server name.

clip_image006

After configuring connection, you will get Entity Data Model Wizard populated with connection string as below. Click on next to proceed further

clip_image007

Here you need to select tables, views etc. For purpose of this post, let us select three tables, Customers, Employees and Products. After selecting tables click on Finish to create model of database in project.

clip_image008

We are going to work with Product table. To perform CRUD operation on this, let us go ahead and created a Repository. To create this right click on model and add an Interface from Code tab. I am giving name as IProductRepository.

clip_image010

In this interface we will define all the operations needed to be performed on Product table. Interface is defined as below,


using System.Collections.Generic;

namespace NorthwindService.Models
{
    public  interface IProductRepository
    {
        IEnumerable<Product> GetProducts();
        bool AddProduct(Product p);
        bool UpdateProduct(Product p);
        bool DeleteProduct(int ProductID);
    }
}

Next we need to implement CRUD operation. To do that add a class and implement IProductRepository in that class. Let us implement all four operations one by one.

Note : All these operations would be defined under ProductRepository class.

We can fetch all the Products as below by writing simple LINQ

public IEnumerable<Product> GetProducts()
        {
            NorthwindEntities entities = new NorthwindEntities();
            var products = from r in entities.Products select r;
            return products.ToList();
        }


A product can be added as below,


 public bool AddProduct(Product p)
        {
            try
            {
                NorthwindEntities entities = new NorthwindEntities();
                entities.Products.Add(p);
                entities.SaveChanges();
                return true; 
            }
            catch (Exception ex)
            {
                return false; 
            }

        }


Product can be updated as below,


public bool UpdateProduct(Product p)
        {
            try
            {
                NorthwindEntities entities = new NorthwindEntities();
                Product proudctToUpdate = (from r in entities.Products where 
                                               r.ProductID == p.ProductID select r).FirstOrDefault();

                proudctToUpdate.ProductName = p.ProductName;
                proudctToUpdate.UnitPrice = p.UnitPrice;
                entities.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


Product can be deleted as below,


public bool DeleteProduct(int productID)
        {
            try
            {
                NorthwindEntities entities = new NorthwindEntities();
                Product proudctToDelete = (from r in entities.Products
                                           where
                                               r.ProductID == productID
                                           select r).FirstOrDefault();
                entities.Products.Remove(proudctToDelete);
                entities.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

After creating repository for CRUD operation, let us go ahead and create Controller. To create Controller, right click on the Controller folder and select Add new Controller. You need to rename Controller name to ProductsController.

image

You will get controller class created as following. Make sure that you have changed Controller to ApiController

clip_image002[6]

Now we can create CRUD operation as below,

Products can be fetched as below,

static readonly IProductRepository repository = new ProductRepository();

        public IEnumerable<Product> GetProducts()
        {
            return repository.GetProducts();
        }

A new record can be created as following. We are passing Product as a resource to create here. While creating new record make sure

  • Action name is PostProduct. Essentially Action name should be started with Post to perform insert operation
  • Pass Product as input parameter
  • Return HttpResponse

We are calling AddProduct method of Repository class. Repository class is returning true on successful insertion of record. We are checking returned value and constructing returned HttpResponse.


public HttpResponseMessage PostProduct(Product p)
        {
            bool result = repository.AddProduct(p);
            HttpResponseMessage response;
            if(result)
            {
            response  = Request.CreateResponse(System.Net.HttpStatusCode.Created);
            }
            else
            {
                response = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);
            
            }
            return response ; 
        }

Modification of resource or Put operation can be performed as below. It is exactly same as Put operation with two differences

  • Action or function name starts from Put
  • UpdateProduct function of Repository class is being called.
  public HttpResponseMessage PutProduct(Product p)
        {
            bool result = repository.UpdateProduct(p);
            HttpResponseMessage response;
           if(result)
            {
                response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
            }
            else
            {
                 response  = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);
            
            }
            return response ; 

        }

Delete of resource or Put operation can be performed as below. It is exactly same as other operation with two differences

  • Action or function name starts from Delete
  • It takes Id as input parameter to delete record with particular id
  • DeleteProduct function of Repository class is being called.

 public HttpResponseMessage DeleteProduct(int id)
        {
            bool result = repository.DeleteProduct(id);
            HttpResponseMessage response;
            if(result)
            {
            response  = Request.CreateResponse(System.Net.HttpStatusCode.OK);
            }
            else
            {
                response = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);
            
            }
            return response ; 

        }

This is what all you need to do to create ASP.NET Web API with CRUD operation on Northwind database.

Creating .NET or Console Client

We are going to create .NET Console client to consumer service we created earlier. To create Console Application project, you need to select Console Application project template from Windows tab. After creating project, right click on project and select manage Nuget packages. Here search for Microsoft.AspNet.WebApi.Client library. Install this NuGet package in client project.

image

After installing package, add following namespaces in project,


using System.Net.Http;
using System.Net.Http.Headers;

Before we perform any operation, first initialize following in the project. Below

  • Initializing HttpClient
  • Setting base address
  • Setting Http Request Header as JSON
 HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:37780/api/");
          
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));



After initializing HttpClient and base address, we need to create client side representation of Product class. Let us create Product class at client side. Make sure that definition of class is same as the server side. Client side Product class is as following,


public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public Nullable<int> SupplierID { get; set; }
        public Nullable<int> CategoryID { get; set; }
        public string QuantityPerUnit { get; set; }
        public Nullable<decimal> UnitPrice { get; set; }
        public Nullable<short> UnitsInStock { get; set; }
        public Nullable<short> UnitsOnOrder { get; set; }
        public Nullable<short> ReorderLevel { get; set; }
        public bool Discontinued { get; set; }
    }



Read Products from service

You can fetch all the Products as below.



 HttpResponseMessage response = client.GetAsync("products").Result;
            if (response.IsSuccessStatusCode)
            {
                var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;
                foreach (var p in products)
                {
                    Console.WriteLine("{0}\t{1};\t{2}", p.ProductName, p.UnitPrice, p.QuantityPerUnit);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }


We are fetching records performing following steps in above code.

  • Records being fetched using GetAsync method of HttpClient class.
  • We are passing name of entity in GetAsync
  • After fetching records reading JSON data using Conent.ReadAsAsync() method of HttpResponseMessage
  • If response is erroneous then we are displaying error code as output.

Creating a Record

To create record or insert a record (in this case Product), we need to perform following steps ,

  • Create instance of product to be inserted
  • Perform PostAsJsonAsync operation on HttpClient and pass entity name and object to be inserted as parameter
  • On successful insertion you will get successful status code else error code.

Following code snippet will create a Product in database perform Put operation using ASP.NET Web API.


 Product p = new Product
            {
                ProductName = "DJ'S Pen",
                QuantityPerUnit = "20",
                Discontinued = true

            };
            HttpResponseMessage response = client.PostAsJsonAsync("products", p).Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }


On successful creation of record you will get response as below,

clip_image001

Updating Record

Updating record is exactly same as creating record. Only you need to use PutAsJsonAsync() method. You can update a record as below,

Product p = new Product
            {
                ProductID = 90,
                ProductName = "DJ'S Bat",
                QuantityPerUnit = "20",
                Discontinued = true

            };
            HttpResponseMessage response = client.PutAsJsonAsync("products", p).Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

On successful update you should get success message as below,

clip_image001[6]

Deleting Record

You can delete a resource using DeleteAsync function. You need to pass URI of the resource to be deleted.


HttpResponseMessage response = client.DeleteAsync("Products/90").Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

Here 90 is ProductId we want to delete. On successful deletion you will get success message as below,

clip_image001[8]

Conclusion

In this blog post we learn following items,

  1. Using ADO.NET Entity Model as model in Web API
  2. Creating CRUD operation on ASP.NET Web API
  3. Consuming service in .NET client

I hope you find this post useful. Thanks for reading.

What is JSON?

For some of you this question might be the easiest to answer. But for many developers concept of JSON is not well understood. In my seminars when I use JSON data for demo, I find many developers do not have understanding of JSON. In this post I am trying to address this problem.

In simple words, “JSON is a data interchange format. Due to its lightweight characteristics it is being highly used to exchange data between different platforms and applications”

image

A simple JSON data representing Students can be like following,

image

You can see that JSON object follows key-value pair mechanism

  • Key should be always a string
  • Value may be a string , number , Boolean or an object

image

You can represent collection in JSON as well. That can be represented as array of JSON objects.

image

Information about many Students can be displayed in JSON format as following,

image

You can have JSON object as value of another JSON object as well.

image

Now let us see that how can we work with JSON in JavaScript. Let us say we have a HTML page as given in the following snippet,


<body>

<h2>Reading Student information from JSON data</h2>
 Name : <span id="namespan"></span> <br />
 Marks : <span id ="marksspan"></span><br />
 Addreess : <span id="addresssapn"></span> <br />

</body>

In JavaScript we have JSON data and we need to bind values of JSON in to the HTML elements. We can do that very simply as given in following snippet,


<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.js"></script>
 <script type="text/javascript" >
 $(document).ready(function () {

var Student = {
 "name": "dj",
 "marks": 89,
 "address":
 {
 "city": "Pune",
 "country": "India"
 }
 };
 document.getElementById('namespan').innerHTML = Student.name;
 document.getElementById('marksspan').innerHTML = Student.marks;
 document.getElementById("addresssapn").innerHTML = Student.address.city;

});

 </script>
</head>

When you browse HTML you will find HTML elements values are displaying JSON data.

image

I hope now you have some understanding of JSON. Thanks for reading this post.

ASP.Net Web API Service in Windows Phone: Part 4 of Many

Creating First HTTP Service using ASP.NET Web API: Part1 of Many

Consuming ASP.NET Web API Service using HttpClient: Part2 of Many

How to Self-Host ASP.Net Web API: Part 3 of Many

In this post we will consume ASP.Net Web API HTTP Service in Windows Phone Application. If you do not specify header information in HTTP request then by default ASP.Net Web API service returns JSON data. So essentially there are three steps involved in consuming HTTP Service from ASP.Net Web API in Windows Phone Application.

  1. Make a HTTP Request
  2. Read data from HTTP Response
  3. Parse returned JSON data and bind data to data bound control

In this post we are going to consume service created in this POST

I have created a Windows Phone Application by choosing target framework 7.1. We are going to display Bloggers Data returned from ASP.Net Web API service in a ListView. Essentially we are going to consume a JSON Data from a HTTP Service. For that add below references in the project.

image

We are going to de-serialize JSON data using DataContractJsonSerializer class. We need to create a class at client side representing Bloggers entity from the service. Let us create a class called BloggersClient. We will de-serialize JSON data returning from the HTTP service in this object of this class.


namespace WindowsPhoneClient
{
public class BloggersClient
{
public string Id { get; set; }
public string Name { get; set; }
public string AreaOfIntrest { get; set; }

}
}

Once the client class is in placed add following references,

image

We are going to download JSON data from ASP.Net Web API service using WebClient class. Make sure that you are passing URL of your HTTP Service.

image

In the completed event, we will parse returned JSON using DataContractJsonSerializer class. In following code,

  • Creating MemoryStream form returned result
  • Creating object to de-serialize the returned JSON data
  • Reading de-serialized data object in List of BloggersClient
  • Setting List of BloggerClient as ItemSource of ListBox. On the XAML we have put a ListBox with name lstBloggers.

image

Code behind to load data from ASP.Net Web API HTTP Service on page load of the application and s display in ListBox is as following


using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace WindowsPhoneClient
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://localhost:39192/api/Bloggers"));
}

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream s = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<BloggersClient>));
List<BloggersClient> result = (List<BloggersClient>) ser.ReadObject(s);
lstBloggers.ItemsSource = result;
}
}
}

On the XAML, we have put ListBox control do bind data from HTTP Service in the control.

If you are not aware of Data Binding in ListBox then watch a quick Video here


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="ASP.Net Web API" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="lstBloggers">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}" />
<TextBlock Text="{Binding AreaOfIntrest}" Style="{StaticResource PhoneTextAccentStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>

Now press F5 to run the application. You should able to get Bloggers detail from ASP.Net Web API service in Windows Phone Application.

image

I hope you find this post useful. Thanks for reading.

Netflix Movie Explorer a Metro Application: Creating Step by Step

Download source code of this article from here

In this article we will follow step by step approach to create Netflix Movie Explorer Metro Application. We will use HTML and WinJS to create this application. See the video to understand expected behavior of the application.

Some of the features of application are as following

  • Browse movies from Netflix
  • Rate the Movies
  • Browse movies in Semantic views
  • Share the Rating of a particular movie with social media or via mail

To get it started, launch Visual Studio and create a new project by choosing Blank App Project template from Windows Metro Style tab. You need VS12 to create this application.

image

After creating project in default.html change “content goes here “with following

clip_image001

After that follow the steps as below,

Step 1: Create Data Source

Very first we need to create data source by reading JSON data from OData feed of Netflix movie database. That can be done using WinJS.xhr function

image

In above code snippet, we are performing following tasks

  • Making a call to Netflix OData using WinJS .xhr function
  • As input parameter to xhr function, we are passing exact url of OData Endpoint.
  • We are applying projection and providing JSON format information in URL itself.
  • Once JSON data is fetched form Netflix server data is being parsed and pushed as individual items in the WinJS list.

After fetching, data is being parsed using JSON Parser and individual items are pushed to movieArray. movieArray is defined as following

image

Step 2: Create ListView

After creating data source we need put WinJS ListView control on the page.

image

A HTML div can be converted to WinJS ListView by setting data-win-control attribute to WinJS.UI.ListView. Other options can be set like layout of the ListView. In this case we have set it to GridLayout, so data will be displayed horizontally. ListView needs data source to display data. Data source can be set either in HTML or in code behind. Let us set data source of movieListView to the movieArray.

image

Make sure that you are setting data source of ListView after the WinJS.xhr function call. At this point of time if you go ahead and run the application, you should be getting following output.

image

Step 3: Create ListView Template

In above output, data is in raw form. To make data more immersive and to show the way we want, we need to create template out of data. After creating template, it needs to be set as attribute of ListView. Template can be created as following

image

Template can be created by setting data-win-control attribute of HTML div as WinJS.Binding.Template . Inside div element

  • Binding image to Picture property of WinJS List or Array
  • Binding inner text of h4 element to Title property of WinJS List or Array

Once Template is created, it needs to be attached to the ListView. After attaching Template, ListView will be as following

image

No go ahead and run the application, you should be getting following shape of the application

image

Before we move ahead, let us put some CSS on ListView to make it more immersive

image

After applying styles on List View, your application should be in following shape.

image

Step 4: Grouping of DataSource

Next we want to group the movies as per first character of their title. For that create group functions as following.

image

After creating grouped functions, we need to create grouped item list and set it as itemDataSource of List View. Modify setting of ListView data source as following

image

Let us go ahead and run the application. At this point shape of the application should be as following

image

Step 5: Creating Header Template

Above we can see the header data is in raw form. So to make header information more immersive, you need to create template for header and then attach that to ListView

A header template can be created in same way as of item template. Header template is created as following

image

After creating Header Template, we need to attach this to ListView. So ListView will be modified as following

image

Let us go ahead and run the application. At this point shape of the application should be as following

image

Step 6: Adding Semantic Zoom

Next we need to add sematic zoom to the ListView. For that very first let us create a Semantic Zoom Template. We want to display movies with first letter of title in semantic zoom view.

image

After creating Semantic Zoom View template, we need to add a SemanticZoom WinJS control. Inside the Semantic Zoom control we need to put ListView (created in previous steps) and a Semantic Zoom View. We can put that as following.

image

After adding Semantic Zoom view we need to set data source of it. This can be set as following.

image

Last work we need to do in Semantiz Zoom is to apply styles.

image

Let us go ahead and run the application. At this point shape of the application should be as following

image

image

Step 7: Adding Output DIV

Now we need to add code to add output div. When user will select a particular movie detail of that movie will be displayed in the output div for rating.

image

And in code behind on the touch of a particular ListView item, we need to display that information in output div. For that add the following code in code behind

image

In above code snippet

  • Iteminvoked event is attached to the ListView
  • When item is invoked then itemPromise function is being called with parameter invokedItem
  • On the invokeditem data we can fetch attributes of ListView items
  • In last set the vales of HTML elements from selected items data.

Let us go ahead and run the application. At this point shape of the application should be as following

image

Step 8: Adding Rating control

To allow user for Rating, let us go ahead and add a WinJS Rating control. Rating control can be added as following

image

We can create a Rating control by setting data-win-control attribute of a div as WinJS.UI.Rating. Other data options like maxRating and averageRating can be set in data-win-options attribute.

After adding Rating control, we need to write code to allow users to perform rating.

image

Let us go ahead and run the application. At this point shape of the application should be as following

image

Step 9: Adding Code to Share Contract

We want our user should able to share the rating of movie on other applications like Mail, Twitter, Facebook. For that we will have to use ShareContract.

image

In above code we are getting the request and setting the title and description in data property. After that creating text to share and setting it in the data request. Above is the code to simple text sharing via ShareContract feature of Windows 8. Once we have share function is ready, we need to get the current view of application using DataTransferManager.getForCurrentView () and attach and event handler datarequested on same. When datarequested event will be fired ShowandShareContract function (created above) will be called and user will able to share using Share Charm.

image

Put above code just before ProcessAll() function and do not forget to declare following variable globally

image

Let us go ahead and run the application. At this point shape of the application should be as following. This is our final application.

image

In this application user can browse the movies, rate a particular movie and then share the rating with the friends on social media or mail.

Conclusion

In this post we learnt to create a Metro Application from scratch. Even though you can download source code of this article from here , I am sharing the codes below . Feel free to use them as you required.

default.html


<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <title>testdemo</title>

<!-- WinJS references -->
 <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
 <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
 <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>

<!-- testdemo references -->
 <link href="/css/default.css" rel="stylesheet" />
 <script src="/js/default.js"></script>
</head>
<body>
 <h1>Netflix Movie Application</h1>
 <div id="moviesTemplate"
 data-win-control="WinJS.Binding.Template">
 <div style="width: 150px; height: 130px;">
 <img src="#" style="width: 100px; height: 100px;"
 data-win-bind="alt: title; src: picture" />
 <div>
 <h4 data-win-bind="innerText:title"></h4>
 </div>
 </div>
 </div>

<div id="headerTemplate"
 data-win-control="WinJS.Binding.Template"
 style="display: none">
 <div class="simpleHeaderItem">
 <h1 data-win-bind="innerText: title1"></h1>
 </div>
 </div>

<div id="semanticZoomTemplate" data-win-control="WinJS.Binding.Template"
 style="display: none">
 <div class="semanticZoomItem">
 <h1 class="semanticZoomItem-Text"
 data-win-bind="innerText: title1">
 </h1>
 </div>
 </div>
 <div id="semanticZoomDiv" data-win-control="WinJS.UI.SemanticZoom">
 <div id="movieListView"
 data-win-control="WinJS.UI.ListView"
 data-win-options="{itemTemplate:moviesTemplate,
 groupHeaderTemplate: headerTemplate
 ,layout: {type: WinJS.UI.GridLayout} }">
 </div>
 <div id="zoomedOutListView"
 data-win-control="WinJS.UI.ListView"
 data-win-options="{itemTemplate: semanticZoomTemplate,
 selectionMode: 'none',
 tapBehavior: 'invoke',
 swipeBehavior: 'none' }">

</div>
 </div>
 <table>
 <tr>
 <td>
 <img id="selectedPlayerImg"
 style="width:250px;height:250px;"/>
 </td>
 <td>
 <h3>You are rating movie</h3><br />
 <span id="selectedPlayer"></span> <br />
 <span id="ratingPlayer"></span> <br />

<div id="ratingcontrol"
 data-win-control="WinJS.UI.Rating"
 data-win-options="{maxRating:10,avrageRating:4}" />

 </td>
 </tr>
</table>

&nbsp;

</body>
</html>

default.js


// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
 "use strict";

 var app = WinJS.Application;
 var activation = Windows.ApplicationModel.Activation;
 WinJS.strictProcessing();
 var movieArray = new WinJS.Binding.List();
 var dataTransferManager;
 var movieName;
 var selectRating;
 app.onactivated = function (args) {

 if (args.detail.kind === activation.ActivationKind.launch) {
 if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
 // TODO: This application has been newly launched. Initialize
 // your application here.
 } else {
 // TODO: This application has been reactivated from suspension.
 // Restore application state here.
 }

 dataTransferManager = Windows.ApplicationModel.
 DataTransfer.
 DataTransferManager.getForCurrentView();
 dataTransferManager.addEventListener("datarequested", ShowandShareContract);
 args.setPromise(WinJS.UI.processAll());

 WinJS.xhr({
 url: "http://odata.netflix.com/Catalog/Titles" +
 "?$format=json&$select=ShortName,BoxArt&$top=300"
 }).then(function (xhr) {
 var movies = JSON.parse(xhr.response).d;
 movies.forEach(function (i) {
 movieArray.push({
 title: i.ShortName,
 picture: i.BoxArt.MediumUrl
 });
 });
 });

var lstMovies = document.getElementById("movieListView").winControl;
 var groupedItemsList = movieArray.createGrouped(getGroupKey, getGroupData, compareGroups);
 lstMovies.itemDataSource = groupedItemsList.dataSource;
 lstMovies.groupDataSource = groupedItemsList.groups.dataSource;
 var lstMoviesZoom = document.getElementById("zoomedOutListView").winControl;
 lstMoviesZoom.itemDataSource = groupedItemsList.groups.dataSource;
 lstMovies.addEventListener("iteminvoked", function (eventObject) {
 eventObject.detail.itemPromise.then(function (invokedItem) {
 var selecteplayer = document.getElementById('selectedPlayer');
 selecteplayer.innerHTML = "<h2>" + invokedItem.data.title + "</h2>";
 movieName = invokedItem.data.title;

var selecteplayerImg = document.getElementById('selectedPlayerImg');
 selecteplayerImg.src = invokedItem.data.picture;

var ratingcontrolc = document.getElementById("ratingcontrol").winControl;
 ratingcontrolc.addEventListener("change", function () {
 selectRating = ratingcontrolc.userRating;
 document.getElementById('ratingPlayer').innerHTML = "<h3> as "
 + selectRating +
 " on scale of 10 <h3>";

});

});
 }, false);

&nbsp;
 }
 };

function compareGroups(left, right) {
 return left.charCodeAt(0) - right.charCodeAt(0);
 }

function getGroupKey(dataItem) {
 return dataItem.title.toUpperCase().charAt(0);
 }

function getGroupData(dataItem) {
 return {
 title1: dataItem.title.toUpperCase().charAt(0)
 };
 }

function ShowandShareContract(e) {

var request = e.request;
 request.data.properties.title = "Netflix Movie Explorer Application";
 request.data.properties.description = "Sharing from Netflix Movie Explorer Application";
 var textToShare = movieName + " has been rated " + selectRating + " out of 10 ";
 request.data.setText(textToShare);

}

app.oncheckpoint = function (args) {

 };

app.start();
})();

default.css

body {
}

@media screen and (-ms-view-state: fullscreen-landscape) {
}

@media screen and (-ms-view-state: filled) {
}

@media screen and (-ms-view-state: snapped) {
}

@media screen and (-ms-view-state: fullscreen-portrait) {
}
.win-listview
 {
 height: 500px;
 width: auto;
 border: 1px solid gray;
 }

.win-listview .win-container {
 margin: 10px;
 }
 .win-listview .win-container:hover {
 background-color: red;
 border-color: red;
 }

.semanticZoomItem
{
 width: 130px;
 height: 130px;
 background-color: rgba(38, 160, 218, 1.0);
}

.semanticZoomItem .semanticZoomItem-Text
 {
 padding: 10px;
 line-height: 150px;
 white-space: nowrap;
 color: white;
 }

&nbsp;

&nbsp;

I hope you find this post useful. Thanks for reading

Working with OData and WinJS ListView in Metro Application

In this post we will see how to consume Netflix OData feed in HTML based Metro Application. Movies information will be displayed as following. At the end of this post, we should have output as below,

image

Netflix exposed all movies information as OData and that is publicly available to use. Netflix OData feed of movies are available at following location

http://odata.netflix.com/Catalog/

Essentially we will pull movies information from Netflix and bind it to ListView Control of WinJS. We will start with creating a blank application.

image

In the code behind (default.js) define a variable of type WinJS List.

image

Now we need to fetch the movies detail from Netflix. For this we will use xhr function of WinJS. As the parameter of function, we will have to provide URL of the OData feed.

image

In above code snippet, we are performing following tasks

  • Making a call to Netflix OData using WinJS .xhr function
  • As input parameter to xhr function, we are passing exact url of OData endpoint.
  • We are applying projection and providing JSON format information in URL itself.
  • Once JSON data is fetched form Netflix server data is being parsed and pushed as individual items in the WinJS list.

As of now we do have data with us. Now let us go ahead and create a ListView control. You can create WinJS ListView as following. Put below code on the default.html

clip_image002

In above code we are simply creating a WinJS ListView and setting up some basic attributes like layout and itemTemplate. Now we need to create Item Template. Template is used to format data and controls how data will be displayed. Template can be created as following

image

In above code, we are binding data from the data source to different HTML element controls. At last in code behind we need to set the data source of ListView

image

Before you go ahead and run the application just put some CSS to make ListView more immersive. Put below CSS in default.css

image

Now go ahead and run the application. You should be getting the expected output as following

image

Let us consolidate all the codes from discussion.

Default.html

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <title>testdemo</title>

<!-- WinJS references -->
 <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
 <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
 <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>

<!-- testdemo references -->
 <link href="/css/default.css" rel="stylesheet" />
 <script src="/js/default.js"></script>
</head>
<body>
 <h1>Netflix Movie Application</h1>
 <div id="moviesTemplate"
 data-win-control="WinJS.Binding.Template">
 <div style="width: 150px; height: 130px;">
 <img src="#" style="width: 100px; height: 100px;"
 data-win-bind="alt: title; src: picture" />
 <div>
 <h4 data-win-bind="innerText:title"></h4>
 </div>
 </div>
 </div>

<div id="movieListView"
 data-win-control="WinJS.UI.ListView"
 data-win-options="{itemTemplate : moviesTemplate,
 layout: {type: WinJS.UI.GridLayout} }">
 </div>

</body>
</html>

Code behind will have following codes

Default.js


// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
 "use strict";

 var app = WinJS.Application;
 var activation = Windows.ApplicationModel.Activation;
 WinJS.strictProcessing();
 var movieArray = new WinJS.Binding.List();
 app.onactivated = function (args) {

 if (args.detail.kind === activation.ActivationKind.launch) {
 if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
 // TODO: This application has been newly launched. Initialize
 // your application here.
 } else {
 // TODO: This application has been reactivated from suspension.
 // Restore application state here.
 }
 args.setPromise(WinJS.UI.processAll());

 WinJS.xhr({
 url: "http://odata.netflix.com/Catalog/Titles" +
 "?$format=json&$select=ShortName,BoxArt&$top=300"
 }).then(function (xhr) {
 var movies = JSON.parse(xhr.response).d;
 movies.forEach(function (i) {
 movieArray.push({
 title: i.ShortName,
 picture: i.BoxArt.MediumUrl
 });
 });
 });
 var lstMovies = document.getElementById("movieListView").winControl;
 lstMovies.itemDataSource = movieArray.dataSource;

 }
 };

app.oncheckpoint = function (args) {

 };

app.start();
})();

And CSS will be as following

default.css


body {
}

@media screen and (-ms-view-state: fullscreen-landscape) {
}

@media screen and (-ms-view-state: filled) {
}

@media screen and (-ms-view-state: snapped) {
}

@media screen and (-ms-view-state: fullscreen-portrait) {
}
.win-listview
 {
 height: 100%;
 width: auto;

 }
 .win-listview .win-container {
 margin: 10px;
 }
 .win-listview .win-container:hover {
 background-color: red;
 border-color: red;
 }
 .semanticZoomItem
{
 width: 130px;
 height: 130px;
 background-color: rgba(38, 160, 218, 1.0);
}

.semanticZoomItem .semanticZoomItem-Text
 {
 padding: 10px;
 line-height: 150px;
 white-space: nowrap;
 color: white;
 }

In this way we can work with OData and winJS ListView. I hope you find this post useful. Thanks for reading.

How to create WCF Data Service with $JSONP format

In this post we will create WCF Data Service takes $JSONP in query and returns JSON data as response. For example if we want to fetch data as JSON we can fetch as following,

http://localhost:5157/WcfDataService1.svc/People?$format=json

To start with, Let us create WCF Data Service on School Database. Open Visual Studio 2010 as administrator and create a Web Application. We will be hosting WCF Data Service in web application.

image

Create DataModel

We will create DataModel using ADO.Net Entity framework. To add a DataModel we need to add ADO.Net Entity Model from Data Tab.

image

We want to create DataModel from database, so we will be choosing Generate from database option.

image

After this we need to choose Server name and database name. You can select appropriate authentication mechanism, in my case I am choosing Windows Authentication.

image

In last step, we need to select tables and views we want to keep as part of DataModel. In this case I am selecting all the tables.

image

Create WCF Data Service

To create WCF Data Service add new item selecting WCF Data Service project template from Web Tab

image

Modify WcfDataService.svc.cs as following. We need to provide DataModel name. In this case DataModel is SchoolEntites, we created in previous step.

image

By this step we have created WCF Data Service on SchoolEntities DataModel. Now press F5 to host created WCF Data Service in Cassini server and query in the browser.

image

And we can query a particular set of entity as following,

image

Enabling JSONP and URL Control Format

Read More Detail Here MSDN

If we want to fetch response in JSON format as following

http://localhost:5157/WcfDataService1.svc/People?$format=json

We will be getting following exception,

image

JSONP is used to fetch data from client side even though request need to be cross domain. To support $JSONP, we need to intercept the message before it gets dispatched. At intercept

  • Read the request URL and if $JSONP is there remove it from the querystring. Because reading $JSONP in connection string WCF Data Service runtime will throw exception as shown above.
  • And change Accept header to application/json

To enable this you need to add following file JSONPSupportBehavior.cs . Download sample project from and file from MSDN Code Gallery

image

Extract downloaded ZIP file and select JSONSupportBehavior.cs . Right click on your project and add existing item. Choose file JSONSupportBehavior.cs and add to the project.

image

Then modify WcfDataService.svc.cs as following,

image

We need to put JSONPSupportBehavior service attribute. Now go ahead and press F5 to run and fetch people in JSON format as following ,

http://localhost:5157/WcfDataService1.svc/People?$format=json

image

In this way we can enable $JSONP format on WCF Data Service. I hope this post is useful. Thanks for reading

 

How to consume WCF REST Service with JSON in Windows Phone 7

In this post I will show you the way to consume JSON WCF REST Service in Windows Phone 7. This post is divided into four parts.

  1. Creating simple WCF REST Service for ADD
  2. Consuming JSON REST Service in Windows Phone 7 application.
  3. Creating complex WCF REST Service with custom classes and types.
  4. Consuming complex JSON REST Service in Windows Phone 7 application.

Creating simple Add Service

To start with let us create a WCF REST Service returning JSON as below. There is one operation contact named Add in the service and that is taking two strings as input parameters and returning integer.


[ServiceContract]
public interface IService2
{

[OperationContract]
[WebGet(UriTemplate="/Add/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int Add(string  Number1, string Number2);

}

Service is implemented as below,


using System;

namespace MultipleBindingWCF
{

public class Service1 : IService2
{

public int Add(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 + num2;
}

}
}

Next in this section we need to configure service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the below changes.


<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<endpoint name ="RESTEndPoint"
contract ="MultipleBindingWCF.IService2"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

After configuring, Service ready for hosting. You are free to host it either on Azure, IIS, or Cassini. For local ASP.Net Server hosting press F5. Do a testing of service in browser and if you are getting expected output, you are good to consume it in the Windows Phone 7 application.

Consuming Service in Windows Phone 7

To consume REST Service in Windows Phone 7 and then parse JSON, you need to add below references in Windows Phone 7 project.

 

 

 

As the design of the page I have put two textbox and one button. User will input numbers to be added in the textbox and on click event of button result would get displayed in message box. Essentially on click event of the button we will make a call to the service. Design of the page is as below,


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="calling JSON REST" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="JSON REST" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox x:Name="txtNumber1" Height="100" Margin="-6,158,6,349" />
<TextBox x:Name="txtNumber2" Height="100" Margin="-6,28,6,479" />
<Button x:Name="btnAdd" Height="100" Content="Add" Click="btnAdd_Click"/>
</Grid>
</Grid>

On click event of the button we need to make a call to the service as below,

clip_image002

And ServiceURi is constructed as below,

clip_image004

There is nothing much fancy about above service call. We are just downloading JSON as string using WebClient. However parsing of JSON is main focus of this post. To parse we need to write below code in completed event.

clip_image006

In above code

  • Converting downloaded string as Stream
  • Creating instance of DataContractJsonSerializer. In that we are passing type as string since returned type of service is string.
  • Reading stream into instance of DataContractJsonSerializer
  • Displaying the result.

Putting all code together you should have below code to make a call and parse JSON in windows phone 7


using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace ConsumingJSON
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void btnAdd_Click(object sender, RoutedEventArgs e)
{

string Number1 = txtNumber1.Text;
string Number2 = txtNumber2.Text;
string ServiceUri = "http://localhost:30576/Service1.svc/Rest/add/"
+ Number1 + "/"
+ Number2;
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(ServiceUri));

}

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
string result = obj.ReadObject(stream).ToString();
MessageBox.Show(result);
}
}
}

Creating complex Service with custom classes and types

Go back to service and add a custom class as below,

[DataContract]
public class Student
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string RollNumber { get; set; }
[DataMember]
public string Grade { get; set; }
}

And add one more function to service. This operation contract will return List of Students.


[OperationContract]
[WebGet(UriTemplate = "/GetStudents", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
List<Student> GetStudents();

Next you need to implement service as below,


public List<Student> GetStudents()
{
List<Student> lstStudent = new List<Student>
{
new Student { Name = "John " ,RollNumber = "1" , Grade = "A"},
new Student { Name = "Dan " ,RollNumber = "2" , Grade = "Q"},
new Student { Name = "Pinal " ,RollNumber = "3" , Grade = "M"},
new Student { Name = "Mahesh " ,RollNumber = "4" , Grade = "Z"},
new Student { Name = "Julie" ,RollNumber = "5" , Grade = "L"},
};
return lstStudent;
}

Configuration will be the same as of simple REST Service returning JSON. Press F5 to host and test the service.

Consuming complex JSON REST Service in Windows Phone 7 application

At the Windows Phone 7 application, you need to create entity class. This class will be representing Student class of service. Add Student class to project as below,


public class Student
{
public string Name { get; set; }
public string RollNumber { get; set; }
public string Grade { get; set; }

}

Design page as below. I have put a button and on click event of the button service will get called and returned data would be bind to the listbox.


<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="110" />
</Grid.RowDefinitions>
<ListBox x:Name="lstStudents" Height="auto" Width="auto" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}"  />
<TextBlock Text="{Binding RollNumber}" Style="{StaticResource PhoneTextTitle3Style}" />
<TextBlock Text="{Binding Grade}" Style="{StaticResource PhoneTextAccentStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

<Button Grid.Row="1" x:Name="btnAdd" Height="100" Content="Add" Click="btnAdd_Click"/>
</Grid>

In the code behind on click event of the button we need to make call using WebClient again


private void btnAdd_Click(object sender, RoutedEventArgs e)
{
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://localhost:30576/Service1.svc/rest/getstudents"));

}

And need to parse the returned JSON as below. In parameter to create instance of DataContractJsonSrrializer we are passing List of Student.


void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Student>));
List<Student> result = obj.ReadObject(stream) as List<Student>;
lstStudents.ItemsSource = result;
}

On running you should be getting output as below.

image

In this way you can work with WCF REST with JSON Data and Windows Phone 7. I hope this post is is useful. Thanks for reading

REST service on JSON Message format

Objective

  1. How to create REST service for JSON request and response format.
  2. How to create SilverLight Client, which will consume a REST service on JSON data format.
  3. How to POST data in JSON format from SilverLight client.
     

Working explanation

Here, I am trying to insert data in static list and fetch it back at SilverLight client.
Step 1

Create new WCF Service Application

File -> New -> Project -> Web -> WCF Service Application

Step 2

Remove all the default code in service1.svc and IService1.cs. Paste the below code there in IService1.cs .

Note

  1. If you have changed the name of service interface then take care of that. If you have changed IService1 to ITest then update code in ITest.cs. if you have changed name of Service1.cs then update code in changed class.
  2. In this sample, I am adding object of Test class in a static list and fetching it back. If you want to perform pure Data base operation (CRUD). Just replace Insert code and get Code with your database operation code.
  3. Add reference of System.ServiceModel.Web to IService1.cs.
  4. Now what is Test class here? And where it should be declared and created. So just right click on service project and add a class. Give name of the class Test and paste below code over there.

Test.cs


 namespace SilverLightRestTesting
{
public class Test{
public int Marks { get; set; }

public String Name { get; set; }
}}

 IService1.cs

using System;

using System.Collections.Generic;using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.ServiceModel.Web; 

namespace SilverLightRestTesting

{

[ServiceContract]

public interface IService1{
[OperationContract] [WebGet(UriTemplate=“/Data”,BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]
List<Test> GetTest();

[OperationContract]
[WebInvoke(UriTemplate = “/Data”, BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void InsertTest(Test t);
}}

Service1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

 namespace SilverLightRestTesting
{
public class Service1 : IService1{
static List<Test> testList = newList<Test>();
public List<Test> GetTest()
{
return testList;
}
public void InsertTest(Test t)
{
testList.Add(t);
}
}}

 Step 3
Open Web.Config file and delete below highlighted code. In other words delete all default bindings and endpoints for existing service model. Delete existing <system.serviceModel>
Step 4
Create a SilverLight application.

  1. Create two buttons on SilverLight markup. One for getting the records from the service and other for Insert into the service. .
  2. Right click on SilverLight application and add the class Test. Because in REST services DataContract are not exposed to the client.

     Test.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 namespace SilverLightRestTesting
{
public class Test{
public int Marks { get; set; }

public String Name { get; set; }
}}

  1. Let us suppose button name is Insert for Insert into Static list of service. Write below code on click event of Insert button.
private void Insert_Click(object sender, RoutedEventArgs e){

Test t1 = new Test() { Name = “Civics”, Marks = 100 };
DataContractJsonSerializer jsondata = newDataContractJsonSerializer(typeof(Test));
MemoryStream mem = newMemoryStream();
jsondata.WriteObject(mem,t1);
string josnserdata = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient cnt = new WebClient();

cnt.UploadStringCompleted += new UploadStringCompletedEventHandler(cnt_UploadStringCompleted);
cnt.Headers[“Content-type”] = “application/json”;
cnt.Encoding = Encoding.UTF8;
cnt.UploadStringAsync(new
Uri(uri), “POST”, josnserdata);
}
void cnt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var x = e;
}

  1. To get all the records in form of JSON from REST service , let us suppose button name is Display. Then write below code on click event of Display button.

private void display_Click(object sender, RoutedEventArgs e)

WebClient cnt = new WebClient();

cnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cnt_DownloadStringCompleted);
cnt.DownloadStringAsync(new
Uri(uri));
}
void cnt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e){

string str = e.Result;

JsonArray json;

if (JsonArray.Parse(str) asJsonArray == null)

json = newJsonArray { JsonObject.Parse(str) asJsonObject };
else

json = JsonArray.Parse(str) asJsonArray;
var q = from t in json
select new Test{
Marks = (int)t[“Marks”],Name = (String)t[“Name”]};
List<Test> tr = q.ToList() as List<Test>;
}

{