Join me for JavaScript Day on 31st Aug

When: 31st August 2013

Where: MCN Solution, Sector 63 Noida

Fee : Free

Topic: JavaScript

Yes this time it is JavaScript. Me with C-Sharpcorner Delhi Chapter bringing you JavaScript Day on 31st Aug at Sector 63 Noida. It would be a full day event focusing on JavaScript.

To attend register here for free

 

image

 

I will be talking more than 2.30 hrs. On various topics of JavaScript. I will start with getting started with JavaScript and then cover below topics,

  • Defining Functions
  • Working with Invocation patterns
  • Working with Function Arguments and Parameters
  • Object as argument
  • Working with Argument types
  • Function as values
  • Function as Namespace
  • Working with Higher Order Function
  • Call() , apply() and bind() methods

There are other two sessions on Arrays in JavaScript and Objects in JavaScript by Brij Mishra and Suchit Khanna respectively

Find full agenda here

I am excited to see you at the JavaScript Day. Do not forget to Register here

Function constructor in JavaScript

As you know that we create or define function in JavaScript using function keyword. So you can create a simple Add function in JavaScript as given in below,


 var add = function Add(a, b) {
                return a + b;
            }

The other way to create functions in JavaScript is using Function constructor. Function constructor creates and complies a JavaScript function at run time.


  var add = new Function
            (
                "a",
                "b",
                "return a+ b; "
            );

You can create a function using Function constructor as below,

  • Parameters are passed as string in Function constructor
  • Last parameter is always body of the function
  • Body of the function is also in string
  • Statements in body are separated with semicolon
  • If there is no input parameter then body of function would be first and only parameter in constructor
  • Any number of arguments can be passed in Function constructor

A function created using JavaScript constructor with no input parameter is as follows,


function GetData() {

          var add = new Function("alert('hello');")
          add();
        }

Two very important points about Function constructor are as follows,

  1. It creates and complies a JavaScript function dynamically at run time
  2. Each time it creates a new object. So creating function using constructor in a loop is not recommended and it is inefficient

Scoping in Function constructor is very important. It always complies as top level function. It never complies as local function so it does not take lexical scoping.


var message = "Hello All";
            function Data() {

                var  message = "Hello Data";
                return new Function("return message");
            }

            var result = Data()();
            alert(result);

In above code snippet, as you see message variable is defined at two levels global and local to function. From Function constructor message (variable) is returned. It will take global variable instead of local message variable. You will get output as following

clip_image001

These are the points you need to keep in mind working with Function constructor. I hope you find this post useful. Thanks for reading.

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.