Sunday 27 September 2015

What's New in C# 6.0


C# 6.0 has not introduced any new concepts like other versions of C# but instead it introduced some of very interesting and useful features which will help you to write more clean code with less typing.
I am sure as a developer you are going to love these features. Lets figure out what are those:



1. Getter-only auto Property.
 C# 6.0 allows you to define getter-only property and initialize it as part of constructor or directly.

class Features
{
        public string FirstName { get; }
        public string LastName { get; } = "Mahto";
        public Features()
        {
            FirstName = "Binod";
        }
}

2. Using static members: Use static with using directive for namespace reference.
It allow you to access static members of a type without having to qualify the access with the type name,

using static System.Math;

and now when you need to call say Sqrt, you don't need to write Math.Sqrt(...) instead just write Sqrt(...).
using CSharp6Features2.Day; //Here Day is an enum which I have defined.

so next time I don't need to specify Enum type 'Day' while calling it's property.

3. String interpolation: Get rid of using value tokens with "string.Format" to format string.
Example: Old way:

string fName = "Binod", lName = "Mahto";
Console.WriteLine(string.Format("My name is {0} {1}", fName, lName));

in C#6.0

string fName = "Binod", lName = "Mahto";
Console.WriteLine($"My name is {fName} {lName}");

4. Expression-bodied properties: Convert your methods or properties which returns data based on some calculation, to one line code like property using lambda expression.
for example:
Old way:
private double GetFullName(string fname, string lname)
{
         return fname + " " + lname;
}

in C# 6.0
public string FullName => $"{fname} {lname}";




5. Index Initializers: C# 6.0 has extended the object initializers to allow to set values to keys through any indexer that the new object has.
Example: Old Way:
public JObject ToJson()
{
       var obj = new JObject();
       obj["X"] = "Binod";
       obj["Y"] = "Mahto";
       return obj;
}

in C#6.0:
public JObject ToJson()
{
       var obj = new JObject() {["FName"] = "Binod",["LName"] = "Mahto" };
       return obj;
}
OR
public JObject ToJson() => new JObject() {["FName"] = "Binod",["LName"] = "Mahto" };

6. Null-conditional operators(?): It helps to avoid lot of codes which we write while accessing objects, like do null check for objects then do null check of that objects properties and so on. Let see the example:
Old way:
 public string FromJson(JObject json)
{
        if(json != null &&
            json["FName"] != null &&
            json["FName"].Type == JTokenType.String &
            json["LName"] != null &&
            json["LName"].Type == JTokenType.String)
         {
              return $"{json["FName"]} {json["LName"]}";
         }
         return string.Empty;
}

in C# 6.0
 public string FromJson(JObject json)
{
     if (json?["FName"]?.Type == JTokenType.String &&
          json?["LName"]?.Type == JTokenType.String)
     {
           return $"{json["FName"]} {json["LName"]}";
      }
      return string.Empty;
}

it is also very useful to do the event null check before triggering the event.
Ex: OnChanged?.Invloke(this, args);
in this case event will be triggered only if event is not null.

7. The nameof operator: There are scenarios when we need to know the name of program elements (property/parameter name), specially while throwing exceptions.
private static int Calculate(ABC obj)
{
       if (obj.y == 0)
            throw new DivideByZeroException(nameof(obj.y));
       else
           return obj.x / obj.y;
}

At last, this is the feature which I noticed in Visual Studio 2015 which impressed me a lot.
Your visual studio itself will let you know about some tips to clean your code (as Resharper does)
Ex: namespace references in using directive  which are not used. There are lot many, I am sure these features you are going to love it.

Till now I haven't encountered any such scenarios where I need the use of nameof operator.

That's it.

Thank You for reading. Feel free to give your feedback/comment.


Friday 14 August 2015

Cross-Origin Requests (CORS) in ASP.NET Web API 2

Hello frnds,

In my previous post CRUD with AngularJS and ASP.Net Web API, I tried to show you, how to perform CRUD using AngularJs and ASP.NET web API.
In this example we had a ASP.NET Web API called 'Book API' and AngularJs views which talks to book api. As part of this example our web api and angularjs view both were part of same application. It means application and APIs both are running under same domain and port.

Now imagine, if our Book APIs are hosted in other domain and we need to consume it through AngularJS or Javascript/jquery app deployed/running in different domain. Problem looks very simple but fact is that we can't perform cross-origin/domain communication. So how to tackle this cross origin calls then, and the answer is using CORS  in ASP.NET Web API 2.





What is CORS?
Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP.

What is "Same Origin"?
Two URLs have the same origin if they have identical schemes, hosts, and ports. (RFC 6454)
These two URLs have the same origin:
http://example.com/foo.html
http://example.com/bar.html

These URLs have different origins than the previous two:
http://example.net - Different domain
http://example.com:9000/foo.html - Different port
https://example.com/foo.html - Different scheme
http://www.example.com/foo.html - Different subdomain

For details please visit: Enabling Cross-Origin Requests in ASP.NET Web API 2.

Now let's do the example.
On first step what we will do is, deploy our Book API (which we have created as part of above mentioned post 'CRUD with AngularJS and ASP.Net Web API'. and then our target will be to consume BooKAPIs from another application hosted with different domain or port.
I deployed my BookAPI to IIS and URL for BooKAPI for me is: "http://localhost:80/AngularJSExample/api/BookAPI".

Next let's create a simple asp.net application. For simplicity, In this application I am going to have a simple html page called "Home.html" and in this I wrote jqury code to access the BookAPI url to display all the books. Here is the code for Home.html.
<head>
    <title>CORS Example</title>
</head>
<body>
    <script src="Scripts/jquery-2.1.4.min.js"></script>
    <button id="btnGetBooks">Get Books</button>
    <div id="bookDiv"></div>
    
    <script>
        $(function () {

            var getBookList = function () {
                $.get(url).success(displayBooks).fail(displayErrors);
            };

            var displayBooks = function (data) {
                for (i = 0; i < data.length;i++) {
                    $("#bookDiv").append('Id=' + data[i].Id + ' Name=' + data[i].Name + ' Author=' + data[i].Author + '<br/>');
                }
            }

            var displayErrors = function (data) {
                $("#bookDiv").append(JSON.stringify(data, null, 1));
            }

            var url = "http://localhost/AngularJSExample/api/BookAPI"

            $("#btnGetBooks").click(getBookList);
        });
    </script>
</body>
</html>

Here is the UI for above code:

In above html, we have a button and on click of this button application will fetch books detail from BookAPI running under http://localhost:80/AngularJSExample/api.

In Html, I have a div which will show the result. On click of button I am calling the BookAPI using jquery $.get() method. For jquery, either you install directly to your application using nuget packages and refer it Or you can directly refer it through online CDN links.




Now I run it and click on 'Get Books' button then this is what you will see in page as output.



It means BookAPI is not allowing cross-origin communication. For your attention though both the application running under same host but ports are different. BookAPI running under port 80 and Home.html application running under port 81 and that's why asp.net web api (bookapi) is refusing the connection requested by port 81.
Here ASP.NET Web API 2 introduced the feature of CORS which makes our life easier on cross-origin connections.

To enable CORS feature for our BookAPI we need to follow few steps. Let's do it.

Follow below mentioned steps to enable CORS for your web api.
1. Install "Microsoft ASP.NET Web API  CORS" package using nuget package manager to you web api application project(please refer below screenshot here)



2. Open WebApiConfig.cs add settings to enable Cors by registering it to work it globally for all api controllers. To do this add below line of code to your 'Register' method:
config.EnableCors(new EnableCorsAttribute("*", "*", "GET"));
Here
first parameter '*' says, allows any orgin,
second parameter '*' says, allows any header,
third parameter 'GET' says, allows only GET methods.

3. OR go to individual API controller and enable it at controller/action method level and add 'EnableCors' attribute to the controller/action method as defined here:
[EnableCors("*","*","GET")]

'EnableCors' attribute presents under 'System.Web.Http.Cors' dll. So you include this you controller as
using System.Web.Http.Cors;

4. Deploy/update your app to IIS.

Now run Home.html page which we created as separate application and click on 'Get Books' button. Here is the result which we get:

That's it.

Thank You for reading. Feel free to give your feedback/comment.


Sunday 26 July 2015

Asynchronous Programming with Async and Await in C# 5.0

There are lot of articles available over the internet on this topic. few of them are nicely explained but some makes you confusing on these terms.

Actually I was going through this concept and realized why don't I blog it for you to make it simple in understanding. So let me try to explain Asynchronous Programming with Async and Await in a way I understand.

Async and Await:
           These are two keywords of C# and It's introduced in C#5.0 as part of .NET Framework 4.5. These two keywords helps you to write asynchronous programming  code (which will see down here) without any delegate, event or threading complex logic. Actually C# does that complex job internally when you use Async and Await.
Looking into below given example, you will realize it is easy and equivalent as normal synchronous programming code. 

Before we proceed let me tell you few basic mandates about async and await:
  1. await can be used only inside async method (method defines with async keyword)
  2. async methods can use only void, Task or Task<T> as return type.
  3. A method can not awaited (we can't use await with method call), if method is not async and doesn't return a Task. 
  4. Always use 'Async' as suffix to your async methods. (this is not mandatory but a guideline which helps to differentiate async and normal methods) 



Let see the example.
Here I am going to create an async method which returns void. Only purpose of this method is to enable my method to use await inside this method.

public async void DoMyCalculation()
{
     int primeLimit = 10;
     Task<IEnumerable<int>> primeNumsTask = GetPrimeNumbersAsync(primeLimit);

     DoSomeTasksHere();

     IEnumerable<int> primeNums = await primeNumsTask;

     Console.WriteLine("Sum of all prime numbers from 1 to " + primeLimit + " is: " + primeNums.Sum());
}

This method will do lot of tasks/calculation including finding sum of prime numbers within a limit. Here my purpose is, I want to calculate sum of prime numbers asynchronously so that it will not stop/interrupt other tasks which might be written inside DoSomeTasksHere() like methods.

In above method,

Task<IEnumerable<int>> primeNumsTask = GetPrimeNumbersAsync(primeLimit);

Says, there is async method called ‘GetPrimeNumbersAsync’ which returns an IEnumerable list of prime numbers(int) within the range provided. But above code actually means, you will get the prime numbers only when you await the task using below line of code.

IEnumerable<int> primeNums = await primeNumsTask;

Here ‘GetPrimeNumbersAsync’ methods will initiate the execution and control will be returned to the calling method ‘DoMyCalculation()’ and control will move forward to execute ‘DoSomeTasksHere()’ method as per our code.
Now let see how we need to define our async method ‘GetPrimeNumbersAsync()’:

public async Task<IEnumerable<int>> GetPrimeNumbersAsync(int limit)
{
     Console.WriteLine("Start GetPrimeNumbersAsync() call");
         
     IEnumerable<int> primeNums = FindPrimeNumbers(limit);

     Console.WriteLine("End GetPrimeNumbersAsync() call");

     return primeNums;
}

private IEnumerable<int> FindPrimeNumbers(int limit)
{
      Console.Write("PrimeNumbers:");
      for (int i = 1; i <= limit; i++)
      {
           Thread.Sleep(1000);
           if (i % 2 == 0)
           {
               Console.Write(i + " ,");
               yield return i;
           }
      }
      Console.WriteLine();
}

So as per the concept, to define a method async we need to declare method with async keyword and return type should of Task<T> (In our case it is Task<IEnumerable<int>>.
That’s all. Here is the complete code:




namespace TestConsoleApp
{
    public class AsyncAwait
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main() call starts.");
            AsyncAwait program = new AsyncAwait();
            program.DoMyCalculation();
           
            Console.WriteLine("Main() call ends.");

            Console.ReadLine();
        }

        public async void DoMyCalculation()
        {
            int primeLimit = 10;
            Task<IEnumerable<int>> primeNumsTask = GetPrimeNumbersAsync(primeLimit);

            DoSomeTasksHere();

            IEnumerable<int> primeNums = await primeNumsTask;
            Console.WriteLine("Sum of all prime numbers from 1 to " + primeLimit + " is: " + primeNums.Sum());
        }

        public async Task<IEnumerable<int>> GetPrimeNumbersAsync(int limit)
        {
            Console.WriteLine("Start GetPrimeNumbersAsync() call");
         
            IEnumerable<int> primeNums = FindPrimeNumbers(limit);

            Console.WriteLine("End GetPrimeNumbersAsync() call");

            return primeNums;
        }

        private IEnumerable<int> FindPrimeNumbers(int limit)
        {
            Console.Write("PrimeNumbers:");
            for (int i = 1; i <= limit; i++)
            {
                Thread.Sleep(1000);
                if (i % 2 == 0)
                {
                    Console.Write(i + " ,");
                    yield return i;
                }
            }
            Console.WriteLine();
        }

        private void DoSomeTasksHere()
        {
            Console.WriteLine("DoSomeTasksHere() call : I am Sleeping.");
            Thread.Sleep(10000);
            Console.WriteLine("DoSomeTasksHere() end : I woke up.");
        }
    }

}

Now if you run the above program, this is what you will get as output in output window.

Main() call starts.
Start GetPrimeNumbersAsync() call
End GetPrimeNumbersAsync() call
DoSomeTasksHere() call : I am Sleeping.
DoSomeTasksHere() end : I woke up.
PrimeNumbers:2 ,4 ,6 ,8 ,10 ,
Sum of all prime numbers from 1 to 10 is: 30
Main() call ends.







Done.
Thank you for reading.
Feel free to provide your feedback/comments.

Reference: https://msdn.microsoft.com/en-us/library/hh191443.aspx



Monday 15 June 2015

Exception Handling - Best Practices

Exception Handling: A well known Concept. I hope everyone knows about it. A very simple but crucial piece of code.
In C#, it's all about try, catch and finally block.
try
{
       //Contains code which could throw unexpected error at run time which is called exception.
}
Catch(Exception)
{
      //Contains  exception handle logic, Ex.: logging.
}
finally
{
      //Contains code which will get executed if try block is executed. It will get executed if there is no exception or even if there is exception. Ex.: used to do memory release, connection close etc.
}


Looks very simple but still programmers do mistakes. So here I am going to discuss few best practices which I learned from my past experience.



1. Throwing exceptions hit performance badly. So try to minimize the 'throw' as much as possible.
Ex.:
void Method()
{
          for(int i = 0; i < 10000; i++)
          {
                try
                {  
                     if( i/2 == 0)
                            throw new Exception();
                 }
                 catch {}
         }
          Console.WriteLine("Loop Ends");
}

Above code practice is totally wrong. Just commenting out the " throw new Exception()" line of code can show the bad impact of having this line.

2. Can we put entire piece of code for a method in a single try block.
Yes. No harm in this.
Ex:
void Method()
{
       try
       {
              //Code
       }
       Catch(Exception)
       {
             
       }
}

3. Don't catch exception if you are not doing anything with the exception. Let the Calling method to catch exception and decide what to do.
Ex:
void Method()
{
       try
       {
              //Code
       }
       Catch(Exception)
       {
              throw;
       }
}

very bad practice of exception handling. It will hit the performance while throwing the exception, Never do it.

4. Don't use the catch exception object to throw exception if you need to catch the exception and then throw. It looses the stack trace details.
Ex:
void Method()
{
       try
       {
              //Code
       }
       Catch(Exception ex)
       {
             //Logging exception here or doing something.
              throw ex;
       }
}

the piece of code "throw ex" is bad practice instead you should write just "throw;"



5. Don't catch exception if you are not doing anything with the exception details.

6. All your public method must have 'try-catch' block instead of having it in private methods.
Note: Handle exception in private methods only if have no intention to throw exception to calling method.

7. Don't keep your catch block dumb.
Ex.
bool Method()
{
       bool status;
       try
       {
              //Code
       }
       Catch{}
       return status;
}

In above code you basically eat the exception. In this case if someone is calling this method he will always get returned FALSE and calling method will never know why return status is false.

8. Avoid returning "ex.Message"  Or "ex.InnerException.Message" as a return statement.
Ex:
string Method()
{
       try
       {
              //Code
       }
       catch (Exception ex)
      {
             return ex.Message; OR return ex.InnerException.Message;
      }
       return "";
}

Exception details always contains crucial and confidential information as it contains detail about the code, logic, resource details etc. So by writing above code you are basically creating a security risk by passing information to calling method.

9. Always use Custom Exception to throw exception when it is raised by service which is going to get consumed by different consumers directly.
Ex. If you are developing a service library or an API which can be consumed by different consumer. In this case you should not throw actual exception as it contains details about you business logic.

10. Don't forget to use try-catch or you will end up showing yellow page with exception details to the user.

Thank you for reading.
Feel free to provide your feedback/comments.


Wednesday 10 June 2015

Dependency Injection with AngularJS Services

Hello Frnds,

Today we are going to discuss about dependency injection with AngularJS Services. It sounds interesting, Isn't it?

This post is the continuation of my previous post " CRUD with AngularJS and ASP.Net Web API".
So in case if you have not gone through that I would suggest please go through that.

What is Dependency Injection(DI):
In short & simple, It's a way to inject the dependencies. 
In detail, dependency injection is a software design pattern that implements inversion of control for software libraries. Caller delegates to an external framework the control flow of discovering and importing a service or software module specified or "injected" by the caller (source: http://en.wikipedia.org/wiki/Dependency_injection).

Dependency Injection is available through out the AngularJS. You can use it with Services, directives, filters, and animations etc. 
For more detail refer this: https://docs.angularjs.org/guide/di#



As I said DI can be used with services, So here I am going to explain you how you inject a service within a service. I am gonna use the same example here which I have used in my last post. In order to proceed I am going to do some changes in the example (used in previous post):
Change 1: Small change in our business model class "Book".
public class Book
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public decimal Price { get; set; }
        public decimal OfferPrice { get; set; } //This is new property which we are adding.
    }

Change2: Define a new AngularJS service class, by adding a new script file "BookngDiscountService.js" under Scripts=>BookngScripts folder.

app.service('bookDiscountManageService', function () {
    this.getDiscountOnBook = getDiscountOnBook = function (bookPrice) {
        if (bookPrice >= 500) {
            return bookPrice * 10 / 100;
        }
        else {
            return 0;
        }
    }
});

What this service does is, it defines a service method to decide discount based on some logic on MRP of book. Very simple isn't it?



Change 3: Modify the view to accommodate to show Price after discount (let's call it OfferPrice).
<table style="border: solid 2px Black; padding: 5px;">
                    <tr style="height: 30px; background-color:lightsteelblue; color: maroon;">
                        <th></th>
                        <th style="width:50px">ID</th>
                        <th style="width:150px">Name</th>
                        <th style="width:150px">Author</th>
                        <th style="width:100px">MRP Price</th>
                        <th style="width:100px">Offer Price</th>
                        <th style="width:50px"></th>
                        <th style="width:50px"></th>
                    </tr>
                    <tbody ng-repeat="book in Books">
                        <tr>
                            <td></td>
                            <td style="width:50px"><span>{{book.Id}}</span></td>
                            <td style="width:150px"><span>{{book.Name}}</span></td>
                            <td style="width:150px"><span>{{book.Author}}</span></td>
                            <td style="width:100px"><span>{{book.Price | currency}}</span></td>
                            <td style="width:100px"><span>{{book.OfferPrice | currency}}</span></td>
                            <td>
                                <input type="button" id="Edit" value="Edit" ng-click="get(book)" />
                            </td>

                            <td>
                                <input type="button" id="Delete" value="Delete" ng-click="delete(book)" />
                            </td>
                        </tr>
                    </tbody>
                </table> 

Change 4: I am going to inject my new service (bookDiscountManageService, defined in change step 3) to my existing service called "bookManageService" (defined in earlier post, BookngService.js).
So here is change we need to do in "bookManageService" to inject our new bookDiscountManageService into bookManageService service.
app.service('bookManageService', function ($http, bookDiscountManageService) {
....
....
}

Highlighted piece of code in above line is the change, and it means that our bookManageService is dependent on another service bookDiscountManageService which is being injected to this service.



Now I want to use the service method 'getDiscountOnBook' of bookDiscountManageService service to update OfferPrice of the book by calling it inside 'getAllBook' service method of 'bookManageService' service. This how we need to modify the code:
//Fetch All Books
    this.getAllBook = function () {
        return $http.get("/api/BookAPI").success(function (data) {
            $.each(data, function (i, item) {
                item.OfferPrice = item.Price - bookDiscountManageService.getDiscountOnBook(item.Price);
            });
        })
    }

Highlighted piece of code shows the change part. What it means is, After getting data from ASP.NET Web API, it calls the injected service 'bookDiscountManageService' to calculate the discounted price.

This is it. Now think about it How easy to achieve the dynamics of OfferPrice without doing any change in ASP.NET Web API or AngularJS controller or in the main AngularJS service. 

After this change here is UI which you will get:
Thank You for reading. Don't forget to like it and feel free to give your feedback/comment.



Monday 8 June 2015

CRUD with AngularJS and ASP.Net Web API

It's really fun to learn something new and the more fun is in sharing it with people.
So here I am gonna explain you "How to perform CRUD with AngularJS using Asp.net Web API". AngularJS become such a hot client side technology in today's web world and believe me it's going to rule the web application development.
Before I start let's know a bit about basic of AngularJS.

What is AngularJS
AngularJS is a library written in JavaScript. It's an open-source web application framework developed and maintained by Google It helps to create single-page applications(SPA) that only requires HTML, CSS and Javascript on client side.
Do not compare it with JQuery, It uses a subset of JQuery to perform some task. So whenever you want/need to install AngularJS for your project then Install/include JQuery library first and then AngularJS.
To know more about AngularJS: https://docs.angularjs.org/guide/introduction

AngularJS extends HTML with ng-directive and the basic directives are:

  • ng-app: defines an AngularJS application.
  • ng-model: binds the value of HTML controls (input, select, textarea) to application data.
  • ng-bind: binds application data to the HTML view.
  • ng-controller: defines the application controller.

Apart from these basics directive I am going to use some concepts of AngularJS like Module, Service, Expressions etc. I would suggest if you have patience then better to spend some time here: http://www.w3schools.com/angular/

Hope by now you have learned about basics of AngularJS. So let's start with CRUD operation example.
where to start?????  Ok let's start with building Web API first which basically will perform CRUD with database. For the example purpose I have not used any database here but your Web Api will be the one which is going to interact with your database.
In short, ASP.NET Web API is a framework for building web APIs on top of the .NET Framework over http protocol. To know more about ASP.NET Web API refer this: http://www.asp.net/web-api.

To Create a ASP.NET Web API using Visual Studio 2013, create a new project => Web => ASP.NET Web Application and then select the template Web API.
(I assume, you are very much familier with visual studio tool and MVC framework and that's why I am not including any screenshot here for this.)


Once you create the project, Let's add a model class "Book.cs" under Model folder.

public class Book
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public decimal Price { get; set; }
    }

Then add a APIController with empty template for this, by right clicking of 'Controller' folder and name it "BookAPIController".

public class BookAPIController : ApiController
    {
        private static IList<Book> books = new List<Book>()
        {
            new Book{Id = "A01", Name = "Once upon a time", Author = "G D Roy", Price = 150.00M},
            new Book{Id = "A02", Name = "The Last Hero", Author = "K P Say", Price = 150.00M},
            new Book{Id = "A03", Name = "The King of Kingdom", Author = "Albert D", Price = 150.00M},
            new Book{Id = "A04", Name = "Jungle King", Author = "D Serduke", Price = 150.00M},
            new Book{Id = "A05", Name = "Magical Box", Author = "M Mathews", Price = 150.00M}
        };

        // GET: api/BookAPI
        public IEnumerable<Book> GetBooks()
        {
            return books;
        }

        // GET: api/BookAPI/5
        public Book GetBook(string id)
        {
            return books.FirstOrDefault<Book>(book => book.Id == id);
        }

        // POST: api/BookAPI
        public HttpResponseMessage PostBook(Book book)
        {
            books.Add(book);
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // PUT: api/BookAPI/5
        public HttpResponseMessage PutBook(Book book)
        {
            if(books.Any<Book>(bk => bk.Id == book.Id))
            {
                try
                {
                    Book currentBook = books.First<Book>(bk => bk.Id == book.Id);
                    int index = books.IndexOf(currentBook);
                    books[index] = book;
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
                catch(Exception ex)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
        }

        // DELETE: api/BookAPI/5
        public HttpResponseMessage DeleteBook(string id)
        {
            if (books.Any<Book>(bk => bk.Id == id))
            {
                try
                {
                    Book currentBook = books.First<Book>(bk => bk.Id == id);
                    int index = books.IndexOf(currentBook);
                    if(books.Remove(currentBook))
                        return Request.CreateResponse(HttpStatusCode.OK);
                    else
                        return Request.CreateResponse(HttpStatusCode.InternalServerError);
                }
                catch (Exception ex)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
        }
    }

In above code, each and every method tells about himself.
Note: WEB API works on Get, Post, Put and Delete http methods.
So our Web API is ready and can be consumed by client.

Now we will actually talk about AngularJS framework to do the CRUD operation without any postback. Here we go:
 Let's add below mentioned three javascript file under 'Script' folder by creating a sub folder 'BookngScripts'. This sub folder is optional but it become necessary to separate out your files with other jquery and angular js files.

  1. BookngService.Js: This is AngularJS service which will basically consume the ASP.NET Web API and works as a middle layer between AngularJS controller and ASP.NET Web API.
  2. BookngModule.Js: It's a container for the different parts of an application. All application controller should belong to a module.
  3. BookngController.js: Controller is a JavaScript Object, created by a standard JavaScript object constructor.

Now we write code for above mentioned items:
BookngService.js
app.service('bookManageService', function ($http) { 

    //Add New Book
    this.post = function (Book) {
        var request = $http({
            method: "post",
            url: "/api/BookAPI",
            data: Book
        });
        return request;
    }

    //Fetch Book
    this.get = function (Id) {
        return $http.get("/api/BookAPI/" + Id);
    }

    //Fetch All Books
    this.getAllBook = function () {
        return $http.get("/api/BookAPI");
    }

    //Update Book  
    this.put = function (Book) {
        var request = $http({
            method: "put",
            url: "/api/BookAPI",
            data: Book
        });
        return request;
    }

    //Delete Book  
    this.delete = function (Id) {
        var request = $http({
            method: "delete",
            url: "/api/BookAPI/" + Id
        });
        return request;
    }

});

Here I created a AngularJS service called "bookManageService". It defines AngularJS service methods like post, get, getAllBook, put and delete. This service methods will be called from AngularJS controller.
Note: $http is an AngularJS service for reading data from remote servers.

Now we create controller called "bookController":
BookngController.js
app.controller('bookController', function ($scope, bookManageService) {
    $scope.IsInEditMode = false; //variable to decide, edit a record or create a record 
    $scope.Message = ""; //variable used to store error or success messages.
    
GetAllBooks(); 

    //Get All Books
    function GetAllBooks() {
        var reqGet = bookManageService.getAllBook();
        reqGet.then(function (obj) { $scope.Books = obj.data },
            function (error) {
                $scope.Message = 'Error while fetching records. Error:' + error;
            });
    }

    //Clear Book Model
    function Clear() {
        $scope.IsInEditMode = false;
        $scope.Id = "";
        $scope.Name = "";
        $scope.Author = "";
        $scope.Price = "";
    }

    //Create or Edit Book
    $scope.save = function () {
        var Book = {
            Id: $scope.Id,
            Name: $scope.Name,
            Author: $scope.Author,
            Price: $scope.Price
        };
        if($scope.IsInEditMode == false){//Adding new book
            var reqPost = bookManageService.post(Book);
            reqPost.then(function (obj) {
                $scope.Message = "Book added successfully";
                GetAllBooks();
                Clear();
            },
            function (err) {  
                $scope.Message = "Adding Book failed for following reason:" + err;  
            }); 
        }
        else { //Editing existing book detail
            Book.Id = $scope.Id;
            var reqPost = bookManageService.put(Book);
            reqPost.then(function (obj) {
                $scope.Message = "Book updated successfully";
                GetAllBooks();
                Clear();
            },
            function (err) {
                $scope.Message = "Updating Book failed for following reason:" + err;
            });
        }
    }

    //Delete a Book
    $scope.delete = function (Book) {
        var reqDelete = bookManageService.delete(Book.Id);
        reqDelete.then(function (obj) {
            GetAllBooks();
            $scope.Message = "Book deleted successfully";  
        },
        function (err) {
            $scope.Message = "Deleting Book failed for following reason:" + err ;
        });
    }

    //Fetch book detail
    $scope.get = function (Book) {
        var reqGet = bookManageService.get(Book.Id);
        reqGet.then(function (obj) {
            var res = obj.data;
            $scope.Id = res.Id;
            $scope.Name = res.Name;
            $scope.Author = res.Author;
            $scope.Price = res.Price;

            $scope.IsInEditMode = true;
        },
        function (err) {
            $scope.Message = "Unable to fetch book detail for following reason:" + err;
        });
    }

    //To Clear all Inputs controls value.  
    $scope.clear = function () {
        $scope.IsInEditMode = false;
        $scope.Id = "";
        $scope.Name = "";
        $scope.Author = "";
        $scope.Price = "";
    }

});

Here created a controller with the name "bookController" and it also define a function as second parameter which takes two argument $scope ($scope is the application object, the owner of application variables and functions. In short, It's the glue between application controller and the view) and the "bookManageService" (one which we created above here). Inside the function, I have defined four event method $scope.save, $scope.get, $scope.delete and $scope.clear.
Now we will create module:
BookngModule.js:
 var app = angular.module('bookModule', []);

and now create a MVC controller called "BookController" and add a action method called "Index".
BookController.cs
public class BookController : Controller
    {
        // GET: Book
        public ActionResult Index()
        {
            return View();
        }
    }


Now right click inside this Index and Add View with Empty(without a model) template and copy-paste the below code in your view:
<html ng-app="bookModule"
@{
    ViewBag.Title = "Manage Books";
}

<body>
    <table id="tblContainer" ng-controller="bookController">
        <tr>
            <td>
                <table style="border: solid 2px Black; padding: 5px;">
                    <tr style="height: 30px; background-color:lightsteelblue; color: maroon;">
                        <th></th>
                        <th style="width:50px">ID</th>
                        <th style="width:150px">Name</th>
                        <th style="width:150px">Author</th>
                        <th style="width:50px">MRP Price</th>
                        <th style="width:50px"></th>
                        <th style="width:50px"></th>
                    </tr>
                    <tbody ng-repeat="book in Books">
                        <tr>
                            <td></td>
                            <td style="width:50px"><span>{{book.Id}}</span></td>
                            <td style="width:150px"><span>{{book.Name}}</span></td>
                            <td style="width:150px"><span>{{book.Author}}</span></td>
                            <td style="width:50px"><span>{{book.Price | currency}}</span></td>
                            <td>
                                <input type="button" id="Edit" value="Edit" ng-click="get(book)" />
                            </td>

                            <td>
                                <input type="button" id="Delete" value="Delete" ng-click="delete(book)" />
                            </td>
                        </tr>
                    </tbody>
                </table>

            </td>
        </tr>
        <tr></tr>
        <tr></tr>
        <tr>
            <td>
                <div style="color: red;">{{Message}}</div>
                <table style="border: solid 4px Red; padding: 2px;">
                    <tr>
                        <td></td>
                        <td>
                            <span>Id</span>
                        </td>
                        <td>
                            <input type="text" id="BookId" ng-model="Id" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Name</span>
                        </td>
                        <td>
                            <input type="text" id="bookName" ng-model="Name" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Author</span>
                        </td>
                        <td>
                            <input type="text" id="bookAuthor" ng-model="Author" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Price</span>
                        </td>
                        <td>
                            <input type="text" id="bookPrice" ng-model="Price" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td>
                            <input type="button" id="save" value="Save" ng-click="save()" />

                            <input type="button" id="Clear" value="Clear" ng-click="clear()" />
                        </td>
                    </tr>
                </table>

            </td>
        </tr>

    </table>
</body>
</html>  
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<script src="~/Scripts/BookngScripts/BookngModule.js"></script>
<script src="~/Scripts/BookngScripts/BookngController.js"></script>
<script src="~/Scripts/BookngScripts/BookngService.js"></script>

If you see the highlighted piece of code, you will realized how your view is connected with the AngularJS controller which we created here and how your model data is getting bind with UI. Anyway let me give some note about the directives highlighted here:

  1. ng-app : this defines the module for our html page. 
  2. ng-controller: this allows me to define the controller for this module.
  3. {{xyz}}: this is the way to define an expression in AngularJS. You can also use such expression like {{5+2+3}}. Note: Instead of using expression to render value in html you can also use ng-bind directive. ex: <td style="width:50px"><span ng-bind="book.Id"></span></td>
  4. ng-click: this directive allows you to bind the event(the one which we created in controller using $scope.get = function(..){....}) for button click.
  5. ng-model: this bind the our model with view. So if view changes model will get updated automatically.
Here is the UI outcome of this:


That's it.

Thank You for reading. Feel free to give your feedback/comment.