How to do CRUD operations in Asp.net Web API ? (Part 2)


Hi

We can do CRUD(Create Read Update and Delete) operations in Web API as given below

Step 1: Create the new project from visual studio like this

Step 2: Create the tblEmp with Id, EmpName and EmpAddress in database as given below

Step 3: Go to the model folder and add the data model as given below

Step 4: Right click on controller folder and Add the Web API controller like this

Add the suitable Model class and data context class as per as your application

Step 5: Now your Web API controller is ready to use in any application

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;
using WebApi_Sample.Models;

namespace WebApi_Sample.Controllers.Web_Api
{
    public class Emps_API_Controller : ApiController
    {
        private Database1Entities db = new Database1Entities();

        // GET: api/Emps_API_
        public IQueryable<tblEmp> GettblEmps()
        {
            return db.tblEmps;
        }

        // GET: api/Emps_API_/5
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult GettblEmp(int id)
        {
            tblEmp tblEmp = db.tblEmps.Find(id);
            if (tblEmp == null)
            {
                return NotFound();
            }

            return Ok(tblEmp);
        }

        // PUT: api/Emps_API_/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PuttblEmp(int id, tblEmp tblEmp)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != tblEmp.Id)
            {
                return BadRequest();
            }

            db.Entry(tblEmp).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!tblEmpExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Emps_API_
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult PosttblEmp(tblEmp tblEmp)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.tblEmps.Add(tblEmp);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = tblEmp.Id }, tblEmp);
        }

        // DELETE: api/Emps_API_/5
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult DeletetblEmp(int id)
        {
            tblEmp tblEmp = db.tblEmps.Find(id);
            if (tblEmp == null)
            {
                return NotFound();
            }

            db.tblEmps.Remove(tblEmp);
            db.SaveChanges();

            return Ok(tblEmp);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool tblEmpExists(int id)
        {
            return db.tblEmps.Count(e => e.Id == id) > 0;
        }
    }
}

Step 6: Now test on browser for get method. you will get the output as given below

Summary:

In this post we learnt that how to create the CRUD operation using Entity Framework with asp.net web api. We also observed that in Asp.net Web API, we cannot give any method name similar to Asp.net MVC controller.
Method Name should always start with HTTP Verbs i.e (GET,PUT, POST and DELETE)

  • Create -> POST
  • Read -> GET
  • Update -> PUT
  • Delete -> DELETE
    Advertisements
  • What is the Asp.net Web API? (Part 1)


    Asp.net web API is the Microsoft framework for building HTTP Service that can be consumed by broad range of client like window application, Web Form Application, WPF, Mobile, Tablet and smart TV.

    It is very easy to learn if you are knowing some basic concept of asp.net MVC framework. It is very much similar to asp.net MVC.

    It contains the MVC framework features like Routing, Controller, Action Result, Filter, Model binders, IOC containers or dependency injection.

    (Note: Image taken from Microsoft site)

    What are the advantages of web API as compare to other service?

    There are many approach to create the service in Microsoft platform like Web Service and WCF. This two services were so popular in old days. Still now in legacy application we will use this two service. Nowadays people are using the application in different devices like PC, Tablet, Smart phone, smart TV and other devices.

    If we will develop the service using old web service it will be very difficult to reach the broad ranges of devices. So to make the developer life easy Microsoft developed the new framework i.e. Asp.net Web API

    It has the following advantages

    1. It targets the broad range of client devices
    2. It doesn’t have tedious and extensive configuration like WCF REST service.
    3. It is light weight architecture and good for devices which have limited bandwidth like smart phones and tablet.
    4. It is open source

    What are the Asp.net Web API Characteristics?

    1. ASP.NET Web API is an ideal platform for building RESTful services.
    2. ASP.NET Web API is built on top of ASP.NET and supports ASP.NET request/response pipeline
    3. ASP.NET Web API maps HTTP verbs to method names.
    4. ASP.NET Web API supports different formats of response data. Built-in support for JSON, XML, BSON format.
    5. ASP.NET Web API can be hosted in IIS, Self-hosted or other web server that supports .NET 4.0+.
    6. ASP.NET Web API framework includes new HttpClient to communicate with Web API server. HttpClient can be used in ASP.MVC server side, Windows Form application, Console application or other apps.

    What are the difference between WCF and Asp.net Web API?

    When to use WCF?

    These are the following scenario to use WCF
    1. If you are using .Net 3.5 or below
    2. If your service needs to support multiple protocols such as HTTP, TCP, Named pipe.
    3. If you want to build service with WS-* standards like Reliable Messaging, Transactions, Message Security.
    4. If you want to use Request-Reply, One Way, and Duplex message exchange patterns.

    When to use Web API?

    These are the following scenario to use WCF
    1. If you are using .NET framework 4.0 or above.
    2. If you want to build a service that supports only HTTP protocol.
    3. If you want to build RESTful HTTP based services.
    4. If you are targeting the broad range of device like PC, Mobile,Tablet and smart TV etc.

    How to decompile the .net dll code?


    So many time we will get the scenario to read the code of .net dll for better understanding the framework. But by default there are no option to read the code in visual studio.

    There are so many commercial tool are available for doing this task.But that all are not the free tool. Recently I found one of more stable open source tool to read the .net dll code i.e. ILSpy.

    You can download this tool from this url http://ilspy.net/

    Steps to use this dll

    Step 1: Just download the binary file from the given above URL

    Step 2: Extract the folder and click on ILSpy.exe

    Step 3:

    Now add your dll and click on class as given below image

    Uncaught TypeError: Cannot read property ‘value’ of null


    Hi

    If you getting this error message in java-script, then you might be thinking that you have written some wrong syntax in java-script, but it is not the syntax problem, it is the problem with reading value of that Id which one you have given to read the values. For example in the below code i have given the wrong text-box Id to read the value then i will get this exception.

    Why is OpenSubKey() returning null on my 64-bit system?


    Today i was debugging the code, it was written like this

    
     string _retValue = "";
                Microsoft.Win32.RegistryKey _rKey;
                Object _rKeyObject;
                string REG_KEY_PATH_PROFILE = "SOFTWARE\\Wow6432Node\\Mycompany\\e-business\\Platform\\profile\\";
                try
                {
                    _rKey = Microsoft.Win32.Registry.LocalMachine;
                    _rKeyObject = _rKey.OpenSubKey(REG_KEY_PATH_PROFILE).GetValue(keyName);
                    _retValue = Convert.ToString(_rKeyObject);
                    return _retValue;
                }
    
    

    It was returning null value every time, then i came to know i am building the application on 64 bit, To make the work around we can change project setup like this given below

    Different ways of doing serialization and deserialization in .Net (Asp.net/Asp.net MVC) (Part 3)


    Method 1: Using System.Runtime.Serialization.Json Namespace

    Method 2: Using System.Web.Script.Serialization Namespace

    Method 3:

    In this method we will use the Newtonsoft.Json dll

    This is one of the most popular open source dll, we install it from Nuget package manager or from google download it and add to our project

    We can write code as given below

    
    using Newtonsoft.Json;
    using System;
    
    namespace WebApplication1
    {
        public partial class Demo3 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                EmpDemo objEmp = new EmpDemo
                {
                    Id = 1021,
                    EmpName = "Chandradev",
                    EmpAddress = "Bangalore"
                };
    
                string jsonData = JsonConvert.SerializeObject(objEmp);
                Response.Write("<b>Converting to Json </b> " + "</br>");
                Response.Write("</br>");
                Response.Write(jsonData);
                Response.Write("</br>");
    
                var objEmp1 = JsonConvert.DeserializeObject<EmpDemo>(jsonData);
                Response.Write("</br>");
                Response.Write("Converting Json to .Net Object:");
                Response.Write("</br>");
                Response.Write("Id: " + objEmp1.Id + "</br>");
                Response.Write("EmpName: " + objEmp1.EmpName + "</br>");
                Response.Write("EmpAddress: " + objEmp1.EmpAddress + "</br>");
            }
    
            public class EmpDemo
            {
                public int Id { get; set; }
                public string EmpName { get; set; }
                public string EmpAddress { get; set; }
            }
        }
    }
    
    

    Note: donot forget to include the Newtonsoft.Json namespace in your code. This approach can be used in Asp.net or asp.net mvc application.

    Different ways of doing serialization and deserialization in .Net (Asp.net/Asp.net MVC)(Part 2)


    different-ways-of-doing-serialization-and-deserialization-in-net-asp-netasp-net-mvc (Part 1)

    Method 2 approach

    we will use System.Web.Script.Serialization namespace of .net framework

    Step 1: Create the EmpDemo Class and write the code in code behind file like given below

    
    using System;
    using System.Web.Script.Serialization;
    
    namespace WebApplication1
    {
        public partial class Demo1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                EmpDemo objEmp = new EmpDemo
                {
                    Id = 1021,
                    EmpName = "Chandradev",
                    EmpAddress = "Bangalore"
                };
    
                JavaScriptSerializer js = new JavaScriptSerializer();
    
                Response.Write("<b>Converting to Json </b> " + "</br>");
                Response.Write("</br>");
                string jsonData = js.Serialize(objEmp);
                Response.Write(jsonData);
                Response.Write("</br>");
    
                var objEmp1 = js.Deserialize(jsonData);
                Response.Write("</br>");
                Response.Write("<b> Converting Json to .Net Object: </b>");
                Response.Write("</br>");
                Response.Write("Id: " + objEmp1.Id + "</br>");
                Response.Write("EmpName: " + objEmp1.EmpName + "</br>");
                Response.Write("EmpAddress: " + objEmp1.EmpAddress + "</br>");
            }
        }
    
        public class EmpDemo
        {
            public int Id { get; set; }
            public string EmpName { get; set; }
            public string EmpAddress { get; set; }
        }
    }
    
    

    Summary: This approach will be suitable in asp.net or asp.net mvc application.