Friday, 8 April 2016

Allow Cross-Origin Requests in Web API

Let’s see how to allow web API to be called from JQuery. 

Browser prevents a web page from making AJAX requests to another domain. This is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site.

But What will do if you create a web API to be called by other websites. You have to allow then to call your API.  Cross Origin Resource Sharing (CORS) allows a server to come over this policy. You can allow specific origins to access your web API.  

Let’s understand with an example.

Let’s create a Web API first :  I am not going to spoon feed you to create web API. I hope you know how to create web API application. Great.. 

Let’s take a APIController :

      using System.Web.Http.Cors;
[EnableCors(origins: "http://localhost:12081", headers: "*", methods: "*")]
public class ValuesController : ApiController
      {        
         public IEnumerable<string> Get()
         {
            return new string[] { "value1""value2" };
         }       
 }

Ooops, what is EnableCors ?
You have to install a nuget package to get this. Write below command in package manager console :
Install-Package Microsoft.AspNet.WebApi.Cors

 Next step to register CORS from global.asax :

         public static void Register(HttpConfiguration config)
        {
            config.EnableCors();                    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

Yeah, Your web API is ready to be accessed from origin ‘http://localhost:12081’.

Do I have any option to allow multiple origin ?  
  
Of course Yes.    You can set number of origin by comma separated value like http://localhost:12081http://www.heros.com, http://www.xyss.com’. Or you can allow all origin by putting ‘*

[EnableCors(origins: "*", headers: "*", methods: "*")]

Note : Don’t include forward slash at the end of url. E.g ‘http://localhost:12081/


Now call API from JQuery :
 jQuery.ajax({
            type: "GET",
            url: 'http://192.168.1.118:85/api/values',                        
            success: function (data) {
                alert(JSON.stringify(data));
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("error");
            }
        });


Hooray!! it’s working...

Tuesday, 1 March 2016

Validate Data annotation attribute from C#



Validate Data annotation attribute from C# manually.

Create validation method :

public static IEnumerable<string> Validate(params object[] objects)
{
   foreach (var item in objects)
   {               
     PropertyInfo[] properties = item.GetType().GetProperties();

     foreach (var propertyInfo in properties)
     {
       object[] customAttributes = propertyInfo.GetCustomAttributes(
typeof(ValidationAttribute),
inherit: true);

       foreach (var customAttribute in customAttributes)
       {
         var validationAttribute = (ValidationAttribute)customAttribute;

         bool isValid = validationAttribute.IsValid(propertyInfo.GetValue(item,     
                                                   BindingFlags.GetProperty,
   null,
   null,
   null));

         if (!isValid)
         {
           yield return validationAttribute.ErrorMessage;
         }
       }
     }
   }
}

Add DTO class :

    public class TestClass1
    {
        [Required(ErrorMessage = "This field is required")]
        [EmailAddress(ErrorMessage = "Please enter valid email address")]
        public string Email { get; set; }

        [Range(0, 10, ErrorMessage = "Value between 0 to 10")]
        public int Num1 { get; set; }

        public TestClass2 TestClass2 { get; set; }
    }

    public class TestClass2
    {
        [Required(ErrorMessage = "FirstName is required")]
        public string FirstName { get; set; }
    }

Now use validation method in real code :

TestClass1 tc = new TestClass1();
            tc.Email = "AP@"; // Please enter valid email address
            tc.Num1 = 50; // Value between 0 to 10
            tc.TestClass2 = new TestClass2(); // FirstName is required

            var messages =  Validate(tc, tc.TestClass2);
            StringBuilder sb = new StringBuilder();
            foreach (var item in messages)
            {
                sb.AppendLine(item);
            }

Monday, 29 February 2016

Convert UTC time to local time by timezones




Convert UTC time to specific time zone’s time

// list of timezones
var timezones = TimeZoneInfo.GetSystemTimeZones();

// choose your timezone to convert time
var convertedDateTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow,
                                                                               TimeZoneInfo.Utc, 
                                                  TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));

// choose your timezone time to utc time
var convertedDateTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow,
                                         TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"),
                                                                               TimeZoneInfo.Utc);