Saturday, 26 October 2013

MVC - Interview Questions and Answers

What is MVC?
    MVC stands for Model View Controller. 
It divides an application into 3 component roles which is based on a framework methodology. 
These component roles are discussed briefly as follows: 

i) Models: These component roles are used to maintain the state which is persisted inside the Database. 

ii) Views: These component roles are used to display the user interface of the application, where this UI is created off of the model data. 

iii) Controllers: These component roles are used for various purposes like handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. 

Can we share a view across multiple controllers ?
            Yes, It is possible to share a view across multiple controllers by putting a view into the          shared folder. 

Return Type of Controller Action Method ?
i) ViewResult : It is used to return a webpage from an action method 
ii) PartialViewResult : It is used to send a section of a view to be rendered inside another view. 
iii) JavaScriptResult : It is used to return JavaScript code which will be executed in the user’s browser. 
iv) RedirectResult : Based on a URL, It is used to redirect to another controller and action method. 
v) ContentResult : It is an HTTP content type may be of text/plain. It is used to return a custom content type as a result of the action method. 
vi) JsonResult : It is used to return a message which is formatted as JSON. 
vii) FileResult : It is used to send binary output as the response. 
viii) EmptyResult : It returns nothing as the result.

The page lifecycle of an ASP.NET MVC page is explained as follows: 
i)                    Application Initialisation 
In this stage, the application starts up by running Global.asax’s Application_Start() method. 

ii) Routing 
Routing is a stand-alone component that matches incoming requests to IHttpHandlers by URL pattern. 
MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other IHttpHandlers configured in the Routes table. 

iii) Instantiate and Execute Controller 
At this stage, the active IControllerFactory supplies an IController instance. 
iv) Locate and invoke controller action 
At this stage, the controller invokes its relevant action method, which after further processing, calls RenderView(). 

v) Instantiate and render view 
At this stage, the IViewFactory supplies an IView, which pushes response data to the IHttpResponse object.

Difference Between ViewData, ViewBag and TempData
 A ViewData is a Dictionary to stored value from controller action and pass it to the View.
A ViewBag is a Collection of View Data , it is dynamic Value pass from controller action to view.        
A TempData is a Dictionary is used to pass the data between the Actions.
            

Tuesday, 22 October 2013

Create a Captcha and change it on refresh using IHttpHandler

What is Captcha ?
    Captcha is the information that is used to find whether in the end user an client is working or an robotic program is running. Few months back i tried a few samples to create program for automatic download from a FTP Server if any file exists. The thing is the automatic program is works fine download the file FTP server and save it to send as message to Phone. Now here i taken a Free domain which is providing a FTP server as Free. After testing the program i make a Windows service do that code to run after every 10 seconds to file the file in FTP to download. After successful in Testing i Left the computer as it is , When i came back evening to home and checked mail. I received a mail from that Domain Administration that "In the Past one hour more than 10,000 request hit my server due that my server got down i can't start the FTP Server Due to that currently we are disable the account for access." 

above scenario is the one of the robotic information to avoid this Captcha is used, make the user to enter the code which is seen is image and validate it .

Initially Captcha is made as clear image by stating characters alone , but some developers make than entry also automatic and make the request as Robotic , That's y today the captcha is very cricitical to understand so easily by giving background some diagonals, Change in Fonts for each character and difference in charcters shape etc.


How the developers make Captcha also in Robotic , Thats simple they read the image and Find the Letters Present inside the image and supply that to the textbox programmatically, how this can be done using OCR technology.

Read about OCR Click here OCR

In this example we are creating a Httphandler, Which will handle the request from the end user and return back the image to the user




How  create the Create generate the Random Numbers conver them in to image.

Handler Code :


using System;
using System.Web;
using System.Collections.Generic;
using System.Drawing;

public class GetImgTextHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        var CaptchaText = context.Request.QueryString["code"];


        HttpContext.Current.Application["Code"] = CaptchaText;
        if (CaptchaText != null)
        {
            List<Letter> letter = new List<Letter>();
            int TotalWidth = 0;
            int MaxHeight = 0;
            foreach (char c in CaptchaText)
            {
                var ltr = new Letter(c);
                letter.Add(ltr);
                int space = (new Random()).Next(5) + 1;
                ltr.space = space;
                System.Threading.Thread.Sleep(1);
                TotalWidth += ltr.LetterSize.Width + space;
                if (MaxHeight < ltr.LetterSize.Height)
                    MaxHeight = ltr.LetterSize.Height;
                System.Threading.Thread.Sleep(1);
            }
            const int HMargin = 5;
            const int VMargin = 3;

            Bitmap bmp = new Bitmap(TotalWidth + HMargin, MaxHeight + VMargin);
            var Grph = Graphics.FromImage(bmp);
            Grph.FillRectangle(new SolidBrush(Color.Lavender), 0, 0, bmp.Width, bmp.Height);
            Pixelate(ref bmp);
            Grph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            Grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            int xPos = HMargin;
            foreach (var ltr in letter)
            {
                Grph.DrawString(ltr.letter.ToString(), ltr.font, new SolidBrush(Color.White), xPos, VMargin);
                xPos += ltr.LetterSize.Width + ltr.space;
            }

            bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private void Pixelate(ref Bitmap bmp)
    {
        Color[] Colors = { Color.Gray, Color.Red, Color.Blue, Color.Olive };
        for (int i = 0; i < 200; i++)
        {
            var rnd = new Random(DateTime.Now.Millisecond);
            var grp = Graphics.FromImage(bmp);
            Image background = Image.FromFile(HttpContext.Current.Server.MapPath("~/images/captcha.gif"));
            grp.DrawImage(background, new Rectangle(0, 0, bmp.Width, bmp.Height));
        }
    }

}





public class Letter
{
    string[] ValidFonts = { "Segoe Script", "Century", "Eccentric Std", "Freestyle Script", "Viner Hand ITC" };
    public Letter(char c)
    {
        Random rnd = new Random();
        font = new Font(ValidFonts[rnd.Next(ValidFonts.Count() - 1)], rnd.Next(20) + 20, GraphicsUnit.Pixel);
        letter = c;
    }
    public Font font
    {
        get;
        private set;
    }
    public Size LetterSize
    {
        get
        {
            var Bmp = new Bitmap(1, 1);
            var Grph = Graphics.FromImage(Bmp);
            return Grph.MeasureString(letter.ToString(), font).ToSize();
        }
    }
    public char letter
    {
        get;
        private set;
    }
    public int space
    {
        get;
        set;
    }

}


Code in Html :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.9.1.js"></script>
    <script>


        function Change() {
            var img = document.getElementById("captcha");
            var randomnumber = Math.random().toString();
            var code = randomnumber.substring(3, 9);
            img.src = "GetImgTextHandler.ashx?code=" + code;


        }

      
 $(document).ready(function () {

            var img = document.getElementById("captcha");
            var randomnumber = Math.random().toString();
            var code = randomnumber.substring(3, 9);
            img.src = "GetImgTextHandler.ashx?code=" + code;



        });
    </script>
</head>
<body>
<fieldset style="width:300px" align="center">
<legend>Generate Captcha</legend>
 
  <table>
 
  <tr><td></td><td> <img src="" id="captcha" height="35px" width="155px" /> <a href="#" onclick="Change()" >change</a></td></tr>
  <tr><td> Enter Code : </td><td><input type="text" name="txt" /></td></tr>
  </table>

 
</fieldset>
         


</body>
</html>




I hope From this article you can learn how to create your own Captcha using the HttpHandler.



Sunday, 20 October 2013

Call a WebService using Javascript with complex return Type.

In this article we are going to see how to call a WebService using Javascript and get the result from the service which is a complex type Employee.

complex Return Type :

Create a Form Which will get the employee name from the textbox and pass as parameter to the Web Service. Web Service return a Complex Employee object which is unknown to javascript to identitfy.
Javascript knows only as it is a object.

Javascript :

 Now we are going to initialize a correct object for the XMLHTTPRequest then form the Url from the Page.ResolveUrl method which will resolve the path of the web service present inside the project.
then Call the method open from the XmlHttp which have to pass the url and mention the Post as method

Set the Request Header "Content-Type" as "Json" ,Use the Send Method to send the Request if any parameter is need to send then send as parameter inside the Send Method in Json format.

Json Format :

{
"employees": [
{ "firstName":"Purushoth" , "lastName":"Kumar" }, 
{ "firstName":"Anna" , "lastName":"Larsen" }, 
{ "firstName":"Suresh" , "lastName":"Kanna" }
]
}

Output Form:


Result :





Javascript :


<script type="text/javascript" language="javascript">
        function Call() {
            var XmlHttp = null;
            if (window.XMLHttpRequest) {
                XmlHttp = new XMLHttpRequest();
            }
            else if (window.ActiveXObject) {
                if (new ActiveXObject("Microsoft.XMLHTTP")) {
                    XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    else
                    {
                        XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                    }           
            }

                var url = '<%= Page.ResolveUrl("~/Calc.asmx/Hello") %>';
                  url = url+ '?rnd='+Math.random();
               
            XmlHttp.open("POST", url, false);
            XmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            XmlHttp.send('{"name":"' + document.getElementById("txt").value + '"}');
            var reply = XmlHttp.responseText;
            var value = eval('(' + reply + ')');
            alert(value.d.Id +' :'+  value.d.Name);

        }
    </script>



Aspx Code:
<body>
    <form id="form1" runat="server">
    <div style="vertical-align:top" align="center">
    <fieldset align="center" style="width:300Px">
    <legend>Employee Form</legend>
    Name :
    <input name="txt" id="txt" type="text"" />
    <a  href="javascript:Call()">Async Call</a>
    </fieldset>
    </div>
    </form>
</body>


Service Code :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebApplication7
{
    /// <summary>
    /// Summary description for Calc
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class Calc : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public Employee Hello(string name)
        {
            return new Employee() { Id = 1, Name = name };
        }
    }

    public class Employee
    {
        public string Name { set; get; }

        public int Id { set; get; }
    }
}




From this article you can learn how to call a web service using Javascript and read the value from the return value of service even though it is an object type .

WCF - Create a Publisher and Subscriber model by various Cricket notification from Service to client.




What is Publisher and Subscriber model ?
   Publisher is a term which will publish the content to the client that who are subscribed, Subscriber's are the client who can subscribe the notifications.They are two ways you can get the changed data from server by Pulling and Pushing. 

Pulling Method :
                Pulling is the method , where client will get the data from server after a consecutive interval . For example in a website state the status of cricket match, What they do is Pulling method after a 10 sec browser hit the server and get the latest changes from the server. This method will not suit for all notification because if we are going to notify a Football match what will happen goal will put by each team after a half an hour sometimes more than one hour. For this scenario consider each and every 10 seconds if browser hit the server resources cost increases and makes server slow to perform. how to avoid this we can make a Pushing method

Pushing Method : 
              Pushing Method, In this method server will push the change data to the all clients which are connected  and subscribed the notifications.

To Implement the Publisher and Subscriber model we are going to use a WCF with an example of Cricket Match.

Example : Consider a Cricket match going to held we need a notification from the Server with following conditions

1.   Wicket
2.   Five Over Once 
3.   Fifty Runs Once

The beauty of this example we are going to create a single instance for same Client Request even though he request for many times we uses the same single instance that are created before.[singleton service]

1. At the which stage uses click notification , it starts notify the user to notify the update to client.
2. Three options we have on which type we have to notify on every wicket it will notify if the subscriber subscribe the activate.
3. If we close the client and again open the client give the request of notification it will notifies the latest update.
4. wsDualHttpBinding which makes the dual communication from server to client for binding.

Client open and click the following three buttons and get the notifies.





Close the Client and again the launch it and click the notifies button , you can see the latest update is notifies.


See the second screen that from the 8th wicket it s get notified.

Service Code :

Contract :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace CricInfoService
{
    public enum NotifyMode
    {
        Wicket,
        Over,
        FiveOverOnce,
        Runs,
        FiftyRunsOnce
    }

    [ServiceContract(CallbackContract=typeof(IClientCallback))]
    interface ICricketService
    {
        [OperationContract]
        bool GetNotification(NotifyMode mode,string username);

        [OperationContract(IsOneWay=true)]
        void GetNotify(NotifyMode mode, string username);
    }

    public interface IClientCallback
    {      
        [OperationContract(IsOneWay=true)]
        void AsyncNotifyMessage(string message);
    }

}


 Service : InstanceContextMode is single which specifies the singleton

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace CricInfoService
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class CricketService:ICricketService
    {
        private static int _wicket = 0;
        private static int _run = 0;
        private static double _over = 0;
        static Random rand = new Random();

        static int Wicket
        {
            set {
                if (!value.Equals(_wicket))
                {
                    _wicket = value;
                    SendNotifyToClient(NotifyMode.Wicket);
                }
            }
            get { return _wicket; }
        }

        static int Run
        {
            set {

                if (!value.Equals(_run))
                {
                    _run = value;
                    if (_run % 50 == 0 )
                    {
                        SendNotifyToClient(NotifyMode.FiftyRunsOnce);
                    }
                 
                }           
            }
            get { return _run; }
        }

        static double Over
        {
            set
            {
                if (!value.Equals(_over))
                {
                    _over = value;

                    int whole =Convert.ToInt32(Math.Truncate(_over));
                       
                    if(_over - whole >= 0.6)
                    {
                        _over = Math.Ceiling(_over);
                    }
                                                
                    if (_over % 5 == 0)
                    {
                        SendNotifyToClient(NotifyMode.FiveOverOnce);
                    }
                }
            }
            get { return _over; }
        }

        public class CricketData
        {
            public  OperationContext CricketContext{set;get;}

            public NotifyMode Mode {set;get;}

            public string UserName {set;get;}           

        }

        static List<CricketData> notifylist = null;

        public CricketService()
        {
            notifylist = new List<CricketData>();
            System.Threading.Thread th = new System.Threading.Thread(Publisher);
            th.Start();
        }

        public bool GetNotification(NotifyMode mode, string username)
        {
            try
            {
                if (mode == NotifyMode.Wicket || mode == NotifyMode.FiveOverOnce || mode == NotifyMode.FiftyRunsOnce)
                {
                    notifylist.Add(new CricketData()
                    {
                        CricketContext= OperationContext.Current,
                        Mode=mode,
                        UserName=username
                    });
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }

        public void GetNotify(NotifyMode mode, string username)
        {
            try
            {
                if (mode == NotifyMode.Wicket || mode == NotifyMode.FiveOverOnce || mode ==                                NotifyMode.FiftyRunsOnce)
                {
                    notifylist.Add(new CricketData()
                    {
                        CricketContext = OperationContext.Current,
                        Mode = mode,
                        UserName = username
                    });                   
                }            
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }

        void Publisher()
        {
            DateTime start = DateTime.Now;
            DateTime Modified =DateTime.Now;

           DateTime wt = DateTime.Now.AddMinutes(NotifySecond(NotifyMode.Wicket));           

            while (true)
            {
                int now = DateTime.Now.Minute;

                if(Wicket<=10)
                    if (wt.Minute == now)
                    {
                        Wicket++;                       
                        wt = wt.AddMinutes(NotifySecond(NotifyMode.Wicket));
                    }
                    else
                    {
                        if((DateTime.Now - Modified).Seconds > 6)
                        {
                            Over += 0.1;
                            Run += 1;
                            Modified = DateTime.Now;
                        }                      
                    }              

                if (Wicket > 10)                                   
                    break;
            }
        }

        private static void SendNotifyToClient(NotifyMode mode)
        {
            for (int i = 0; i < notifylist.Count; i++)
            {
                CricketData data = notifylist[i];                            
                if (data.Mode == mode)
                {
                    Send(data);
                }               
            }                           
        }

        private static void Send(CricketData data)
        {
            int f = NotifySecond(data.Mode);           
            IClientCallback client = 
                       data.CricketContext.GetCallbackChannel<IClientCallback>();
            String message = string.Format("{1}/{0} : Runs/Wickets {2} Overs", Wicket, 
                       Run, Over);
            try
            {
                client.AsyncNotifyMessage(message);
            }
            catch
            {

            }           
        }

        static int NotifySecond(NotifyMode mode)
        {
            if (mode == NotifyMode.Wicket)
            {
                return 1;
            }
            else if (mode == NotifyMode.FiveOverOnce)
            {
                return  2;
            }
            else if (mode == NotifyMode.FiftyRunsOnce)
            {
                 return  3;
            }
            return 0;    
        }

    }
}


 Web Config:
<system.serviceModel>
    <bindings>
      <wsDualHttpBinding>
        <binding name="Bind" bypassProxyOnLocal="true" useDefaultWebProxy="true" />
      </wsDualHttpBinding>
    </bindings>
    <services>     
      <service behaviorConfiguration="returnFaults" name="CricInfoService.CricketService">
        <endpoint address="" binding="wsDualHttpBinding" bindingConfiguration="Bind"                            contract="CricInfoService.ICricketService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/CricInfoService/Cric/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="returnFaults">        
          <serviceMetadata httpGetEnabled="True"/>        
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>


host the WCF service : Hosting WCF Service


Client Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CricClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SubscriberHandler subscribeclient1 = new SubscriberHandler(CricService.NotifyMode.Wicket, "Rajesh",listBox1);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SubscriberHandler subscribeClient2 = new SubscriberHandler(CricService.NotifyMode.FiveOverOnce, "suresh", listBox2);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            SubscriberHandler subscribeClient3 = new SubscriberHandler(CricService.NotifyMode.FiftyRunsOnce, "Ram", listBox3);
        }
    }

    class SubscriberHandler : CricService.ICricketServiceCallback
    {
        ListBox lstobj = null;

        public SubscriberHandler(CricService.NotifyMode mode, string name,ListBox obj)
        {
            CricService.CricketServiceClient client = new CricService.CricketServiceClient(new System.ServiceModel.InstanceContext(this));
            lstobj = obj;
            bool status = client.GetNotification(mode, name);
            MessageBox.Show("Cricket Notification Activated in "+ mode.ToString() + " Mode : " + status);
        }

        public void AsyncNotifyMessage(string message)
        {
            lstobj.Items.Add(message);
        }
    }

}



From the above code You can see the SubscriberHandler which will get the instance of each client and send the instance to the service and get the result from the server then server starts the notification from server to client.

From this article you can see the publisher and subscriber model creation from WCF using WsDualHttpBinding.