Saturday 28 December 2013

Various ways to get the values from the form post to the controller action - ASP.MVC

In this article we are going to see the various ways of accessing a values from the view form post in the
action.

HTML :
@model TestingMvc.Models.Employee
@{
    ViewBag.Title = "Create Employee";
}
<h2>
    Create Employee</h2>
   
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset style="width:300px">
        <legend>Employee</legend>
        <br />
        <div class="editor-label">
            @Html.LabelFor(m => m.EmployeeName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(m => m.EmployeeName)
            @Html.ValidationMessageFor(m=>m.EmployeeName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x => x.Country)
        </div>
        <div class="editor-field">
            @Html.EditorFor(x => x.Country)
            @Html.ValidationMessageFor(x=>x.Country)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x => x.DepartmentId, "Department")
        </div>
        <div class="editor-field">
            @Html.DropDownList("Departments", new List<SelectListItem>(){
    new SelectListItem(){Text="TECH",Value="1"},
    new SelectListItem(){Text="HR",Value="2"},
    new SelectListItem(){Text="Finance",Value="3"}
    }, "Select Department")
    @Html.ValidationMessageFor(x=>x.DepartmentId)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x=>x.Married)
        </div>
        <div class="editor-field">
            @Html.DropDownList("Married",new List<SelectListItem>(){
   new SelectListItem(){Text="Yes",Value="YES"},
   new SelectListItem(){Text="No",Value="NO"}  
   })
   @Html.ValidationMessageFor(x=>x.Married)
        </div>
        <br />
        <input type="submit" value="Create" />
    </fieldset>
}

<br />
@Html.ActionLink("Back to List","Index","Department")

FormCollection:
 From this FormCollection developer can get the all controls values present with in the form while post.Values are stored as key/values pairs

        [HttpPost]
        public ActionResult Create(FormCollection form)
        {       
            BusLayer bl = new BusLayer();
            bl.Create(form["EmployeeName"], form["Country"], form["Married"], int.Parse(form["Departments"]));
            return RedirectToAction("Details", new { id=int.Parse(form["Departments"])});           
        }

  
Parameter:
     From This method all the elements are mention as parameter with the same name as the control name to the input for action then it is default mapped the values to that variable, parameters can be in any order.

        [HttpPost]
        public ActionResult Create(string employeename,string country,string married,int departments)
        {       
            BusLayer bl = new BusLayer();
            bl.Create(employeename,country,married,departments);
            return RedirectToAction("Details", new { id=departments});           
        }



Output:



From this article you can learn the various ways of access a values from the request posted from the client.

Submit a FORM in ASP.NET MVC

In this article we are going to see how to submit a form to the controller,so let we take a example add a new employee to the list and submit it.

Create a Employee Controller and action in a name of Create which is mention as HttpGet that means it is a Get Request so it is called at the load time, Now for this action create a View.

C#

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }



HTML

@model TestingMvc.Models.Employee
@{
    ViewBag.Title = "Create Employee";
}
<h2>
    Create Employee</h2>
   
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset style="width:300px">
        <legend>Employee</legend>
        <br />
        <div class="editor-label">
            @Html.LabelFor(m => m.EmployeeName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(m => m.EmployeeName)
            @Html.ValidationMessageFor(m=>m.EmployeeName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x => x.Country)
        </div>
        <div class="editor-field">
            @Html.EditorFor(x => x.Country)
            @Html.ValidationMessageFor(x=>x.Country)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x => x.DepartmentId, "Department")
        </div>
        <div class="editor-field">
            @Html.DropDownList("Departments", new List<SelectListItem>(){
    new SelectListItem(){Text="TECH",Value="1"},
    new SelectListItem(){Text="HR",Value="2"},
    new SelectListItem(){Text="Finance",Value="3"}
    }, "Select Department")
    @Html.ValidationMessageFor(x=>x.DepartmentId)
        </div>
        <div class="editor-label">
            @Html.LabelFor(x=>x.Married)
        </div>
        <div class="editor-field">
            @Html.DropDownList("Married",new List<SelectListItem>(){
   new SelectListItem(){Text="Yes",Value="YES"},
   new SelectListItem(){Text="No",Value="NO"}  
   })
   @Html.ValidationMessageFor(x=>x.Married)
        </div>
        <br />
        <input type="submit" value="Create" />
    </fieldset>
}

<br />
@Html.ActionLink("Back to List","Index","Department")

For Post the form we have to create a another action with same name with HttpPost as Attribute.

C# 
        [HttpPost]
        public ActionResult Create(FormCollection form)
        {       
            BusinessLayer bl = new BusinessLayer();
            bl.Create(form["EmployeeName"], form["Country"], form["Married"], int.Parse(form["Departments"]));
            return RedirectToAction("Details", new {                                                                          id=int.Parse(form["Departments"])});           
        }



 Businnes Logic:

    public class BusLayer
    {
        public void Create(string name, string country, string married, int departmentid)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeDbContext"].ConnectionString);
            con.Open();
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "EMP_ADD";
                cmd.Parameters.Add(new SqlParameter("@NAME", name));
                cmd.Parameters.Add(new SqlParameter("@DEPT", departmentid));
                cmd.Parameters.Add(new SqlParameter("@COUNTRY", country));
                cmd.Parameters.Add(new SqlParameter("@MARRIED", married));
                cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }
    }

OUTPUT:


SQL SCRIPT :

CREATE PROCEDURE EMP_ADD(
@NAME VARCHAR(100),
@DEPT VARCHAR(100),
@COUNTRY VARCHAR(20),
@MARRIED VARCHAR(4)
)
AS
BEGIN

SET NOCOUNT ON

      INSERT INTO
      EMPTABLE(
                        NAME,
                        DEPTID,
                        COUNTRY,
                        MARRIED
                  )
      VALUES(
                        UPPER(@NAME),
                        @DEPT,
                        UPPER(@COUNTRY),
                        UPPER(@MARRIED)
                  )

SET NOCOUNT OFF  
     
END



When the Form is submitted  the values and controls are submitted as form collection to the action, so each and every control is stored as Key value pairs.

Friday 27 December 2013

Creating a Model using entity framework in MVC

         In this article we are going to see how to create a model using entity framework and used it in the Application. Let we take a scenario that the List out the employee information based on the employee id as input.


Sql  Script:

CREATE TABLE EMPTABLE
(
      ID INT IDENTITY(1,1),
      NAME VARCHAR(200),
      COUNTRY VARCHAR(400),
      MARRIED VARCHAR(200)
)

INSERT INTO EMPTABLE(NAME,COUNTRY,MARRIED)
VALUES('RAJESH','INDIA','NO')
INSERT INTO EMPTABLE(NAME,COUNTRY,MARRIED)
VALUES('SURESH','US','NO')
INSERT INTO EMPTABLE(NAME,COUNTRY,MARRIED)
VALUES('KISHORE','US','YES')
INSERT INTO EMPTABLE(NAME,COUNTRY,MARRIED)
VALUES('PREM KUMAR','UK','NO')




Html:
@model TestingMvc.Models.Employee

@{
    ViewBag.Title = "Employee Data";
}

<h2>Employee Information</h2>

<table style="border:2px solid gray">
<tr>
<td><b>ID</b></td><td style="padding:5px">@Model.EmployeeId</td>
</tr>
<tr>
<td><b>Name</b></td><td style="padding:5px">@Model.EmployeeName</td>
</tr>
<tr>
<td><b>Country</b></td><td style="padding:5px">@Model.Country</td>
</tr>
<tr>
<td><b>Married</b></td><td style="padding:5px">@Model.Married</td>
</tr>
</table>



Now we concentrate on Code part:

Create a Model Class for Employee and the parameters and map that with actual name of the table and column with the attributes.

[Table("EMPTABLE")]
    public class Employee
    {
        [Column("ID")]
        public int EmployeeId { set; get; }

        [Column("NAME")]
        public string EmployeeName { set; get; }

        [Column("COUNTRY")]
        public string Country { set; get; }

        [Column("MARRIED")]
        public string Married { set; get; }
    }



Now create a context for that Employee Model class.

class should be derived from the Dbcontext then add the properites with DbSet Type, which means it take the set of collection values from the Model class Employee

    public class EmployeeDbContext:DbContext
    {
        public DbSet<Employee> Employees { set; get; }
    }



Now add the web.config connection string the name should be same as the context, so at the runtime engine will search for that name in the connection string. Place the connection string in the root web.config.

<connectionStrings>
    <add name="EmployeeDbContext" connectionString="Data Source=rajesh-PC\sqlserver2008;Initial Catalog=SampleDb;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
  </connectionStrings>

C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestingMvc.Models;

namespace TestingMvc.Controllers
{
    public class EmployeeController : Controller
    {              
  public ActionResult Details()
        {
            List<Employee> emp = (new EmployeeDbContext()).Employees.ToList();
            return View(emp);
        }

    }
}  

Output:





From this article you can learn how to implement the entity framework for creating a Model and use it application.


Different Design Patterns present in the C# Dotnet Framework

In this article we are going to see the various design patterns present in the Dotnet Framework. Design Patterns are used to outline the main issues faced in the software industry.The patterns are divided in to the Three Groups

Different types of Design Patterns and there sub categories.

1. Creational Patterns
2. Structural Patterns
3. Behavioral Patterns

Creational Patterns

    Prototype Pattern
        This pattern is used to return a instance of a object by using it's prototype and the class itself create a clone of that object with in the instance.

    Factory Pattern
               Factory pattern is the implementation of creating a Instance to the user but not exposing the instance logic to the client , using Interface implementation.

    Factory Method
              It also like factory class, The object of the class is created through interface implementation but the kind of object instance is decide by the derived class not by the base class base class is a Abstract class.

    Abstract Factory
               It is an extension of the Factory pattern,  where the interface are declared in the Factories so it works in a similar way of Factory.The derived class from a abstract class returns the instance of a  class that need with Interface implementation as return type.

    Builder Pattern
               Builder pattern returns a instance from  a class based on the input , which have same interface implemented and then perform the some task before the return of instance.            

    Singleton Pattern  
               Singleton pattern creates a instance of a class which can have only one instance even though many request is given it reuses the same object to perform the operation.

Structural Patterns
    Adapter Pattern
               Converts one instance of a class in to another,it makes two class compatible.

    Bridge Pattern
               It composes objects in to tree structure.It decouples abstraction from a implementation. abstraction represents the client where from the objects will be called .

    Decorator Pattern
           It is same as the Inheritance concept.

    Composite Pattern
         It is a pattern in which each component are acts as individual so it can be separated easily.

    FlyWeight Pattern
          It is used to share the common data between the objects.

Behavioral Patterns
    
Mediator Pattern
        This pattern is used to make objects loosely coupled.

    Observer Pattern
        This pattern is when two or more objects have relationship then if the parent object is modified then it should  notify to all dependent object. Ex : Observable collection

Real time scenario : Publisher and subscriber model

    Iterator Pattern
         This pattern is used to iterate the elements from the collections. IEnumerable is the Interface is example one
 
From this article you can learn what are the design patterns present in the C# Dotnet framework.

Different Diagrams in UML

In this article we are going to see the UML diagram and the different types. UML is the abbreviation of Unified Modelling Language. UML is a universal accept way of describing software in a diagrammatic way.

There are two types of diagram
1. structural diagram
2. Behavioural diagram


Structural Diagram:
   1. Class Diagram 
       It is the main building of any object oriented solution.It consists of a starting with Class name at the top then with the attributes finally with the Methods.
 
   2. Object Diagram
It is defined as instance diagram.

   3. Component Diagram
       It describes about the structural relationship between the components.Components interact with each other by Interface.
 
   4. Deployment Diagram
       It describes the hardware of our system and the software present in that system.
 
   5. Package Diagram
This diagram shows the Dependencies between a Package in a system.




Behavioural Diagram:
   1. Use Case Diagram
This  diagram which shows the graphical representation of user involved in the system.It defines about the different functional and the interaction between the functional is defined by the diagram.

   2. Sequence Diagram
This diagram is used to specify the interaction between the objects.Process are represented as Sequentially and interaction shows as arrows

   3. Communication Diagram
This diagram is used to specify the message pass between the objects.
 
   4. StateMachine Diagram
This diagram is used to specify the behaviour of a object at a specific state.
 
   5. Activity Diagram
This diagram is used to represent the WorkFlow of a system.
 
 
From this article you can learn what are the diagram present in the UML for specify the software in diagrammatic.