Wednesday, 11 July 2018

Call a Web API From a .NET Client (C#)

In this tutorial, a client app is written that consumes the following web API:
ActionHTTP methodRelative URI
Get a product by IDGET/api/products/id
Create a new productPOST/api/products
Update a productPUT/api/products/id
Delete a productDELETE/api/products/id
To learn how to implement this API with ASP.NET Web API, see Creating a Web API that Supports CRUD Operations.
For simplicity, the client application in this tutorial is a Windows console application. HttpClient is also supported for Windows Phone and Windows Store apps. For more information, see Writing Web API Client Code for Multiple Platforms Using Portable Libraries

Create the Console Application

In Visual Studio, create a new Windows console app named HttpClientSample and paste in the following code:
C#
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace HttpClientSample
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }

    class Program
    {
        static HttpClient client = new HttpClient();

        static void ShowProduct(Product product)
        {
            Console.WriteLine($"Name: {product.Name}\tPrice: " +
                $"{product.Price}\tCategory: {product.Category}");
        }

        static async Task<Uri> CreateProductAsync(Product product)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync(
                "api/products", product);
            response.EnsureSuccessStatusCode();

            // return URI of the created resource.
            return response.Headers.Location;
        }

        static async Task<Product> GetProductAsync(string path)
        {
            Product product = null;
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.IsSuccessStatusCode)
            {
                product = await response.Content.ReadAsAsync<Product>();
            }
            return product;
        }

        static async Task<Product> UpdateProductAsync(Product product)
        {
            HttpResponseMessage response = await client.PutAsJsonAsync(
                $"api/products/{product.Id}", product);
            response.EnsureSuccessStatusCode();

            // Deserialize the updated product from the response body.
            product = await response.Content.ReadAsAsync<Product>();
            return product;
        }

        static async Task<HttpStatusCode> DeleteProductAsync(string id)
        {
            HttpResponseMessage response = await client.DeleteAsync(
                $"api/products/{id}");
            return response.StatusCode;
        }

        static void Main()
        {
            RunAsync().GetAwaiter().GetResult();
        }

        static async Task RunAsync()
        {
            // Update port # in the following line.
            client.BaseAddress = new Uri("http://localhost:64195/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                // Create a new product
                Product product = new Product
                {
                    Name = "Gizmo",
                    Price = 100,
                    Category = "Widgets"
                };

                var url = await CreateProductAsync(product);
                Console.WriteLine($"Created at {url}");

                // Get the product
                product = await GetProductAsync(url.PathAndQuery);
                ShowProduct(product);

                // Update the product
                Console.WriteLine("Updating price...");
                product.Price = 80;
                await UpdateProductAsync(product);

                // Get the updated product
                product = await GetProductAsync(url.PathAndQuery);
                ShowProduct(product);

                // Delete the product
                var statusCode = await DeleteProductAsync(product.Id);
                Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
    }
}
The preceding code is the complete client app.
RunAsync runs and blocks until it completes. Most HttpClient methods are async, because they perform network I/O. All of the async tasks are done inside RunAsync. Normally an app doesn't block the main thread, but this app doesn't allow any interaction.
C#
static async Task RunAsync()
{
    // Update port # in the following line.
    client.BaseAddress = new Uri("http://localhost:64195/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

    try
    {
        // Create a new product
        Product product = new Product
        {
            Name = "Gizmo",
            Price = 100,
            Category = "Widgets"
        };

        var url = await CreateProductAsync(product);
        Console.WriteLine($"Created at {url}");

        // Get the product
        product = await GetProductAsync(url.PathAndQuery);
        ShowProduct(product);

        // Update the product
        Console.WriteLine("Updating price...");
        product.Price = 80;
        await UpdateProductAsync(product);

        // Get the updated product
        product = await GetProductAsync(url.PathAndQuery);
        ShowProduct(product);

        // Delete the product
        var statusCode = await DeleteProductAsync(product.Id);
        Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");

    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }

    Console.ReadLine();
}

Install the Web API Client Libraries

Use NuGet Package Manager to install the Web API Client Libraries package.
From the Tools menu, select NuGet Package Manager > Package Manager Console. In the Package Manager Console (PMC), type the following command:
Install-Package Microsoft.AspNet.WebApi.Client
The preceding command adds the following NuGet packages to the project:
  • Microsoft.AspNet.WebApi.Client
  • Newtonsoft.Json
Json.NET is a popular high-performance JSON framework for .NET.

Add a Model Class

Examine the Product class:
C#
public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}
This class matches the data model used by the web API. An app can use HttpClient to read a Product instance from an HTTP response. The app doesn't have to write any deserialization code.

Create and Initialize HttpClient

Examine the static HttpClient property:
C#
static HttpClient client = new HttpClient();
HttpClient is intended to be instantiated once and reused throughout the life of an application. The following conditions can result in SocketException errors:
  • Creating a new HttpClient instance per request.
  • Server under heavy load.
Creating a new HttpClient instance per request can exhaust the available sockets.
The following code initializes the HttpClient instance:
C#
static async Task RunAsync()
{
    // Update port # in the following line.
    client.BaseAddress = new Uri("http://localhost:64195/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
The preceding code:
  • Sets the base URI for HTTP requests. Change the port number to the port used in the server app. The app won't work unless port for the server app is used.
  • Sets the Accept header to "application/json". Setting this header tells the server to send data in JSON format.

Send a GET request to retrieve a resource

The following code sends a GET request for a product:
C#
static async Task<Product> GetProductAsync(string path)
{
    Product product = null;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        product = await response.Content.ReadAsAsync<Product>();
    }
    return product;
}
The GetAsync method sends the HTTP GET request. When the method completes, it returns an HttpResponseMessage that contains the HTTP response. If the status code in the response is a success code, the response body contains the JSON representation of a product. Call ReadAsAsyncto deserialize the JSON payload to a Product instance. The ReadAsAsync method is asynchronous because the response body can be arbitrarily large.
HttpClient does not throw an exception when the HTTP response contains an error code. Instead, the IsSuccessStatusCode property is false if the status is an error code. If you prefer to treat HTTP error codes as exceptions, call HttpResponseMessage.EnsureSuccessStatusCode on the response object. EnsureSuccessStatusCode throws an exception if the status code falls outside the range 200–299. Note that HttpClient can throw exceptions for other reasons — for example, if the request times out.

Media-Type Formatters to Deserialize

When ReadAsAsync is called with no parameters, it uses a default set of media formatters to read the response body. The default formatters support JSON, XML, and Form-url-encoded data.
Instead of using the default formatters, you can provide a list of formatters to the ReadAsAsyncmethod. Using a list of formatters is useful if you have a custom media-type formatter:
C#
var formatters = new List<MediaTypeFormatter>() {
    new MyCustomFormatter(),
    new JsonMediaTypeFormatter(),
    new XmlMediaTypeFormatter()
};
resp.Content.ReadAsAsync<IEnumerable<Product>>(formatters);
For more information, see Media Formatters in ASP.NET Web API 2

Sending a POST Request to Create a Resource

The following code sends a POST request that contains a Product instance in JSON format:
C#
static async Task<Uri> CreateProductAsync(Product product)
{
    HttpResponseMessage response = await client.PostAsJsonAsync(
        "api/products", product);
    response.EnsureSuccessStatusCode();

    // return URI of the created resource.
    return response.Headers.Location;
}
The PostAsJsonAsync method:
  • Serializes an object to JSON.
  • Sends the JSON payload in a POST request.
If the request succeeds:
  • It should return a 201 (Created) response.
  • The response should include the URL of the created resources in the Location header.

Sending a PUT Request to Update a Resource

The following code sends a PUT request to update a product:
C#
static async Task<Product> UpdateProductAsync(Product product)
{
    HttpResponseMessage response = await client.PutAsJsonAsync(
        $"api/products/{product.Id}", product);
    response.EnsureSuccessStatusCode();

    // Deserialize the updated product from the response body.
    product = await response.Content.ReadAsAsync<Product>();
    return product;
}
The PutAsJsonAsync method works like PostAsJsonAsync, except that it sends a PUT request instead of POST.

Sending a DELETE Request to Delete a Resource

The following code sends a DELETE request to delete a product:
C#
static async Task<HttpStatusCode> DeleteProductAsync(string id)
{
    HttpResponseMessage response = await client.DeleteAsync(
        $"api/products/{id}");
    return response.StatusCode;
}
Like GET, a DELETE request does not have a request body. You don't need to specify JSON or XML format with DELETE.

Test the sample

To test the client app:
  1. Download and run the server app. Download instructions. Verify the server app is working. For exaxmple, http://localhost:64195/api/products should return a list of products.
  2. Set the base URI for HTTP requests. Change the port number to the port used in the server app.
    C#
    static async Task RunAsync()
    {
        // Update port # in the following line.
        client.BaseAddress = new Uri("http://localhost:64195/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    
  3. Run the client app. The following output is produced:
    console
    Created at http://localhost:64195/api/products/4
    Name: Gizmo     Price: 100.0    Category: Widgets
    Updating price...
    Name: Gizmo     Price: 80.0     Category: Widgets
    Deleted (HTTP Status = 204)

Creating WCF REST Service

I have read many forum posts regarding WCF REST service creation and implementation but its difficult to understand for beginners, so to make it understandable, decided to write this article which shows step by step how to create WCF REST Service.

Prerequisites
To understand WCF REST service, you need to have at least beginner knowledge on WCF. If you are a beginner in WCF then please refer my following articles on c-sharpcorner for WCF.
  1. Introduction To WCF Endpoints
  2. Introduction to WCF Services
  3. Creating WCF Service
I hope you have read the preceding articles, now let us start with WCF REST from the definition.
What is WCF REST ?
REST stands for Representational state transfer which is a technique to communicate on cross platform application and exchange the data in JSON or XML format with the help of GET, POST, PUT, and DELETE methods of HTTP protocol.

Let us briefly understand about the HTTP methods which is most commonly used to create WCF REST service:
  • GET : Get the resource (Records) from particular source such as SQL database.
  • POST : Used to insert the records into the particular source such as SQL, Oracle database.
  • PUT : Used to modify the resource or records.
  • DELETE : Used to delete the specific resource or record from particular source.
I hope you understood the basics about REST concept. Now let us start creating WCF REST Service through a step by step approach.

Step 1: Create WCF Service.

To know how to create WCF service in depth, please refer my article creating WCF Service (link mentioned above). So, let's see a simple way to create WCF service:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2015".
  2. "File" - "New Project" - "C#" - WCF Service Application as in the following screenshot:

    WCF Service Application
  3. Provide the project name such as "PayMentRESTService " or another as you wish and specify the location.
  4. Now delete the auto created Interface and svc file which we will create a new one so beginners can understand it.

    delete the auto created Interface
  5. Now Add New WCF Service file and give name PayMentRESTService as in the following screenshot:

    Add New WCF Service file
I hope you have followed the same steps and and learned how to add WCF Service. After adding the Service file, the project solution explorer will be as in the following screenshot:

solution explorer

Step 2: Configure REST Service Template.

Now open the IPaymentService.cs Interface file and write the following code:
  1. [ServiceContract]    
  2. public interface IPayMentService    
  3. {    
  4.     [OperationContract]    
  5.     [WebInvoke(Method = "GET",UriTemplate = "/PayBill/{PayId}", BodyStyle = WebMessageBodyStyle.Wrapped,RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]    
  6.     string PayBill(string PayId);    
  7.        
  8. }   
Let us understand above REST Template using the following diagram 

Code

I hope you have understood the basic REST Template from the above image.

Step 3: Implement IPaymentService.cs interface methods into PaymentService.svc.cs file as.
  1. public class PayMentService : IPayMentService    
  2. {    
  3.     public string PayBill(string PayId)    
  4.     {    
  5.         return "Transaction having PayId " + PayId + " was successful";    
  6.     }    
  7. }  
Now our REST Service Code is ready. Let us complete the other steps.

Step 4: Configure End Points and Service Behaviors in web.config file as:

End Points and Service Behaviors configuration is very important in WCF Service. Many people say that it is complicated to configure, but trust me its much easier and simple with powerful intellisense. Lets open web.config file and find system.serviceModel tag and here are the steps:

Configure service behaviors as:

Configure service

Configure End points as:

Configure End points

While configuring Endpoints Tag automatically shows how to set and what contract because it shows the list of contract files (Interfaces) i.e. service contract. I hope you got a basic idea about the End points configuration. Soon I will post a video on this. After configuring Endpoints and service behaviors the system.serviceModel tag section of web.config file will be as in the following code snippet:
  1. <system.serviceModel>    
  2.     <behaviors>    
  3.       <serviceBehaviors >    
  4.         <behavior name="ServiceBehavior">    
  5.           <!-- To avoid disclosing metadata information, set the values below to false before deployment -->    
  6.           <serviceMetadata httpGetEnabled="true"/>    
  7.           <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->    
  8.           <serviceDebug includeExceptionDetailInFaults="false"/>    
  9.         </behavior>    
  10.       </serviceBehaviors>    
  11.     
  12.       <endpointBehaviors>    
  13.         <behavior name="web">    
  14.     
  15.           <webHttp/>    
  16.     
  17.         </behavior>    
  18.     
  19.       </endpointBehaviors>    
  20.     
  21.     </behaviors>    
  22.     <services>    
  23.       <service name="PayMentRESTService.PayMentService" behaviorConfiguration="ServiceBehavior">    
  24.     
  25.         <endpoint binding="webHttpBinding" contract="PayMentRESTService.IPayMentService" behaviorConfiguration="web">    
  26.     
  27.     
  28.         </endpoint>    
  29.       </service>    
  30.     
  31.     </services>    
  32.     
  33.     <serviceHostingEnvironment  multipleSiteBindingsEnabled="true" />    
  34.   </system.serviceModel>    
I hope you have done same configuration settings which I have done .

Step 5: Test REST Service.

Now our service is ready. Let's test it using REST client of mozilla browser as in the following:

Our REST Service URL will be http://localhost:64858/PayMentService.svc/PayBill/100

Test REST Service

In the above Response of WCF REST service you have seen that the status code is 200 OK. It means our service executed successfully. Let's confirm by switching to Response Body tab of REST client as in the following screenshot:

responce

From the preceding output its clear that our service executed successfully and as per configuration it returned JSON output. I hope from the preceding examples we have learned how to create WCF REST Service.

Design Patterns in .Net

Design patterns provide general solutions or flexible way to solve common design problems. This article provides a simple introduction regarding learning and understanding design patterns.

Before starting with design patters in .Net let's understand what is meant by design patterns and why is it useful in software programming.

What are Design Patterns in software development?
Design Patterns in the object oriented world is reusable solution to common software design problems that occur repeatedly in real-world application development. It is a template or description for how to solve problems that can be used in many situations.

"A pattern is a recurring solution to a problem in a context."

"Each pattern describes a problem that occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice." - Christopher Alexander, A Pattern Language.

Patterns are used by developers for their specific design to solve their problems. Pattern choice and usage among various design patterns depends on individual need and their problem. Design patterns are a very powerful tool for software developers. It is important to understand design patterns rather than memorizing their classes, methods and properties. It is also important to learn how to apply patterns to specific problems to get the desired result. This will be the required continuous practice for using and applying design patterns in day to day software development. First identify the software design problem then see how to address these problems using design patterns and determine the best suited design problem to solve the problem.

There are 23 design patterns, also known as Gang of Four (GoF) design patterns. The Gang of Four are the authors of the book, "Design Patterns: Elements of Reusable Object Oriented Software". These 23 patterns are grouped into three main categories based on their:

Creational Design Pattern
  1. Factory Method
  2. Abstract Factory
  3. Builder
  4. Prototype
  5. Singleton
Structural Design Patterns
  1. Adapter
  2. Bridge
  3. Composite
  4. Decorator
  5. Façade
  6. Flyweight
  7. Proxy
Behavioral Design Patterns
  1. Chain of Responsibility
  2. Command
  3. Interpreter
  4. Iterator
  5. Mediator
  6. Memento
  7. Observer
  8. State
  9. Strategy
  10. Visitor
  11. Template Method
In this article, we are learning and understanding Creational Design Patterns in detail including UML diagram, template source code and a real-world example in C#.

Creational Design Patterns provide ways to instantiate a single object or group of related objects. These patterns deal with the process of object creation in such way that they are separated from their implementing system. That provides more flexibility in deciding which object needs to be created or instantiated for a given scenario. There are the following five such patterns.

1. Abstract Factory 
Creates a set of related objects or dependent objects. The "family" of objects created by the factory is determined at run-time depending on the selection of concrete factory classes.

An abstract factory pattern acts as a super-factory that creates other factories. An abstract factory interface is responsible for creating a set of related objects or dependent objects without specifying their concrete classes.
 
The UML class diagram below describes an implementation of the abstract factory design pattern.

Design-Patterns-1.jpg

The classes,objects and interfaces used in the above UML diagram is described below.
  1. Client
    This class uses the Abstract Factory and Abstract Product interfaces to crreate a family of related objects.
     
  2. Abstract Factory:
    This is an interface that creates abstract products.
     
  3. Abstract Product:
    This is an interface that declares a type of products.
     
  4. Concrete Factory 
    This is a class that implements the abstract factory interface to create concrete products.
     
  5. Concrete Product 
    This is a class that implements the abstract product interface to create products.
The following code shows the basic template code of the abstract factory design pattern implemented using C#:

Design-Patterns-2.jpg
Design-Patterns-3.jpg  
In the above abstract factory design pattern the source code template client has two private fields that  hold the instances of abstract product classes. These objects will be accessed by inheriting their base class interface. When the client is instantiated, a concrete factory object is passed to its constructor and populate private fields of the client with appropriate data or values.

The Abstractfactory is a base class for concrete factory classes that generate or create a set of related objects. This base class contains a methods definition for each type of object that will be instantiated. The base class is declared as Abstract so that it can be inherited by other concrete factory subclasses.

The concrete factory classes are inheriting from the Abstractfactory class and overrides the method of the base class to generate a set of related objects required by the client. There can be a specifeid number of concrete factory classes depending on the software or application requirements.
Abstractproduct is a base class for the types of objects that the factory class can create. There should be one base type for every distinct type of product required by the client.

The concrete product classes are inheriting from Abstractproduct class. Each class contains specific functionality. Objects of these classes are generated by abstractfactory classes to populate the client.

Real-world example of Abstract factory design pattern using C#
As an example, consider a system that does the packaging and delivery of items for a web-based store. The company delivers two types of products. The first is a standard product that is placed in a box and delivered through the post with a simple label. The second is a delicate item that requires shock-proof packaging and is delivered via a courier.

In this situation, there are two types of objects required, a packaging object and a delivery documentation object. We could use two factories to generate these related objects. The one factory will be responsible for creating packaging and other delivery objects for standard parcels. The second will be responsible for creating packaging and delivery objects for delicate parcels. 

Class Client

Design-Patterns-4.jpg

Design-Patterns-5.jpg

AbstractFactory Patterns Form

Design-Patterns-6.jpg

Output
Design-Patterns-7.jpg
 
The example code above creates two client objects, each passing to a different type of factory constructor. Types of generated objects are accessed through the client properties.  
Note
While studying abstract factory patterns, one question is, what are concrete classes? So I Google searched for that and the following is the answer to my question.

A concrete class is nothing but a normal class that has all basic class features, like variables, methods, constructors, and so on.

We can create an instance of the class in other classes.

 2. Singleton
The Singleton design pattern is one of the simplest design patterns. This pattern ensures that the class has only one instance and provides a global point of access to it. The pattern ensures that only one object of a specific class is ever created. All further references to objects of the singleton class refer to the same underlying instance.

There are situations in a project where we want only one instance of the object to be created and shared among the clients. No client can create an instance from outside. It is more appropriate than creating a global variable since this may be copied and leads to multiple access points. 

The UML class diagram below describes an implementation of the abstract factory design pattern:

Design-Patterns-8.jpg

In the singleton patterns UML diagram above the "GetInstace" method should be declared as static. This method returns a single instance held in a private "instance" variable.  In the singleton pattern, all the methods and instances are defined as static. The static keyword ensures that only one instance of the object is created and you can call methods of the class without creating an object.

The constructor of a class is marked as private. This prevents any external classes from creating new instances. The class is also sealed to prevent inheritance, that could lead to sub classing that breaks the singleton rules.
 
The following code shows the basic template code of the singleton design pattern implemented using C#.
 
The eager initialization of singleton pattern:

Design-Patterns-9.jpg

Lazy initialization of singleton pattern:

Design-Patterns-10.jpg
 
Thread-safe (Double-checked Locking) initialization of singleton pattern:

Design-Patterns-11.jpg
 
The code above shows the "lockThis" object and the use of locking within the "GetInstance" method. Since  programs can be multithreaded, it is possible that two threads could request the singleton before the instance variable is initialized. By locking the dummy "lockThis" variable, all other threads will be blocked. This means that two threads will not be able to simultaneously create their own copies of the object.
 
Real-world example of Abstract factory design pattern using C#.net :
I am trying to apply this pattern in my application where I want to maintain an application state for user login information and any other specific information that is required to be instantiated only once and held in only one instance.
 
Class ApplicationState :

Design-Patterns-12.jpg

Singleton pattern form:

Design-Patterns-13.jpg

Output

Design-Patterns-14.jpg

The preceding sample code creates two new variables and assigns the return value of the GetState method to each. They are then compared to check that they both contain the same values and a reference to the same object.