Friday, 17 June 2016

Save image in database and render image from database

Firstly, We can save image in database as a byte array. Here, We will create a webapi which accept image as a base64 string. And further, we will convert the base64 string image into byte array and save it in mysql database. 

Datatype for MYSQL to save byte array is LONGBLOB.

Example


Properties class

public class UserInfo
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    public string UserImage { get; set; }//Base64 string

    public string ImageMimeType { get; set; }
}


API controller

[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    [HttpGet]
    [Route("SaveUserInfo")]
    [AppAuthorization]
    public IHttpActionResult SaveUserInfo(UserInfo model)
    {
        if (model != null)
        {
            try
            {
                if (ModelState.IsValid)
                {                    
                    var res = _userRepository.InsertUserInfo(model);
                    return Ok(res);
                }
                else
                {
                    return Content<object>(HttpStatusCode.InternalServerError, new { Status = false, Message = "Invalid model." });
                }
            }
            catch (Exception ex)
            {
                return Content<object>(HttpStatusCode.InternalServerError, new { Status = false, Message = ex.Message });
            }
        }
        else
        {
            return Content<object>(HttpStatusCode.InternalServerError, new { Status = false, Message = "Please provide model." });
        }
    }  
}


Business logic class

public class UserRepository : IUserRepository
{
    Dictionary<string, object> _sqlParams;

    public object InsertUserInfo(UserInfo model)
    {
       if (model.UserPic != null && model.UserPic != "")
       {
           _sqlParams = new Dictionary<string, object>();
           _sqlParams["FirstName "] = model.FirstName;
           _sqlParams["LastName "] = model.LastName;
           _sqlParams["Email"] = model.Email;
           _sqlParams["ImageBytes"] = Convert.FromBase64String(model.UserImage);
           _sqlParams["ImageName"] = model.FirstName;
           _sqlParams["MimeType"] = model.PicMimeType;     

          long userId = DBUtility.ExecuteInsertSql(SqlQueryConstants.InsertUserInfo, _sqlParams);

           return new {Status = true, Data = http://www.url.com:8098/UserImage/" + userId };//This url will render image
        }
        else
        {
           return new {Status = false, Message = "Please provide your image." };
        }
     }
}

Now, (http://www.url.com/Images/UserImage/" + userId) user will get this url to render the user image. 
This url basically hits the image controller and userImage action which will read image byte array from database and render image.


Image Controller

[AllowCrossSiteJsonAttribute]
public class ImagesController : Controller
{
   [Route("UserImage/{userId}")]
   public ActionResult UserImage(int userId)
   {
      var user = _userRepository.GetUserInfo(userId);//Get user info
      return new FileContentResult(user.ImageBytes, user.MimeType);          
   }
}




Tuesday, 7 June 2016

MVC Authorization filter

MVC supports 4 types of filter

  • Authorization
  • Action
  • Result
  • Exception

Authorization filter
It is executed after the user is authenticated in MVC life-cycle. It is basically used to authorize user from resources of your application. You can create your own custom authorization filter. A class which extend AuthorisationFilterAttribute class and overrides its OnAuthorization() method is authorization filter.

Example - Suppose you need to access user data from WEB API by providing authorization token. 

Controller
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    [HttpGet]
    [Route("GetUserAppProfile")]
    [AppAuthorization]
    public IHttpActionResult GetUserProfile()
    {
        try
        {
            long userId = Convert.ToInt64(Request.Headers.GetValues("UserId").FirstOrDefault());
            var res = _userRepository.GetUserAppProfile(userId);
            return Ok(res);
        }
        catch (Exception ex)
        {
            return Content<object>(HttpStatusCode.InternalServerError, new { Status = false, Message = ex.Message });
        }
    }
}

Custom filer
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!actionContext.Request.Headers.Contains("AuthToken"))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Status = false, Message = "Token is missing" });
            }
            else
            {
                string authToken = actionContext.Request.Headers.GetValues("AuthToken").FirstOrDefault();

                if (string.IsNullOrEmpty(authToken))

                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Status = false, Message = "Token is missing" });
                }
                else
                {
                    long userId = userService.AuthorizeAppUser(authToken);

                    if (userId != null)

                    {
                        actionContext.Request.Headers.Add("UserId", userId.ToString());
                    }
                    else
                    {
                        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Status = false, Message = "Invalid token" });
                    }
                }               
            }
            base.OnAuthorization(actionContext);
        }//End
    }

Before execution of action method, This custom authorization filter will execute and check for authentication token in header if token doesn't exist. It will straight forward return the status and message. And will not execute the action method.

Saturday, 4 June 2016

C# Classes And Objects

C# classes, It is basically a wrapper or a construct which group together methods, variables or properties. And Object is instance of class. We can create as many instance of class with new keyword. Object has attributes and behavior and these attribute and behavior is defined by a class.

For example : - Suppose you have a TV(Television). It is an object and its size, color is its attributes and its functions like volume up down or number of channels is its behavior. 
Same in case of c# classes and object. Classes instance is an object and its attribute and behaviour is defined by a class.

Class A
{
   int a= 4;
   int b=5;
   int c=0;
   public void Add()
  {
     c= a+b;
  }
   main//Main method
  {
     A instance1 = new A(); //Here can create as many as objects/instance you need
     A instance2 = new A();
  }
}




Saturday, 8 August 2015

How to count repeated characters in an array

using System;

namespace SequenceCount
{
    class Program
    {
        // to count repeated characters in an array
        private void CountRepeatedCharacters()
        {
            string word = "aaabbcccd";
            char[] characters = word.ToCharArray();
            char startingCharacter = characters[0];
            byte count = 1;
            string output = string.Empty;

            for (int i = 1; i < characters.Length; i++)
            {
                if (characters[i] == startingCharacter)
                {
                    count++;
                }

                else
                {
                    output = output + startingCharacter + count.ToString();
                    // set the current character to startingCharacter and set count to 1
                    startingCharacter = characters[i];
                    count = 1;
                }
            }

            output = output + startingCharacter + count.ToString();
            Console.WriteLine("Output will be : " + output);
            Console.ReadLine();
        }

        static void Main(string[] args)
        {
            Program objProgram = new Program();
            objProgram.CountRepeatedCharacters();
        }
    }
}

Sunday, 26 July 2015

How to know that the Page is Post Back or not without using IsPostBack Property

Current Request Type Property is a way to identify current request is post back request or not.

Current context request object have property named RequestType which can be checked to know that is the page posted back to server or not. For example :-

        if (Request.RequestType == "GET") 
         {
            // Call when page loading first time
            // Equal to if (!IsPostBack) property
         }

        if (Request.RequestType == "POST") 
         {
            // Call when page loading second or higher time
            // Equal to if (IsPostBack) property
         }

This is an alternate way of isPostBack mechanism.


GET :- When user requests to a web page by typing the URL in web browser, open a window through JavaScript (window.open ..) or clicking in hyperlink its called Get request or first time request.


POST :- When user requests to a web page by clicking in button (input type submit) or submit a form through JavaScript to the server (form.submit() function in JavaScript) its called Post request or second / higher request.

That’s it!!…..Happy Programming...

Sunday, 7 June 2015

How to create instance of an interface

In this article, i am going to show what is the way to create an instance of a interface. Actually, there is no direct way to create an instance of a interface. This is because they are incomplete (like templates) and creation of an object is completely meaningless here. If we want to do something like that, we must create an instance of class / type that implements that interface. For Example :- ILIST(T) interface provided in System.Collections.Generic namespace showing the below error while i was trying the same.


As i told you before, we must have to use it as a variable which points to a class which implements that interface to workaround this kind of problem. Something like that:-


Here, List(T) is a class which implementing ILIST(T) interface. Please remember that, ILIST(T) and ILIST are not same, the only difference is that first one is generic in type and we can pass any type in place of T. 

That’s it!!…..Happy Programming...