Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Monday, April 14, 2014

Using stored procedures in Entity Framework Model First Approach (Part I - Adding New Stored procedure)

Before starting with this article I will expect that you have a basic idea on the Entity Framework - Model First approach and its use.

Here I am explaining the step by step approach how to use a newly created stored procedure in our C# code through the EntiFramework. Let say we have created a new procedure named as 'GetAllPersons', now we can follow the below steps :-

STEP I (Open EDMX file right click and choose the option 'Update Model from Database...') :



STEP II (Now in this below screen choose save entity connection string in Web.Config as the name given at the time of creation. Then click on NEXT.) : 


STEP III (Select 'Add' tab and there select the particular stored procedure you want to add to entity model) :

Unselect the option 'Pluralize or singularize object names' and click on FINISH button.


STEP IV(Rename the Entity added automatically.) :

Open the Model Browser now and we can see the 3 things added automatically in entity model like :-
StoredProcedure - The procedure we added recently.
Function Import - Function which actually will be called in code by the object of the entity context.
ComplexType - The entity returned by the SP or the Function generated.

These Function and ComplexType can be renamed as we want them.

Rename the ComplexType name as our feasibility :-



STEP V(Edit the Function Import as per requirement):

Open the function import in EDIT mode.

Rename the function and select appropriate Stored Procedure and ComplexType.
 After editing done :-
STEP VI(Finish & Run Custom Tool):

Now after all the changes are being done to make the latest change available in code we have to run the custom tool as mentioned in below image. This step is to update the classes from the model to avail latest changes made to it in code behind.

For more information on this custom tool and tt files please refer to the description here.

STEP VII(Get result in code file) :

To get the list of all the Persons as returned by the function imported :-

Create the object of the Entity context class,
Test_SPEntities objTestSPEntity = new Test_SPEntities();

Call the function and get the result as list of the particular Complex Type,
List<GetAllPersonsEntity> listAllPersons = objTestSPEntity.GetAllPersons().ToList();


Hope this will be definitely of help for the guys who just started with basics of the Entity Framework.

Monday, November 18, 2013

What is ASP.Net MVC Routing and why is it needed, explained.

Introduction : The ASP.Net Routing framework is at the core of every ASP.Net MVC request and it is simply a pattern-matching system. At the application start-up it registers one or more patterns with route table of the framework to tell it what to do with the pattern matching requests. For routing main purpose is to map URLs to a particular action in a specific controller.

When the routing engine receives any request it first matches the request URL with the patterns already registered with it. If it finds any matching pattern in route table it forwards the request to the appropriate handler for the request. If the request URL does not matches with any of the registered route patterns the routing engine returns a 404 HTTP status code.

Where to configure :
Global asax

How to configure :
ASP.Net MVC routes are responsible for determining which controller methods to be executed for the requested URL. The properties for this to be configured are :-

Unique Name : A name unique to a specific route.
URL Pattern : A simple URL pattern syntax.
Defaults : An optional set of default values for each segments defined in URL pattern.
Constraints : A set of constraints to more narrowing the URL pattern to match more exactly.

The RegisterRoute method in RouteConfig.cs file :-
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // ignore route with extension .axd

            routes.MapRoute(
                name: "Default", // Name of the route
                url: "{controller}/{action}/{id}", // pattern for the url
                defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional } // default values                 for each section
            );
        }

    }

Then in Global.asax.cs file call this on application start event handler so that this will be registered on application start itself :-

protected void Application_Start()
{
     RouteConfig.RegisterRoutes(RouteTable.Routes);

}

How Routing engine Works :-

Route Matching :-



Hope this will give a clear understanding on what is routing and how routing engine works ....

Tuesday, November 5, 2013

MVC - Introduction to ASP.Net MVC & its architecture.

What is ASP.Net MVC ?

Microsoft ASP.Net MVC is a framework to build web applications which is built on top of the Microsoft's .Net Framework. It is mostly emphasized on a loosely coupled application architecture and highly maintainable code. It was fully functional with Microsoft's Visual Studio 2011 to create fully functioning ASP.Net MVC web application.


Evolution of MVC :

ASP : This was the first scripting language by Microsoft for web development in which code and markup are authored together in  a single file with each single file corresponding to a page on the website.

ASP.Net Web Forms : Then the next web forms came into picture which provides some separation of code and markup by splitting the web content into two different files : one for markup & another for code.

MVC : The first version released in 2008 and this was totally different than page based approach. This was an revolution from page based architecture to MVC architecture. But both are still based on the top of the common frameworks.


MVC Architecture:

This new MVC architecture encourages strict isolation between the individual parts of an application and works following the loose coupling.
Benefits of this loose coupling :-
Development - All individual components are independent of each other so they can be more easily developed in isolation. Also they can be easily replaced or substituted.
Testing - Due to loose coupling of components it gives the ability for components to be easily swapped with mock representations(avoid making calls to a database,
by replacing the component that makes database calls with one that simply returns
static data) greatly facilitates the testing process.
Maintenance - Isolated component logic means that changes can be typically isolated to a small number of components—often just one. 


Model : The model contains the core business logic and data. It encapsulates the properties and behaviors of a domain entity and exposes the properties which describes it. Ex :-
The Teacher class represents the concept of an “teacher” in the application
and may expose properties such as Name and SubjectID, as well as exposing behavior
in the form of methods such as Teach().

View : The View is mainly used for representing the models into a user friendly visual representation. This is mainly the HTML to be rendered in the browser.

It has many forms like model can be visualized in HTML, PDF, XML or even in spreadsheets as well. The business logic to make the data to be compatible to be viewed through Views will remain in model itself.

Controller : The controller mainly controls the application logic and works as a coordinator between View and Model. It receives input from users via View and passes back the results to the view to display them to user.

Wednesday, October 23, 2013

Passing Data [View-to-Controller, Controller-to-View & Controller-to-Controller in ASP.Net MVC]



View-to-Controller :

Let us first discuss how to pass data from a ASP.Net MVC View to Controller. There are four ways to pass the data from View to Controller which are being explained below :-

1) Traditional Approach: In this approach we can use the request object of the HttpRequestBase class. This object contains the input field name and values as name-value pairs in case of the form submit. So we can easily get the values of the controls by their names using as indexer from the request object in the controller.
Ex :-
        Let say you are having a input in the form with name 'txtName' then its values can be retrieved in controller from request object like as below :
                     string strName = Request["txtName"].ToString();

2) Through FormCollection: We can also get post requested data by the FormCollection object. This object also has requested data as the name/value collection as the Request object. 
Ex :             
[HttpPost]
public ActionResult Calculate(FormCollection form) 
{
        string strName = form["txtName"].ToString();
        . . . . . . . . . . . . . . . . . . . . 
}

3) Through Parameters: We can also pass the input field names as parameters to the post action method by keeping the names same as the input field names. These parameters will have the values for those fields and the parameter types should be string. Also no need to define the parameters in any specific sequence.

Ex : 
[HttpPost]
public ActionResult Calculate(string txtName)
{
    string strName = Convert.ToString(txtName);
    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 
}

           In all of the above approaches we need to even convert the non-string type to string type due to which if any parsing fails then the entire action may fail here. Here we have to convert each value to avoid any exceptions but, in the below 4th approach of passing data from view to controller it reduces the amount of code.

4) Strongly type model binding to view: Here we need to create a strongly typed view which will bind directly the model data to the various fields of the page.

Ex :- 
i) Create a model with the required member variables.
Let say we have a model named 'Person' with member variable named as 'Name'
ii) Now pass the empty model to teh view as parameter in the controller action.
Ex : 
public ActionResult GetName()
{
    Person person = new Person();
    return View(person);
}
iii) Prepare the strongly typed view to display the model property values through html elements as below :-
Ex -
         <div><%= Html.Encode(person.Name) %></div>

iv) Create the action method that handles the POST request & processes the data.
Ex : 
[HttpPost]
public ActionResult GetPersonName(Person person)
{    
    return Content(person.Name.ToString());
}


Controller-to-View:

           There are three options to pass information from controller to view. Here are mentioned below :-
1) ViewData: The ViewData is a Dictionary of objects that are derived from the 'ViewDataDictionary' class and its having keys as string type and a value for respective keys. It contains a null value on each redirection and it needs typecasting for complex data types.
Ex :- Assign value in controller action like :
ViewData["PersonName"] = "Test Name";
Fetch this ViewData value in View like this - <h1><%= ViewData["PersonName"]  %></h1>

2) ViewBag: ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. It doesn't require typecasting for complex data types. It also contains a null value when redirection occurs.
Ex :- Assign value in controller action like :
ViewBag.PersonName= "Test Name";
Fetch this ViewData value in View like this - <h1><%= ViewBag.PersonName  %></h1>

3) TempData: TempData by default uses the session to store data, so it is nearly same to session only, but it gets cleared out at the end of the next request. It should only be used when the data needs only to persist between two requests. If the data needs to persist longer than that, we should either repopulate the TempData or use the Session directly.
Ex :-
In Controller : TempData["PersonName"] = "Test Name";
In View :  <h1><%= TempData["PersonName"]  %></h1>

Controller-to-Controller:

If its not private, just pass it as JSON object on the url using the third parameter in the redirect like below example :

               return RedirectToAction("ActionName", "ControllerName", new { userId = id });

If it is private data, we can use TempData - which will be removed at the end of the request after the next request reads it.