Tuesday, December 6, 2016

WCF Data Access Layer

Entity Framework
It's an Object Relational Mapping (ORM) Tool.

  • Communicate with Database
  • Map database data to object-oriented data.

Entity Framework 3 Approach

Database First approach 
Create database with tables, columns, relations etc. and Entity framework will generate Model classes (Business entities) and Data Access Layer code.

Model First approach
Model classes and relationship between them will be defined manually using Model designer in Visual studio, and Entity Framework will generate Data Access Layer and Database with tables, columns, relations automatically.


Code First approach 
Manually POCO classes (simple .NET classes) will be created. Relationship between those classes will be defined by means of code.When the application executes for the first time Entity framework will generate Data Access Layer and Database with tables, columns and relations automatically in the database server.


DBSet
The collection of all the entities that query from the database.

Monday, December 5, 2016

Web API VS WCF SOAP

Consume data on HTTP from clients like mobile, JavaScript, Windows applications, etc.
WebAPI is the technology by which you can expose data over HTTP following REST principles.


WCF SOAP
WEB API
Size
Heavyweight because of complicated WSDL structure.
Light weight, only the necessary information is transferred.
Protocol
Independent of protocols.
Only for HTTP protocol
Formats
To parse SOAP message, client needs to understand WSDL format.
Output of WebAPI is simple string messages, JSON, simple XML format, etc. So writing parsing logic for that is very easy.
Principles
SOAP follows WS-* specification.
WebAPI follows REST principles. (Please refer to REST in WCF chapter.)

WCF and WebAPI also can implement REST, why WebAPI
WCF was brought into implement SOA, the intention was never to implement REST. WebAPI is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating REST service, WebAPI is more preferred.

Authentication and Authorization in MVC

Windows authentication or Forms authentication for MVC.

Windows authentication

1. In the web.config, set the authentication mode to Windows.
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization> 

2. In the controller, use authorize attribute which specifies who have access to these controllers and actions.
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
    //
    // GET: /Start/
    [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
    public ActionResult Index()
    {
        return View("MyView");
    }
} 

Forms authentication

1. In the web.config, set the authentication mode to Forms and the login URL points to a controller.
<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication> 

2. In the controller, check valid user access and set in cookie.
public ActionResult Login()
{
    if ((Request.Form["txtUserName"] == "Shiv") && 
          (Request.Form["txtPassword"] == "Shiv@123"))
    {
        FormsAuthentication.SetAuthCookie("Shiv",true);
        return View("About");
    }
    else
    {
        return View("Index");
    }
} 

3.All Authorize attribute to all pages so any unauthorized user making a call to these controllers will be redirected to the controller (in this case the controller is “Login”) .

[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
} 

MVC Sessions

Sessions can be maintained in MVC by three ways: tempdataviewdata, and viewbag.

Temp Data - maintain data when you move from one controller to another controller or from one action to another action. When you redirect, it maintains data between those redirects. It internally uses session variables.

View Data - maintain data when you move from controller to view.

View Bag - It’s a dynamic wrapper around view data (2 or more). When you use Viewbag type, casting is not required. It uses the dynamic keyword internally.









Left: is for view bag. (Dynamic keywords)












Session variables - Maintain data from any entity to any entity.

Hidden fields and HTML controls - Maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Maintains data betweenViewData/ViewBagTempDataHidden fieldsSession
Controller to ControllerNoYesNoYes
Controller to ViewYesNoNoYes
View to ControllerNoNoYesYes


What is the difference between TempData and ViewData ?
TempData maintains data for the complete request
ViewData maintains data only from Controller to the view.

What is the difference between ViewBag and ViewData ?
Both are used to communicate between controller and view.
ViewBag  is dynamic
ViewData is dictionary object.

Does TempData preserve data in the next request also?
TempData is dictionary object. is available throughout for the current request and in the subsequent request, it’s available depending on whether “TempData” is read or not.

So if TempData is once read it will not be available in the subsequent request.




MVC Validation

Using data annotations. Data annotations are nothing but attributes which applied on model properties.

This CustomerCode property is tagged with a Required data annotation attribute. If this model is not provided customer code, it will not accept it.

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

To display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%> 

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");
    }
}

use the ValidationSummary method from the Html helper class to display all errors in one go

<%= Html.ValidationSummary() %>   

Others Data Annotation.

[StringLength(160)]public string FirstName { get; set; } //String Length
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; } //Email Regular Expression
[Range(10,25)]public int Age { get; set; } //Number in Range
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; } //string compare
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage; //get a error message, use Error corllection.
TryUpdateModel(NewCustomer); //Create model object yourself and call TryUpdateModel in controller to check the object valid or not.
ModelState.AddModelError("FirstName", "This is my server-side error."); //Add errors in the controller


2 Step to enable data annotation validation on client side.
  • Reference the JQuery files.
  • <script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
  • Call EnableClientValidation method.
  • <% Html.EnableClientValidation(); %> 

Sunday, December 4, 2016

MVC Routing

Routing
Define URL structure and map the URL with the controller.

E.g. user types “http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes the DisplayCustomer action.
This is defined by adding an entry in to the routes collection using the maproute function.

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

Route Mapping is writte in "RouteConfig.cs" and register using "global.asax" application start event.

you can map mutiple URL with same action. Just need to make 2 entry with different key name and specify the same controller and action.

MVC 5, by using the "Route" attribute we can define the URL structure.
E.g. in the below code we have decorated the "GotoAbout" action with the route attribute. The route attribute says that the "GotoAbout" can be invoked using the URL structure "Users/about".

public class HomeController : Controller
{
       [Route("Users/about")]
       public ActionResult GotoAbout()
       {
           return View();
       }
}

Advantage of define Route Structure (MVC5)

Developers can see the URL structure in top of the method rather than go to “routeconfig.cs” and see the lengthy codes.
This is much user friendly as compared to scrolling through the “routeconfig.cs” file and going through the length line of code to figure out which URL structure is mapped to which action.

public class HomeController : Controller
{
       [Route("Users/about")]
       [Route("Users/WhoareWe")]
       [Route("Users/OurTeam")]
       [Route("Users/aboutCompany")]
       public ActionResult GotoAbout()
       {
           return View();
       }
}

MVC

MVC
An architectural pattern which separates the representation and user interaction :

View - Look and Feel
Model - Object, provide data to view
Controller - Take end user request and loading the appropriate Model and View.

It more suitable to WEB, Windows App user MVP.


ASP.NET Web Forms
ASP.NET MVC
development model
Form follow a traditional event driven
Is a lightweight and follow MVC (Model, View Controller) pattern
HTML
Server controls
HTML Helpers
Support view state
Yes
No
URL
File-based URLs (must have physical file name)
Route-based URL (based on controller not on physical file)
Syntax
Follow Web Forms Syntax
Follow customizable syntax (Razor as default)
Coupling
ASPX and ASPX.CS are tightly coupled
Views and logic are kept separately
Consistent Look
Master Pages
Layout
Page Reuse
User Controls
Partial Views
Open Source
No
Yes

Advantage of MVC
  • Separate code behind to a separate class file, so we can reuse the code.
  • Automated UI testing, it give us to wrote unit test and automate manual testing.
MVC Life Cycle





Creating the request object: -The request object creation has 4 steps:

Step 1 Fill route: MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if is the first request, it will fill the route table with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route: 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.
______________________________________________________________________________

TestController is the class name.
Test is the controller name.
In URL, you should type Test only.
______________________________________________________________________________

Action method is a public method inside controller which accepts user’s request and returns response.

public method in controller will automatically become action method. Non public method cannot invoked from the web.

Public method but not action method
[NonAction]
public string SimpleMethod()
{
    return "Hi, I am not action method";
}
______________________________________________________________________________

HTML Helpers
Help you to render HTML controls in the view.

Html.TextBox("CustomerCode")
Html.TextBoxFor(m => m.CustomerCode) //using property name from object m.

ActionLink method can navigate from one view to another using a hyperlink. E.g. below is navigate to "Home" controller and invoke "GotoHome" method.
<%= Html.ActionLink("Home","Gotohome") %>
______________________________________________________________________________

“input type=submit” request to the server .
“input type=button” perform some custom client side actions.
______________________________________________________________________________


We can restrict the MVC action with the HttpGet or HttpPost attribute. E.g. 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);
} 
______________________________________________________________________________

Partial Views
Is a reusable view (like a user control) which can be embedded inside other views.
E.g. all your pages have a standard structure with left menu and  header. So you can create partial views for each of these items and then you call that partial view in the main view.

<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body> 
______________________________________________________________________________

ASPX. Razor was introduced in MVC 3. It’s a clean and lightweight view engine. Syntaxes are easy as compared to ASPX.

ASPX 
<%=DateTime.Now%> 
Razor
@DateTime.Now
______________________________________________________________________________

ActionResult
  • is an abstract class 
  • It has few derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
  • Can be used to exploit polymorphism and dynamism, for returning different types of views dynamically. 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
} 

ViewResult - Renders a specified view to the response stream.
JsonResult - Serializes a given ViewData object to JSON format.
______________________________________________________________________________

ActionFilters help you to perform logic while an MVC action is executing or after an MVC action has executed.


Action filters are useful in the following scenarios:
  1. Implement post-processing logic before the action happens.
  2. Cancel a current execution.
  3. Inspect the returned value.
  4. Provide extra data to the action.
Types of the action filters (execute by sequence)
  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters
You can create action filters by two ways:

1) Inline Action Filter

Need to implement the IActionFilter interface.

The IActionFilter interface has two methods: OnActionExecuted and OnActionExecuting. We can implement pre-processing logic or cancellation logic in these methods.

public class Default1Controller : Controller , IActionFilter
{
    public ActionResult Index(Customer obj)
    {
        return View(obj);
    }
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        Trace.WriteLine("Action Executed");
    }
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        Trace.WriteLine("Action is executing");
    }
} 

2) Action Filter Attribute

The problem with the inline action attribute is that it cannot be reused across controllers
So we can use Action Filter Attribute. We need to inherit from ActionFilterAttribute and implement the IActionFilter interface.

public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        Trace.WriteLine("Action Executed");
    }
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
      Trace.WriteLine("Action executing");
    }
} 

The controllers on which we want the action attribute to execute.

[MyActionAttribute]
public class Default1Controller : Controller 
{
    public ActionResult Index(Customer obj)
    {
        return View(obj);
    }
}
______________________________________________________________________________

we can use Request.HttpMethod to detect POST and GET action.

public ActionResult SomeAction()
{
    if (Request.HttpMethod == "POST")
    {
        return View("SomePage");
    }
    else
    {
        return View("SomeOtherPage");
    }
}
______________________________________________________________________________

Model is Business specific data. It will be created based on Business and Database structure. ViewModel is View specific data. It will be created based on the View.

When use ViewModel ? E.g. DB Store FirstName and LastName, they are model. ViewModel = EmployeeName = FirstName and  + LastName

Every view should have its own ViewModel although it's same as model. good for update in future.
______________________________________________________________________________

Bundling help combines multiple JavaScript and CSS files into a single entity thus minimizing multiple requests into a single request to increase performance.

Open BundleConfig.cs from the App_Start folder.

public  class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
           "~/Scripts/*.js")); //All JS file
        BundleTable.EnableOptimizations = true;
    }
}

Execute at ASPX or Razor view.
<%= Scripts.Render("~/Scripts/MyScripts")  %>

Minification is to reduce Script and CSS files size by removing blank spaces, comments and etc. Minification  is implemented by itself when you implement bundling.
______________________________________________________________________________

Right clicking + Area will group the controller classes.


______________________________________________________________________________

We can bind 2 models with a single view, but not from UI (because UI only can select 1)
so you do in the code manually.

public class CustOrderVM
{
public  Customer cust = new Customer();
public Order Ord = new Order();
}

<%= model.cust.Name %>
<%= model.Ord.Number %>
______________________________________________________________________________
Check user agent and point to which view.
______________________________________________________________________________

In the controller, to handle the exception by override the “OnException” event and set the “Result” to the view name which you want to invoke when the error occurs.

public class HomeController : Controller
 {
    protected override void OnException(ExceptionContext filterContext)
    {
      Exception ex = filterContext.Exception;     
      filterContext.ExceptionHandled = true;
      var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");

      filterContext.Result = new ViewResult()
      {
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
      };
    }
}

@Model.Exception;
______________________________________________________________________________

You can handle multiple submit button in an MVC view.

This is wrong, you press any of button also call "Action1" only.
<form action="Action1" method=post>
<input type=&rdquo;submit&rdquo; name=&rdquo;Submit1&rdquo;/>
<input type=&rdquo;submit&rdquo; name=&rdquo;Submit2&rdquo;>
</form>

1) HTML way : 2 Form and 2 Action
<form action="Action1" method=post>
<input type=&rdquo;submit&rdquo; name=&rdquo;Submit1&rdquo;/>
</form>

2) AJAX way : 2 Function and 2 Action

Create 2 functions "Fun1" and "Fun2", call using JQUERY
<Script language="javascript">
function Fun1()
{
$.post(&ldquo;/Action1&rdquo;,null,CallBack1);
}
function Fun2()
{
$.post(&ldquo;/Action2&rdquo;,null,CallBack2);
}
</Script>

3) 1 Form 1 Action

<input type="submit" name="BtnSubmit&rdquo; value="Save Employee" />

<input type="button" name="BtnReset" value="Reset" onclick="ResetForm();" />

<input type="submit" name="BtnSubmit" value="Cancel" />

public ActionResult SaveEmployee(Employee e, string BtnSubmit)
{
    switch (BtnSubmit)
    {
        case "Save Employee":
            return Content(e.FirstName + "|" + e.LastName + "|" + e.Salary);
        case "Cancel":
            return RedirectToAction("Index");
    }
    return new EmptyResult();
}
// Not Related (Reset by client)
<script>
    function ResetForm() {
        document.getElementById('TxtFName').value = "";
        document.getElementById('TxtLName').value = "";
        document.getElementById('TxtSalary').value = "";
    }
</script


https://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-answers#Disclaimer