April 28, 2016

C# Tips



String.Equals(stringA, stringB, StringComparison.CurrentCultureIgnoreCase)

Vs
string pageTitle = suppliedTitle ?? "Default Title"

-----------------------------------------------------------------------------------------------------
MyClass myObject = (MyClass) obj; throw a class InvalidCastException exception. 
Vs
MyClass myObject = obj as MyClass; The second will return null if obj isn't a MyClass

-----------------------------------------------------------------------------------------------------
Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}  
Vs
Employee emp = new Employee();  
emp.Name = "John Smith";  
emp.StartDate = DateTime.Now(); 


-----------------------------------------------------------------------------------------------------

class ExtensionMethods2  
{  
   static void Main()  
   {  
      int[] ints = { 10, 45, 15, 39, 21, 26 };  
      var result = ints.OrderBy(g => g);  
      foreach (var i in result)  
      {  
         System.Console.Write(i + " ");  
      }  
   }  
}  
  
//Output: 10 15 21 26 39 45  

-----------------------------------------------------------------------------------------------------
if(dictionary.ContainsKey(key))  
{  
   value = dictionary[key];  
}  


if(dictionary.TryGetValue(key, out value))  

{ ... } 
-----------------------------------------------------------------------------------------------------

April 25, 2016

ASP.NET Web API

ASP.NET Web API Versions:
Web API Version
Supported .NET Framework
Coincides with
Web API 1.0
.NET Framework 4.0
ASP.NET MVC 4
Web API 2
.NET Framework 4.5
ASP.NET MVC 5

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 is Web API?  API is some kind of interface which has a set of functions that allow programmers to access specific features or data of an application, operating system or other services.
  • Create Web API Project
    • Web API with MVC Project
    • Stand-alone Web API Project
  • Test Web API – Fidder, postman
1.       It must be derived from System.Web.Http.ApiController class.
2.       It can be created under any folder in the project's root folder. However, it is recommended to create controller classes in the Controllers folder as per the convention.
3.       Action method name can be the same as HTTP verb name or it can start with HTTP verb with any suffix (case in-sensitive) or you can apply Http verb attributes to method.
4.       Return type of an action method can be any primitive or complex type.
  • Configure Web API  
  • Global.asax
    • GlobalConfiguration.Configure(WebApiConfig.Register)
  • WebApiConfig
public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

1.       Convention-based Routing
2.       Attribute Routing
1.       FromUri
2.       FromBody 
1.       Void
2.       Primitive type or Complex type
3.       HttpResponseMessage
4.       IHttpActionResult
1.       Media type specifies the format of the data as type/subtype
2.       Content-Type header attribute (Body)
3.       Accept Header attribute
Media Type Formatter Class
MIME Type
Description
JsonMediaTypeFormatter
application/json, text/json
Handles JSON format
XmlMediaTypeFormatter
application/xml, text/json
Handles XML format
FormUrlEncodedMediaTypeFormatter
application/x-www-form-urlencoded
Handles HTML form URL-encoded data
JQueryMvcFormUrlEncodedFormatter
application/x-www-form-urlencoded
Handles model-bound HTML form
URL-encoded data


Filter Type
Interface
Class
Description
Simple Filter
IFilter
-
Defines the methods that are used in a filter
Action Filter
IActionFilter
ActionFilterAttribute
Used to add extra logic before or after action methods execute.
Authentication Filter
IAuthenticationFilter
-
Used to force users or clients to be authenticated before action methods execute.
Authorization Filter
IAuthorizationFilter
AuthorizationFilterAttribute
Used to restrict access to action methods to specific users or groups.
Exception Filter
IExceptionFilter
ExceptionFilterAttribute
Used to handle all unhandled exception in Web API.
Override Filter
IOverrideFilter
-
Used to customize the behaviour of other filter for individual action method.


Difference between WCF and Web API and WCF REST and Web Service

Web Service
It is based on SOAP and return data in XML form.
It supports only HTTP protocol.
It is not open source but can be consumed by any client that understands xml.
It can be hosted only on IIS.
WCF
It is also based on SOAP and return data in XML form.
It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
The main issue with WCF is, its tedious and extensive configuration.
It is not open source but can be consumed by any client that understands xml.
It can be hosted with in the application or on IIS or using window service.

http://www.wcftutorial.net/Home.aspx

WCF Rest
To use WCF as WCF Rest service you have to enable webHttpBindings.
It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
It support XML, JSON and ATOM data format.
Web API
This is the new framework for building HTTP services with easy and simple way.
Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
Unlike WCF Rest service, it use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
It can be hosted within the application or on IIS.
It is light weight architecture and good for devices which have limited bandwidth like smart phones.
Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
To whom choose between WCF or WEB API
Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.
RestWebService
HttpGet
HttpPost
HtttpPut
HttpDelete