22 March 2015

WCF - Windows Communication Foundation

1. WCF WCF as a programming platform that is used to build Service-Oriented applications. Microsoft has unified all its existing distributed application technologies (e.g. MS Enterprise Services, ASMX web services, MSMQ, .NET Remoting etc) at one platform

2. Difference between WCF and ASMX Web Services
1.     ASP.NET web service is designed to send and receive messages using SOAP over HTTP only.
While WCF can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, Named Pipes etc)
       2.     Web services is hosted in IIS only. WCF can be hosted in IIS, WAS, Console, Windows NT Service
       3.     Web service has only  Limited security ,  WCF is consistency security programming model.
       4.     Web services uses Xml serializer and WCF uses Data contract serializer.

2.  WCF Endpoints
1.     Client uses endpoint to communicate with WCF Service.

A WCF service endpoint has three basic elements i.e. Address, Binding and Contract.
Address: It defines “WHERE”. Address is the URL that identifies the location of the service.
Binding: It defines “HOW”. Binding defines how the service can be accessed.
Contract: It defines “WHAT”. Contract identifies what is exposed by the service.

3. Operation Overloading while exposing WCF Services?
By default, WSDL doesn’t support operation overloading. Overloading behavior can be achieved by using “Name” property of OperationContract attribute.

[ServiceContract]
 interface IMyCalculator
 {
        [OperationContract(Name = “SumInt”)]
        int Sum(int arg1,int arg2);
        [OperationContract(Name = “SumDouble”)]
        double Sum(double arg1,double arg2);
  }

4.Message Exchange Patterns (MEPs) supported by WCF

                1.Request/Response
                2.One Way
                3.Duplex

Request/Response
It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.
One Way
In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. One way MEP will work in such scenarios.
If we want queued message delivery, One way is the only available option.
Duplex
The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.

5.Standard Bindings in WCF
1.     BasicHttpBinding  is standard binding is designed to expose a service as if it is an ASMX/ASP.NET web service.

2.     NetTcpBinding provides transport level security, Transport Level security means providing security at the transport layer itself.
        
                   
                         
                   
         
 
       3. wsHttpBinding  provides following security  None,Transport,Message and Transport with message credentials
           
                         
                                     
                         
            
    
other bindings are WebHttpBinding - Wcf Restful service, netNamedPipeBinding,netTcpBinding,netPeerTcpBinding and netmsmqBinding


6. Core components of WCF Service
Service Class:  A service class implementing in any CLR-based language and expose at least one method.
Hosting Environment: a managed process for running service.
Endpoint: a client uses it to communicate with service.

7.Multiple endpoints for different binding types
Yes, we can have multiple endpoints for different binding types. For example, an endpoint with wsHttpBinding and another one with netTcpBinding.

8. Contracts in WCF?
A Contract is basically an agreement between the two parties i.e. Service and Client.

1.     Behavioral Contracts define that what operations client can perform on a service.
ServiceContract [Interface] attribute is used to mark a type as Service contract that contains operations.    OperationContract [Method in Interface]attributes is used to mark the operations that will be exposed.           Fault Contract defines what errors are raised by the service being exposed.
      2.     Structural Contracts
                DataContract [Class] attribute define types that will be moved between the parties.
                MessageContract attribute define the structure of SOAP message.
9. Different WCF Instance Activation Methods available
Per Call: A new instance is created against each incoming request from client and later disposed off  as response generated.
Per Session: an instance for each session.
Singleton: All incoming requests are served by only one instance.
10.Different ways to handle concurrency in WCF?
Single: means at a given time, only a single request can be processed by WCF service instance. Other requests will be waiting until the first one is fully served.
Multiple: means multiple requests can be served by multiple threads of a single WCF service instance.
Reentrant: means a single WCF service instance can process one request at a given time but the thread can exit the service to call another service.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple] public class MyService : IMyService
{
}

11.WCF throttling
WCF throttling enables us to regulate the maximum number of WCF instances, concurrent calls and concurrent sessions.

               
                               
                                                maxConcurrentInstances=”2147483647”
                                                maxConcurrentCalls=”16″
                                                maxConcurrentSessions=”10″
               

12.Fault contract
when some exception occurs at a WCF service level, it will not expose as it is to client. Reason is that WCF exception is a CLR exception and it doesn’t make sense to expose it outside CLR because it contains internal details of service code like stack trace. So, WCF handles and returns error details to client using Fault Contract.“So, fault contract is a contract that contains the details of possible exception(s) that might occur in a service code.
 [ServiceContract]
 public interface IService1
 {
                [OperationContract]
                [FaultContract(typeof(MyFaultDetails))]
                int MyOperation1();
 }
 [DataContract]
  public class MyFaultDetails
  {
                [DataMember]
                public string ErrorDetails { get; set; }
  }

public int MyOperation1()
  {
       Try{               //Do something……       }catch()
       {
                  MyFaultDetails ex = new MyFaultDetails();
                  ex.ErrorDetails = “Specific error details here.“;
                  throw new FaultException(ex,“Reason: Testing…..“);
       }
  }
13.Transfer Security Modes
None – No security at all. Very risky to choose.
Transport – Securing message transfer with transport protocol like TCP, IPs, HTTPs, MSMQ.  It’s Ideal for Intranet scenarios having point to point communication.
Message – Securing message by encrypting it. Good for scenarios even when multiple intermediaries involved.
Mixed – TransportWithMessageCredential uses transport for message privacy and service authentication with client authentication handled at message level.
Both -Using both Message as well as transport security. In this case a secured encrypted message travel over a secure transport (pipe) only supported by MSMQ Binding.

               
                               
               

14.Reliable Messaging in WCF?
We know that networks are not perfect enough and those might drop signals or in some scenarios there can be a possibility of wrong order of messages during message exchange.
WCF allows us to ensure the reliability of messaging by implementing WS-ReliableMessaging protocol.

   
                 
                                         enabled=”true”
                                        ordered=”true”
                                        inactivityTimeout=”00:02:00″ />
    
 
15.Reliable Sessions in WCF?
Reliable sessions actually ensure that the caller for messages will know about the lost message(s) but it can’t guarantee about the delivery of message(s).
There is a misconception about reliable sessions that it ensures the session will never expire or stays for a very long time. This we can achieve by using timeout for sessions.


How IIS Process Asp.net request before Asp.net Page Life cycle

How IIS Process Asp.net request before Life cycle

When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to respective  Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.

Worker Process:  Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.  All the ASP.Net functionality runs under the scope of worker process.  When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.
Application Pool: Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availability for any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn’t not impact other web application as they they are configured into different application pools.

reference
http://abhijitjana.net/2010/03/14/beginner%E2%80%99s-guide-how-iis-process-asp-net-request/

Dependency Injection

Dependency Injection

Dependency Injection is to reduce tight coupling

The Dependency Injection pattern is a particular implementation of Inversion of Control.
Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source

Advantages of using Dependency Injection pattern and Inversion of Control are the following:


Reduces class coupling,Increases code reusing,Improves code maintainability,Improves application testing

Factory Method Patterns in C#

Factory Method Patterns

Definition: In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.

Uses of Factory Method Patterns

1.    creation of object is done when it is required.
2.    The process of objects creation is required to centralize within the application.
3.    A class (creator) will not know what classes it will be required to create.


interface Product
{

}

class ConcreteProductA : Product
{
}
class ConcreteProductB : Product
{
}
abstract class Creator
{
 public abstract Product FactoryMethod(string type);
}
class ConcreteCreator : Creator
{
 public override Product FactoryMethod(string type)
 {
 switch (type)
 {
 case "A": return new ConcreteProductA();
 case "B": return new ConcreteProductB();
 default: throw new ArgumentException("Invalid type", "type");
 }
 }
}

JQuery Quick Reference

JQuery Quick Reference

1.    JQuery
            jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript programming.
jQuery uses CSS syntax to select elements.

  2. Uses
The jQuery library contains the following features:

            HTML/DOM manipulation
            CSS manipulation
            HTML event methods
            Effects and animations
            AJAX
            Utilities
Notes:
If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).
$(document).ready(function(){
   // jQuery methods go here...
});
or
$(function(){
   // jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).

3. JQuery Selector
$("*")     Selects all elements    
$(this)     Selects the current HTML element    
$("p.intro")     Selects all elements with class="intro"    
$("p:first")     Selects the first element     Try it
$("ul li:first")     Selects the first
  • element of the first
          
  • $("ul li:first-child")     Selects the first
  • element of every
          
  • $("[href]")     Selects all elements with an href attribute     Try it
    $("a[target='_blank']")     Selects all elements with a target attribute value equal to "_blank"    
    $(":button")     Selects all
    $("tr:even")     Selects all even elements    
    $("tr:odd")     Selects all odd elements

    4.

    click()
    $("p").click(function(){  // When a click event fires on a element
                $(this).hide();   //   hide the current element
    });
    dblclick()
    $("p").dblclick(function(){
                $(this).hide();
    });
    mouseenter()
     $("#p1").mouseenter(function(){
                alert("You entered p1!");
    });

    hover()
    $("#p1").hover(function(){
                alert("You entered p1!");
    },

    focus()
    $("input").focus(function(){
                $(this).css("background-color", "#cccccc");
    });
    blur()
    $("input").blur(function(){
                $(this).css("background-color", "#ffffff");
    });
    jQuery toggle()
    Shown elements are hidden and hidden elements are shown:
    $("button").click(function(){
                $("p").toggle();
    });

    5. jQuery Callback Functions         
    JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.
    A callback function is executed after the current effect is finished.

    $("button").click(function(){
                $("p").hide("slow", function(){
                alert("The paragraph is now hidden");
                });
    });
    function do_a( callback ){
      setTimeout( function(){
                // simulate a time consuming function
                console.log( '`do_a`: this takes longer than `do_b`' );

                // if callback exist execute it
                callback && callback();
      }, 3000 );
    }

    function do_b(){
      console.log( '`do_b`: now we can make sure `do_b` comes out after `do_a`' );
    }

    do_a( function(){
      do_b();
    });

    Example :
    `do_a`: this takes longer than `do_b`
    `do_b`: now we can make sure `do_b` comes out after `do_a`

    6. jQuery - Chaining

    Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.
    $("#p1").css("color", "red")
      .slideUp(2000)
      .slideDown(2000);

    7. Get Attributes - attr()
                $("button").click(function(){
                alert($("#w3s").attr("href"));
                });
    8.jQuery - Set Content and Attributes
                text() - Sets or returns the text content of selected elements
                html() - Sets or returns the content of selected elements (including HTML markup)
                val() - Sets or returns the value of form fields

    $("#btn1").click(function(){
                $("#test1").text("Hello world!");
    });
    $("#btn2").click(function(){
                $("#test2").html("Hello world!");
    });
    $("#btn3").click(function(){
                $("#test3").val("Dolly Duck");
    });

    9.Set Attributes - attr()
    The jQuery attr() method is also used to set/change attribute values.

     $("button").click(function(){
                $("#w3s").attr("href", "http://www.w3schools.com/jquery");
    });

    10.jQuery - Add Elements
        With jQuery, it is easy to add new elements/content.
       
                append() - Inserts content at the end of the selected elements
                prepend() - Inserts content at the beginning of the selected elements
                after() - Inserts content after the selected elements
                before() - Inserts content before the selected elements

    11.jQuery - Remove Elements

        With jQuery, it is easy to remove existing HTML elements.

                remove() - Removes the selected element (and its child elements)
                empty() - Removes the child elements from the selected element


    jQuery remove() Method
    The jQuery remove() method removes the selected element(s) and its child elements.
    $("#div1").remove();

    jQuery empty() Method
    The jQuery empty() method removes the child elements of the selected element(s).
    $("#div1").empty();

    Filter the Elements to be Removed
    $("p").remove(".italic");

    jQuery - Get and Set CSS Classes

    With jQuery, it is easy to manipulate the CSS of elements.


                addClass() - Adds one or more classes to the selected elements
                removeClass() - Removes one or more classes from the selected elements
                toggleClass() - Toggles between adding/removing classes from the selected elements
                css() - Sets or returns the style attribute

    jQuery addClass() Method
    $("button").click(function(){
                $("h1, h2, p").addClass("blue");
                $("div").addClass("important");
    });

    jQuery removeClass() Method

    $("button").click(function(){
                $("h1, h2, p").removeClass("blue");
    });

    jQuery toggleClass() Method

    $("button").click(function(){
                $("h1, h2, p").toggleClass("blue");
    });

    jQuery css() Method

    Return a CSS Property
    The following example will return the background-color value of the FIRST matched element:
    $("p").css("background-color");

    Set a CSS Property
    $("p").css("background-color", "yellow");

    Set Multiple CSS Properties
    The following example will set a background-color and a font-size for ALL matched elements:
    $("p").css({"background-color": "yellow", "font-size": "200%"});

    jQuery - Dimensions

    jQuery has several important methods for working with dimensions:

                width()
                height()
                innerWidth()
                innerHeight()
                outerWidth()
                outerHeight()


    jQuery Traversing - Ancestors
    An ancestor is a parent, grandparent, great-grandparent, and so on.
    With jQuery you can traverse up the DOM tree to find ancestors of an element.

    jQuery parent() Method
    The parent() method returns the direct parent element of the selected element.
    This method only traverse a single level up the DOM tree.

    jQuery parents() Method
    The parents() method returns all ancestor elements of the selected element, all the way up to the document's root element ().
    $(document).ready(function(){
                $("span").parents();
    });
    The following example returns all ancestors of all elements that are
      elements:
    $(document).ready(function(){
                $("span").parents("ul");
    });

    jQuery parentsUntil() Method
    The parentsUntil() method returns all ancestor elements between two given arguments.
    $(document).ready(function(){
                $("span").parentsUntil("div");
    });

    jQuery Traversing - Descendants

    A descendant is a child, grandchild, great-grandchild, and so on.
    With jQuery you can traverse down the DOM tree to find descendants of an element.

    jQuery children() Method

    The children() method returns all direct children of the selected element.
    $(document).ready(function(){
                $("div").children();
    });

    jQuery find() Method
    The find() method returns descendant elements of the selected element, all the way down to the last descendant.
    $(document).ready(function(){
                $("div").find("span");
    });


    The following example returns all descendants of
    :
    $(document).ready(function(){
                $("div").find("*");
    });


    jQuery siblings() Method
    The following example returns all sibling elements of

    :

    $(document).ready(function(){
                $("h2").siblings();
    });
    jQuery next() Method

    The next() method returns the next sibling element of the selected element
    $(document).ready(function(){
                $("h2").next();
    });

    jQuery nextAll() Method
    The nextAll() method returns all next sibling elements of the selected element.
    $(document).ready(function(){
                $("h2").nextAll();
    });
    jQuery nextUntil() Method
    The nextUntil() method returns all next sibling elements between two given arguments.

    $(document).ready(function(){
                $("h2").nextUntil("h6");
    });
    jQuery first() Method
    The first() method returns the first element of the selected elements.
    $(document).ready(function(){
                $("div p").first();
    });

    jQuery last() Method
    The last() method returns the last element of the selected elements.
    $(document).ready(function(){
                $("div p").last();
    });
    jQuery eq() method
    The eq() method returns an element with a specific index number of the selected elements.
    $(document).ready(function(){
                $("p").eq(1);
    });

    jQuery filter() Method
    The following example returns all elements with class name "intro":
    $(document).ready(function(){
                $("p").filter(".intro");
    });

    jQuery not() Method
    The following example returns all elements that do not have class name "intro":
    $(document).ready(function(){
                $("p").not(".intro");
    });

    jQuery - The noConflict() Method
    If two different frameworks are using the same shortcut, one of them might stop working.
    The jQuery team have already thought about this, and implemented the noConflict() method.
    The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.

    $.noConflict();
    jQuery(document).ready(function(){
                jQuery("button").click(function(){
                jQuery("p").text("jQuery is still working!");
                });
    });

    JQuery
    //MVC JQuery Ajax
    $('#learnitem-form').ajaxSubmit({
      data : {
                data1: data1,
                data2: data2,

                },
      success : function(result){
      //success
                },
      error : function(){
      //error
      }
    });

    Posting Javascript Object


    type     This is type of HTTP Request and accepts a valid HTTP verb. POST is the option illustrated in this article.
    url     This is the location of the resource that the request will be made to.
    data     This is the actual data to be sent as part of the request.
    contentType     This is the content type of the request you are making. The default is 'application/x-www-form-urlencoded'.
    dataType     This is the type of data you expect to receive back. Accepted values are text, xml, json, script, html jsonp. If you do not provide a value, jQuery will examine the MIME type of the response and base its decision on that.






    MVC Interview Question in Dotnet

    MVC Interview Question in Dotnet

    1.     What is MVC ?
    MVC is an architectural pattern which separates the representation and user interaction.
    M - Model -  Application business logic is in the Model
    V - View - Views represent the user interface, with which the end users interact.
    C - Controller - Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface.

    2. Advantages of MVC
    1.     ASP.NET MVC views are light weight, as they do not use viewstate.
    2.     Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
    3.     Complex application can be easily managed by the developer.
    4.     In Razor view engine using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.
    5.     Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.). Bundling that makes it easy to combine or bundle multiple files into a single file.
    6.     Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary whitespace and comments and shortening variable names to one character.
    3. MVC Application Life cycle
    MVC application life cycle has two main phases
    Creating the request object and sending our response to the browser.
    Creating the request Object
    Step 1: Fill route : - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.
    Step 2: Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
    Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext” object.
    Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
    Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.

    4.Routing in MVC
    Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event.

    routes.MapRoute(
                   "View", // Route name
                   "View/ViewCustomer/{id}", // URL with parameters
                   new { controller = "Customer", action = "DisplayCustomer",
    id = UrlParameter.Optional }); // Parameter defaults

    The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.

    5.HTML helpers in MVC
    HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.
    Copy Code

    <%= Html.TextBox("LastName") %>
    6. Difference between HTML.TextBoxFor and HTML.TextBox
    Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t
    Html.TextBox("CustomerCode")
    Html.TextBoxFor(m => m.CustomerCode)

    7.Attribute based routing in MVC
    This is a feature introduced in MVC 5. By using the "Route" attribute we can define the URL structure.
    public class HomeController : Controller
    {
           [Route("Users/about")]
           public ActionResult GotoAbout()
           {
               return View();
           }
    }
    Most of the time developers code in the action methods. Developers can see the URL structure right upfront rather than going to the “routeconfig.cs” and see the lengthy codes.

    8. Navigate from one view to another using a hyperlink?
    <%= Html.ActionLink("Home","Gotohome") %>
    Home - Controller
    Gotohome - Action

    9. Restrict MVC actions to be invoked only by GET or POST
    We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.

    [HttpGet]
    public ViewResult DisplayCustomer(int id)
    {
        Customer objCustomer = Customers[id];
        return View("DisplayCustomer",objCustomer);
    }

    10.ViewData, ViewBag and TempData

    ASP.NET MVC offers us three options ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility.
    Helps to maintain data when you move from controller to view.
    ViewData requires typecasting for complex data type and check for null values to avoid error and ViewBag doesn’t require typecasting for complex data type.
    ViewBag & ViewData Example:

    public ActionResult Index()
                    ViewBag.Name = "Arun Prakash";
                    return View();   
    }

    public ActionResult Index() 
    {
                    ViewData["Name"] = "Arun Prakash";
                    return View();
    }

    In View, we call like below:

    @ViewBag.Name  
    @ViewData["Name"]
    TempData:

    Helps to maintain data when you move from one controller to another controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only.

    It requires typecasting for complex data type and check for null values to avoid error.
    So if “TempData” is once read it will not be available in the subsequent request.

    11.Partial views in MVC?
    Partial view is a reusable view (like a user control) which can be embedded inside other view.

    12.Validations in MVC?
    Data annotations are nothing but attributes which can be applied on model properties.

    Types
    [Required]
    [StringLength(50, MinimumLength = 2)]
    [Range(15, 100)]

    Data type
    The data type annotation can be used to specify the data type for validation. The information may also be used as UI hint later in rendering process.
    Copy Code

    [Url]
    public string url { get; set; }
    [Phone]
    public string phone { get; set; }
    [DataType(DataType.Date)]
    public DateTime updatedate { get; set; }

    [DataType(DataType.PhoneNumber)]
    public string phone { get; set; }
    public class Customer
    {
        [Required(ErrorMessage="Customer code is required")]
        public string CustomerCode
        {
            set;
            get;
        }
    }

    <% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
    { %>
    <%=Html.TextBoxFor(m => m.CustomerCode)%>
    <%=Html.ValidationMessageFor(m => m.CustomerCode)%>

    <%}%>
    Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

    public ActionResult PostCustomer(Customer obj)
    {
        if (ModelState.IsValid)
        {
            obj.Save();
            return View("Thanks");
        }
        else
        {
            return View("Customer");
        }
    }

    13.Can we display all errors in one go?
    Yes, we can; use the ValidationSummary method from the Html helper class.
    <%= Html.ValidationSummary() %>

    14. Ajax in MVC

    Implement Ajax using Ajax libraries
    function GetData()
    {
                    var url = "/MyAjax/getCustomer";
                    $.post(url, function (data)
                    {
                    $("#txtCustomerCode").val(data.CustomerCode);
                    $("#txtCustomerName").val(data.CustomerName);
                    }
                    )
    }
    implement AJAX by using the “AJAX” helper library


    <%
       var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};                    
    %>
    <% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>


    <%} %>

    15.Difference between ActionResult and ViewResult?

    ActionResult is an abstract class while ViewResult derives from the ActionResult class.
    ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
    Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.

    public ActionResult DynamicView()
    {
       if (IsHtmlView)
                    return View(); // returns simple ViewResult
       else
                    return Json(); // returns JsonResult view
    }

    16.Different types of results in MVC?

    There 12 kinds of results in MVC, at the top is the ActionResult class which is a base class that can have 11 subtypes as listed below:

                    1.ViewResult - Renders a specified view to the response stream
                    2.PartialViewResult - Renders a specified partial view to the response stream
                    3.EmptyResult - An empty response is returned
                    4.RedirectResult - Performs an HTTP redirection to a specified URL
                    5.RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine,  based on given route data
                    6.JsonResult - Serializes a given ViewData object to JSON format
                    7.JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
                    8.ContentResult - Writes content to the response stream without requiring a view
                    9.FileContentResult - Returns a file to the client
                    10.FileStreamResult - Returns a file to the client, which is provided by a Stream
                    11.FilePathResult - Returns a file to the client


    17. Areas in MVC?
    Group the  controller classes into logical section
    18. MVC Scaffolding
    Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for create, read, update and delete.
    19.Multiple Submit buttons pointing to multiple actions in a single MVC view
    HTML Way








    Ajax Way







    20. MVC Ajax Example
    //MVC JQuery Ajax

    $('#learnitem-form').ajaxSubmit({

      data : {
              data1: data1,
              data2: data2,

             },

      success : function(result){
      //success
             },
      error : function(){
      //error
      }
    });
    20. MVC Action Filters
    ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.

    Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.

    Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method

    OnActionExecuting - Runs before execution of Action method.
    OnActionExecuted - Runs after execution of Action method.
    OnResultExecuting - Runs before content is rendered to View.
    OnResultExecuted - Runs after content is rendered to view.



    Result filter, which wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response.

    Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page.

    21. MVC Custom Filters
    When you request any page into MVC Application, it will go through the Routing Architecture. Your Routing system will decide your URL pattern. The default routing algorithm is like {controller}/ {action}/ {id} patterns. But it can be possible to change that pattern using Custom Routes.

    When you create a Custom Route, you can also include route constraints. These constraints are used to restrict the requests to match routes. There are three basic types of constraints:

    1.     Regular Expression Constraints - check the pattern of the Route and prevent invalid requests
    2.     HttpMethod Constraints - You can match route with any type of the HTTP operation like POST, GET, etc. you want to prevent user to access particular URL when GET operation occurs but not POST operation occurs.
    //Custom Route With HttpMethod Constraint
                routes.MapRoute(
                    "HttpMethodConstraintRoute",
                    "Blog/Insert",
                    new { Controller = "Blog", action = "Insert" },
            new { method = new HttpMethodConstraint("GET") });

     3. CatchAllRoutes- Suitable for the dynamic URL, But if you want to match your URL, regardless of the number     of the segments for that, we have to create Catch-All Parameter.

    22.Action Results - ActionResult method works as a return type of any controller method in the MVC. It acts like the base class of Result classes. It is used to return the models to the Views, file streams and also redirect to the controllers.
    23.Razor View Engine VS Web Form(ASPX) View Engine

    1.     Razor Engine is an advanced view engine that was introduced with MVC3.
    Web Form Engine is the default view engine for the Asp.net MVC that is included with Asp.net MVC from the beginning.

                 2. The file extensions used with Razor Engine are different from Web Form Engine. It has .cshtml (Razor
                with  C#) or .vbhtml (Razor with VB) extension for views, partial views, editor templates and for layout pages.

    3. The file extensions used with Web Form Engine are also like Asp.net Web Forms. It has .aspx         extension     for  views, .ascx extension for partial views & editor templates and .master extension for layout/master pages.

                   4. Razor has new and advance syntax that are compact, expressive and reduces typing.
                   Web Form Engine has the same syntax like Asp.net Web Forms uses for .aspx pages.

    5. Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @ symbol to make the code like as:
    @Html.ActionLink("SignUp", "SignUp")
    Web Form syntax are borrowed from Asp.net Web Forms syntax that are mixed with html and sometimes make a view messy. Webform uses <% and %> delimiters to make the code like as:
    <%: Html.ActionLink("SignUp", "SignUp") %>

    6.By default, Razor Engine prevents XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or html tags like <,> before rendering to view.
    Web Form Engine does not prevent XSS attacks means any script saved in the database will be fired while rendering the page

    7. Razor Engine is little bit slow as compared to Webform Engine.
    Web Form Engine is faster than Razor Engine.

    8. Razor Engine, doesn't support design mode in visual studio means you cannot see your page look and feel.
    Web Form engine support design mode in visual studio means you can see your page look and feel without running the application.

    9. Razor Engine support TDD (Test Driven Development) since it is not depend on System.Web.UI.Page class.
    Web Form Engine doesn't support TDD (Test Driven Development) since it depend on System.Web.UI.Page class which makes the testing complex.




    Implementing OAuth validation in a Web API

     I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...