Thursday, May 31, 2018

HTTP Status Code

HTTP defines a list of status codes that can be returned from your service or web API and these status can help to client API to understand response and route or process it accordingly.

There are few series, which can tell us the high level meaning of HTTP status code
  • 2xx Success – this series of status code tells that request is successfully accepted and processed
  • 3xx Redirection - this series of status code tells that client must take additional action to complete the request.
  • 4xx Client errors - this series of status code tells that there is error due to the client
  • 5xx Server errors - this series of status code tells that server failed to fulfil a request
There are few important HTTP status codes

2xx Success
  • 200 OK - Response to a successful GET, PUT, PATCH or DELETE. Can also be used for a POST that doesn't result in a creation.
  • 201 Created - Response to a POST that results in a creation. Should be combined with a Location header pointing to the location of the new resource
  • 204 No Content - Response to a successful request that won't be returning a body (like a DELETE request)

3xx Redirection
  • 304 Not Modified - Used when HTTP caching headers are in play
  • 400 Bad Request - The request is malformed, such as if the body does not parse
  • 401 Unauthorized - When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser

4xx Client errors
  • 403 Forbidden - When authentication succeeded but authenticated user doesn't have access to the resource
  • 404 Not Found - When a non-existent resource is requested
  • 405 Method Not Allowed - When an HTTP method is being requested that isn't allowed for the authenticated user
  • 410 Gone - Indicates that the resource at this end point is no longer available. Useful as a blanket response for old API versions
  • 415 Unsupported Media Type - If incorrect content type was provided as part of the request
  • 422 Unprocessable Entity - Used for validation errors
  • 429 Too Many Requests - When a request is rejected due to rate limiting
  • 5xx Server errors
  • 500 Internal Server Error - A generic error message for unexpected error
  • 501 Not Implemented - The server either does not recognize the request method, or it lacks the ability to fulfil the request. Usually this implies future availability (e.g., a new feature of a web-service API)

For more information, visit on Wikipedia url

Thanks for visiting !!

Wednesday, May 30, 2018

ASP.NET Web API Caching


In this blog, we will discuss about Web API caching and memory caching and how it improve the overall performance of Web API. Cached data save database call or external call to process the future request.


Web API doesn’t support the output caching and we have to store the data in local memory or in database.

ASP.NET Web API Caching
ASP.NET Web API Caching

 
Here is code sample to implement memory caching in web api.

Microsoft provides the System.Runtime.Caching library for memory caching.

Add a reference above lib and here is a Helper Class to store data or get data from cached memory

using System;

using System.Runtime.Caching;

public static class MemoryCacher

{

    public static object GetValue(string key)

    {

        MemoryCache memoryCache = MemoryCache.Default;

        return memoryCache.Get(key);

    }


    public static bool Add(string key, object value, DateTimeOffset absExpiration)

    {

        MemoryCache memoryCache = MemoryCache.Default;

        return memoryCache.Add(key, value, absExpiration);

    }


    public static void Delete(string key)

    {

        MemoryCache memoryCache = MemoryCache.Default;

        if (memoryCache.Contains(key))

        {

            memoryCache.Remove(key);

        }

    }

}


Add data in cache memory:
MemoryCacher.Add(“Key”,Object, DateTimeOffset.UtcNow.AddYears(1))


Get data from cache memory:
MemoryCacher.Get(“Key”)

ASP.NET Web API provides the filters, that you can use to add extra logic before or after action executes, so above caching data logic you can use inside filter to cache web api response.

Here is an example how to create action filter that cache web api response.

  public class WebAPICacheAttribute : ActionFilterAttribute

    {

        public int Duration { getset; }

        private bool CacheEnabled = false;


      public WebAPICacheAttribute(int _duration, bool _cacheEnabled)
        {

            Duration = _duration;

            CacheEnabled = _cacheEnabled;

        }

        public override void OnActionExecuting(HttpActionContext context)

        {

            if (CacheEnabled)

            {

                if (context != null)

                {                   
                        //generate cache key from HTTP request URI and Header

                        string _cachekey = string.Join(":"new string[]

                        {

                            context.Request.RequestUri.OriginalString,

                            context.Request.Headers.Accept.FirstOrDefault().ToString(),

                        });                      


                        // Check Key exists

                        if (MemoryCacher.Contains(_cachekey))

                        {    


                            var val = (string)MemoryCacher.GetValue(_cachekey);

                            if (val != null)

                            {

                                context.Response = context.Request.CreateResponse();

                                context.Response.Content = new StringContent(val);

                                var contenttype = (MediaTypeHeaderValue)MemoryCacher.GetValue(_cachekey +

                            ":response-ct");

                                if (contenttype == null)

                                    contenttype = new MediaTypeHeaderValue(_cachekey.Split(':')[1]);

                                context.Response.Content.Headers.ContentType = contenttype;

                                return;

                            }

                        }                    
                }             

            }

        }



        public override void OnActionExecuted(HttpActionExecutedContext context)

        {

          

                if (CacheEnabled)

                {

                    if (WebApiCache != null)

                    {

                        string _cachekey = string.Join(":"new string[]

                        {

                            context.Request.RequestUri.OriginalString,

                            context.Request.Headers.Accept.FirstOrDefault().ToString(),

                        });


                    if (context.Response != null && context.Response.Content != null)

                        {

                           string body = context.Response.Content.ReadAsStringAsync().Result;


                         if (MemoryCacher.Contains(_cachekey))

                            {

                        MemoryCacher.Add(_cachekey, body, DateTime.Now.AddSeconds(Duration));

                                MemoryCacher.Add(_cachekey + ":response-ct",

                                context.Response.Content.Headers.ContentType,

                                DateTime.Now.AddSeconds(_timespan));

                            }

                            else

                            {

                        MemoryCacher.Add(_cachekey, body, DateTime.Now.AddSeconds(Duration));

                                MemoryCacher.Add(_cachekey + ":response-ct",

                                context.Response.Content.Headers.ContentType,

                                DateTime.Now.AddSeconds(Duration));

                            }

                        }

                    }

                }                    

        }


    }


Now you can use WebAPICache action filter on GetProject Action to cache Project data and if the client will send the same request, the Web API will not call to data repository layer to get project records, it will get from cache
Web API Controller:

public class ProjectApiController : ApiController

{
 [HttpGet]

        [Route("api/Project/{projectId:int}")]

        [WebAPICache(_duration:3600,_cacheEnabled: true)]

        public Project GetProject(int projectId)

        {

            return Repository.GetProperty(projectId);

 }
  }

 Other Web API related topics: 
·        ASP.NET Web API Caching

Thanks for visiting!!

ASP.NET MVC how to disable Caching

ASP.NET MVC Output Cache enables you to cache the action result content by a MVC controller action. By default MVC Output cache is enabled. So for this you don’t need to do anything, if client will send same request, browser will not forward request to MVC controller and it returns previous cached result but in few scenario, you don’t want to cache controller action result and want to disabled output caching for specific controller action.

You can use [OutputCache] attribute to disabled or enabled the browser caching for specific action or all action in controller.

·         Action Level: 
Disable output caching for specific action only

public class HomeController : Controller

{
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

public ActionResult Index(ParametersData parameters)

{

   return View();

}
}

·         Controller Level:
Disable output caching for all actions in controller

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class HomeController : Controller

{
public ActionResult Index(ParametersData parameters)

{

   return View();

}
}

·         Global/Application Level
You can a add a action filer in FilterConfig.cs for disabling caching for application controllers

public class FilterConfig

    {

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)

        {

            filters.Add(new CustomHandleErrorAttribute());

            filters.Add(new OutputCacheAttribute

            {

                VaryByParam = "*",

                Duration = 0,

                NoStore = true,

            });

        }

    }

Other ASP.NET MVC related topics:
Thanks for visiting!! 

WCF : Differences between Buffered and Streamed Transfers

WCF supports the streamed or buffered mode to transfer the request /response message from client to server or vice versa

1.       Buffered Mode : 

WCF holds the entire message in local memory buffer until transfer is completed it means a receiver can read message once it is completed delivered.

WCF Configuration:
<basicHttpBinding>
<binding name="BasicHttpBindingService"  maxReceivedMessageSize="2147483647" maxBufferSize="2147483647"   transferMode="Buffered/>
</basicHttpBinding>

2.       Streamed Mode :

WCF hold only the message header only and it start transferring the small part of message body as stream and receive can start read the message, before it is completely delivered.

WCF Configuration:

<basicHttpBinding>
<binding name="BasicHttpBindingService"  maxReceivedMessageSize="2147483647"  transferMode="Streamed"
</basicHttpBinding>

Differences between Buffered and Streamed Transfers


                       Buffered
                       Streamed
client can process or read  the message once it is completely received
Client can start processing the data when it is partially received
Performance will be good when message size is small
Performance will be good when message size is larger(more than 64K)

Note :
  • By default, Streaming is disabled for all bindings
  • TCP, IPC and HTTP Binding support streaming transfer mode
  • For small size Message, by default transfer mode option is good but if message size is larger, you have to choose the streaming mode for better performance
  • No OutOfMemory exceptions anymore for larger size data processing , if you choose streaming mode
Thanks for Visiting!!

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...