Saturday, 31 August 2013

Learning MVC-Part 3 : Creating MVC Application & Perform CRUD Operations Using EntityFramework

                                      In our first and second attempt to learn MVC, we learnt, what is MVC?, what is separation of concerns?, how to create a simple MVC application and perform CRUD operations on the application using LINQ to SQL.
My this article focuses on how to perform CRUD operations in MVC application by the use of an ORM(Entity Framework).
The article is an attempt to overcome the confusion related to how to use EntityFramework with MVC application in a very simple way.

Share/Bookmark

Wednesday, 28 August 2013

Learning MVC-Part 2 :Creating MVC Application & Perform CRUD operations using LINQ to SQL


Introduction:
                           In first part of the tutorial series we got a glimpse of MVC. In this part we’ll focus on practical implementation of MVC Pattern. I don’t need to  explain about theory of MVC as we have already covered this in previous part of the article.

Share/Bookmark

Tuesday, 27 August 2013

Learning MVC-Part 1 : Introduction to MVC Architecture and Separation of Concerns

Introduction:

 
After having gone through numerous of blogs and articles, I came to a conclusion that very few of the genuine writers have explained the topic from basics to its details in a full-fledged way with a working application. My effort in this MVC articles series would be to cover almost all the aspects of MVC starting from creating simple app and connecting with the database with various Microsoft providers. We’ll be gradually moving forward part by part to understand and practically implement all the scenarios.

Road Map:




All set, now we can start our journey with Part1.

Part1: Introduction to MVC architecture and Separation of Concerns.

Topics to be covered:
  • 1.     What does MVC mean.
  • 2.     Understand MVC Architecture.
  • 3.     Separation of Concerns


Players:

Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.

View: The user interface that renders the model into a form of interaction.

Controller: Handles a request from a view and updates the model that results a change in Model’s state.

To implement MVC in .NET we need mainly three classes (View, Controller and the Model).

MVC Architecture:

           The choice of MVC comes when we go for a solution where separation of concerns, ease of maintainability and extensibility of an application matters a lot. As per the architecture given below, we can see the request-response flow of a MVC application.

The architecture is self explanatory in itself. Browser as usual sends a request to IIS,IIS searches for the route defined in MVC application and passes request to the controller as per route, the controller communicates with model and passes the populated model(entity) to View(front end), Views are populated with model properties, and are rendered on the browser, passing the response to browser through IIS via controllers which invoked the particular View.

Separation of Concern:

As per Wikipedia 'the process of breaking a computer program into distinct features that overlap in functionality as little as possible'. MVC design pattern aims to separate content from presentation and data-processing from content. Theoretically well, but where do we see this in MVC? One is reasonably clear - between the data-processing (Model) and the rest of the application.
When we talk about Views and Controllers, their ownership itself explains separation.The views are just the presentation form of an application, it does not have to know specifically about the requests coming from controller. The Model is independent of View and Controllers, it only holds business entities that can be passed to any View by controller as per need of exposing them to end user.The controller in independent of Views and Models, its sole purpose is to handle requests and pass it on as per the routes defined and as per need of rendering views.Thus our business entities(model), business logic(controllers) and presentation logic(views) lie in logical/physical layers independent of each other.

Conclusion:

Now we know why and where to use MVC, in another part of learning MVC we’ll be creating a MVC application from scratch, exploring the practical implementation of MVC.

Read more:

Other Series

My other series of articles:
For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.



Share/Bookmark

Sunday, 25 August 2013

Foreach loop Internals

A Foreach loop automatically produces a Cast to the object you pass. So its sometimes irrelevant to use var inside foreach loop.

Share/Bookmark

Javascript Alert in C#

Code:

/// <summary>
/// A JavaScript alert 
/// </summary>
public static class Alert
{
    /// <summary>
    /// Shows a client-side JavaScript alert in the browser.
    /// 
</summary>

    /// <param name="message">The message to appear in the alert.
</param>

    public static void Show(string message)
    {
        // Cleans the message to allow single quotation marks
        string cleanMessage = message.Replace("'""\\'");
        string script = string.Format("<script type=\"text/javascript\">$(document).ready(function(){alert('{0}');});</script>", cleanMessage);

        
// Gets the executing web page

        Page page = HttpContext.Current.CurrentHandler as Page;

        
// Checks if the handler is a Page and that the script isn't all ready on the Page

        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))

        {

            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);

        }

    }

}

Share/Bookmark

Session Helper Class (Facade)

                                                         
Code:

 using System.Web;
/// <summary>
/// Static Session facade class
/// </summary>
public static class SessionHelper
{
# region Private Constants
private const string userId = "UserId";
private const string projectId = "ProjectId";
# endregion
#region Private Static Member Variables
private static HttpContext thisContext;
#endregion
#region Public Static Methods
/// <summary>
/// Clears Session
/// </summary>
public static void ClearSession()
{
HttpContext.Current.Session.Clear();
}
/// <summary>
/// Abandons Session
/// </summary>
public static void Abandon()
{
ClearSession();
HttpContext.Current.Session.Abandon();
}
#endregion
#region Public Static Properties
/// <summary>
/// Gets/Sets Session for UserId
/// </summary>
public static string UserId
{
get
{
if (HttpContext.Current.Session[userId] == null)
return "";
else
return HttpContext.Current.Session[userId].ToString();
}
set { HttpContext.Current.Session[userId] = value; }
}
public static string ProjectId
{
get
{
if (HttpContext.Current.Session[projectId] == null)
return "";
else
return HttpContext.Current.Session[projectId].ToString();
}
set { HttpContext.Current.Session[projectId] = value; }
}
#endregion
}
//Use as: SessionHelper.UserId="user1";
//        string user=SessionHelper.UserId;
//        SessionHelper.Abandon();




Share/Bookmark

Features Added in Different Version of .Net Framework

.Net Framework 1.0 - This is the first version of .Net Framework that was released by Microsoft.

.Net Framework 1.1 - This is the 2nd major release of .Net Framework release by Microsoft. In this release it supports mobile ASP.Net controls, ODBC and Oracle Database. It also provides support for Internet Protocol version 6(I0v6).

.Net Framework 2.0 - It is part of Visual Studio 2005 and Microsoft SQL Server 2005. .Net Framework 2. Was the latest version of .Net Framework that has support Windows 2000.Net Framework 2.0 has many changes and enhancements as compared to ,Net Framework 1.1. It has a number of application programming interface changes. It contains many new personalization features for ASP.Net, for example, support for themes, skins, and web parts.

.Net Framework 3.0 - It uses the CLR version of 2.0. It contains a set of managed code APIs that form an integral part of Windows Vista and Windows Server 2008. .Net Framework 3.0 uses the same version of CLR that was incorporated with .Net Framework 2.0. It includes some new features as follows:
  1. Windows Presentation Foundation
  2. Windows Communication Foundation
  3. Windows Workflow Foundation
  4. Windows CardSpace
·.Net Framework 3.5 - .Net Framework 3.5 also uses the CLR version 2.0. In this release it supports LINQ, extension methods, lambda expression, anonymous types and built in Ajax support.

·.Net Framework 4.0 - In this release it supports PLINQ and Task Parallel Library. It supports Code Contracts and provides new types to work with arbitrary-precision arithmetic.

Read more:

Other Series

My other series of articles:

For more technical articles you can reach out to CodeTeddy.

Share/Bookmark

Use the ENUM object to manipulate Enumerated Values

Enums are a tremendously easy way to make your code understandable. In the bad old days, when working on someone else's program I'd be forced to decode code like this:
Dim cust As New Customer
cust.Type = 0
With an Enum, everything is more obvious:
Dim cust As New Customer
cust.Type = CustomerTypes.Deadbeat
What takes Enums to the next level are the static methods built into the Enum class. For instance, if I want to turn an Enum into an array of strings, I can use the Enum class's GetNames method:
Dim cTypes As String() = [Enum].GetNames(GetType(CustomerTypes))
Because of the way Visual Basic handles names, Enum has to be enclosed in brackets to prevent syntax errors. C# doesn't require those brackets:
string[] cTypes = Enum.GetNames(typeof(CustomerTypes));
I can then bind the output from GetNames to any listing control to get a list of the names in the Enum displayed in my user interface:
MyListBox.ItemsSource = Enum.GetNames(typeof(CustomerTypes));
GetNames shows the basic structure of the Enum class's static methods: the first parameter to any method is always the Type of the Enum you want to work with. For instance, if you have code in a Web Service that's passed the value of an Enum, you can convert that value into the name of the corresponding Enum entry using the Enum class's GetName method. As before, the first parameter is the type of the Enum; the second parameter is the value you're looking up:
Dim inputValue As Integer = 1
Me.MyTextBox.Text = [Enum].GetName(GetType(CustomerTypes), inputValue)
Parse goes one better and converts a string containing one of the names in an Enum into the Enum item itself. This code, for instance, sets the Customer object's Type property to the appropriate Enum item based on a string value:
Dim custTypeString As String = "DeadBeat"
cust.Type = [Enum].Parse(
GetType(CustomerTypes), custTypeString);
Visual Basic doesn't require the explicit cast to use Parse:
string custTypeString = "DeadBeat";
cust.Type = (CustomerTypes) Enum.Parse(
typeof(CustomerTypes), custTypeString);
If the string value you're passing to Parse isn't an item in the Enum, the Parse method throws an exception. To avoid that, you can use the Enum's TryParse method which, while it still won't do the conversion, won't throw an exception either. An even better answer is to use the Enum's IsDefined method to see if the item exists before trying to retrieve it:
if (Enum.IsDefined(typeof(CustomersType), custTypeString))
{
Customers ctype = (CustomersType) Enum.Parse(
typeof(CustomersType), custTypeString);
}
else
{
ErrorLabel.Text = "Not a valid customer type.";
}
(Taken from a blog.)

Share/Bookmark

ASP.Net Grid View Sorting using jQuery


The Article explains how to implement Sorting in Asp.Net Grid View using jQuery,
Just open the solution, and you’ll get to see the js file used to perform sorting on the GridView we have in Asp.Net aspx page.



The sorting is done on the basis of css class names provided in Style.css.
Just run the solution, and you’ll get to see that grid is sorted on the basis of string, date and numbers as well.

You can implement and extend this solution in your existing/new website.

Happy Coding J.

Share/Bookmark

Wednesday, 21 August 2013

CRUD Operations using AutoMapper in C# MVC Application

Download Source Code         

Introduction:

In our article series of Learning MVC, we learnt a lot about MVC, about various techniques to communicate to database in MVC applications, and few internal concepts too.
When we indulge into realtime programming environment, we face not only one but many type of challenges in the code.My this article explains a new concept Auto Mapper in MVC application to overcome one of the major challenge we face while communicating with data entities and binding them to our model.

Challenge:

Sometimes while interacting with real time(database) entities and binding our model to them, we end up in a situation like,

var dbContext = new MyDBDataContext();
var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
var user = new LearningMVC.Models.User();
            if (userDetails != null)
            {
                user.UserId = userDetails.UserId;
                user.FirstName = userDetails.FirstName;
                user.LastName = userDetails.LastName;
                user.Address = userDetails.Address;
                user.PhoneNo = userDetails.PhoneNo;
                user.EMail = userDetails.EMail;
                user.Company = userDetails.Company;
                user.Designation = userDetails.Designation;
            }
 return View(user);

The above mentioned code is not very hard to understand ,In the above code, an instance var dbContext = new MyDBDataContext(); is created from a LinqTOSql Context class, there after user details from a Users specific table have been fetched and stored in var userDetails variable.We had an existing model named User(LearningMVC.Models.User()), that has similar properties as that of Users class generated from database, now we initialize properties of instance of our model from properties of instance of User class from database, so that we can populate our View in a MVC application.
We see here there are 8 properties that are similar to each other but each set lies in separate class, one in Model, and one in Users class.And what we do is one by one we bind these properties to our model and pass it to View.Now problem is what if we have 100 column records coming from database, and also our model have same no. of properties, and the code has to be repeated 6-7 times at different scenarios, now do we still follow such strategy of binding each property from db to model, trust me the code will be 100 pages large, and will be charging 5 times the effort just to bind the model from domain entities.
To overcome this tedious situation AutoMapper is introduced.It not only reduces the effort, but also limits the execution time that has been taken by such a large no. of lines to execute.

Auto Mapper:

AutoMapper is a open source provided in GitHub.
As per the AutoMapper CodePlex web page  "AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper's established conventions, almost zero configuration is needed to map two types." therefore, it provides the solution for our mapping issue.

                   



Install AutoMapper:

Firstly install the NuGet Package Manager in your Visual Studio IDE. Once done,go to
Tools -> Library Packet Manager -> Packet manager Console
Then in the console window opened at bottom of Visual Studio, type:

PM> Install-Package AutoMapper

Press Enter, this will install AutoMapper and when next time you open MVC application in Visual Studio , it will automatically add dll reference to project.



AutoMapper in Action:

Lets Create an MVC application first, you can create an MVC application, and connect it with database using LINQ to SQl following my article http://www.codeproject.com/Articles/620197/Learning-MVC-Part-2-Creating-MVC-Application-and-P

I have also attached the code of Existing MVC application used without AutoMapper.
Now let’s evaluate all the Controller Actions one by one and convert the code using AutoMapper.

Step1: Create database for existing application, the databse script is attached with the source code,




Open Existing MVC Application in Visual Studio,



See that AutoMapper is referenced in project, now use that namespace in MyController,as,



Step2: Index Action:

In the very first Action of our controller MyController(Can be found under Controllers folder), Index Action, we see the code,

public ActionResult Index()
        {
            var dbContext = new MyDBDataContext();
            var userList = from user in dbContext.Users select user;
            var users = new List<LearningMVC.Models.User>();
            if (userList.Any())
            {
                foreach (var user in userList)
                {
                    users.Add(new LearningMVC.Models.User()
                        {
                            UserId = user.UserId,
                            Address = user.Address,
                            Company = user.Company,
                            FirstName = user.FirstName,
                            LastName = user.LastName,
                            Designation = user.Designation,
                            EMail = user.EMail,
                            PhoneNo = user.PhoneNo
                        });
                }
            }
         
            return View(users);
        }

Now where will AutoMapper fit in here, you know that, it will be used to replace the property mapping done one by one in the code, therefore,
Just at the first line of code, define a AutoMap,
To create the default mapping, call the Mapper.CreateMap<T1, T2>() with proper types. In this case, T1 will be LearningMVC.User and T2 will be LearningMVC.Models.User

Mapper.CreateMap<LearningMVC.User, LearningMVC.Models.User>();

LearningMVC.User -> DTO Object Class

LearningMVC.Models.User -> Model Class to bind the View

So, here we define a mapping between, DTO and Model class with the help of AutoMapper class.
Now inside foreach loop, replace the whole code by,

LearningMVC.Models.User userModel = Mapper.Map<LearningMVC.User, LearningMVC.Models.User>(user);
users.Add(userModel);

Finally call the Mapper.Map<T1, T2>(obj1) to get the mapped object of T2.
So, our final Action code,
  public ActionResult Index()
        {
            Mapper.CreateMap<LearningMVC.User, LearningMVC.Models.User>();
            var dbContext = new MyDBDataContext();
            var userList = from user in dbContext.Users select user;
            var users = new List<LearningMVC.Models.User>();
            if (userList.Any())
            {
                foreach (var user in userList)
                {
                    LearningMVC.Models.User userModel = Mapper.Map<LearningMVC.User, LearningMVC.Models.User>(user);
                    users.Add(userModel);
                }
            }
         
            return View(users);
        }
 We see now, we escaped that boring work of matching properties one by one.Now run the application, and you’ll see the application running as before.



Step 3: Details Action:

Existing Code

public ActionResult Details(int? id)
        {
            var dbContext = new MyDBDataContext();
            var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            var user = new LearningMVC.Models.User();
            if (userDetails != null)
            {
                user.UserId = userDetails.UserId;
                user.FirstName = userDetails.FirstName;
                user.LastName = userDetails.LastName;
                user.Address = userDetails.Address;
                user.PhoneNo = userDetails.PhoneNo;
                user.EMail = userDetails.EMail;
                user.Company = userDetails.Company;
                user.Designation = userDetails.Designation;
            }
            return View(user);
        }

New Code with AutoMapper

public ActionResult Details(int? id)
        {
            var dbContext = new MyDBDataContext();
            Mapper.CreateMap<LearningMVC.User, LearningMVC.Models.User>();
            var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            LearningMVC.Models.User user = Mapper.Map<LearningMVC.User, LearningMVC.Models.User>(userDetails);
            return View(user);
        }


Step4: Create Action (POST)

Existing Code

[HttpPost]
        public ActionResult Create(LearningMVC.Models.User userDetails)
        {
            try
            {
                var dbContext = new MyDBDataContext();
                var user = new User();
                if (userDetails != null)
                {
                    user.UserId = userDetails.UserId;
                    user.FirstName = userDetails.FirstName;
                    user.LastName = userDetails.LastName;
                    user.Address = userDetails.Address;
                    user.PhoneNo = userDetails.PhoneNo;
                    user.EMail = userDetails.EMail;
                    user.Company = userDetails.Company;
                    user.Designation = userDetails.Designation;
                }
                dbContext.Users.InsertOnSubmit(user);
                dbContext.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

New Code with AutoMapper

[HttpPost]
        public ActionResult Create(LearningMVC.Models.User userDetails)
        {
            try
            {
                Mapper.CreateMap<LearningMVC.Models.User, LearningMVC.User>();
                var dbContext = new MyDBDataContext();
                var user = Mapper.Map<LearningMVC.Models.User, LearningMVC.User>(userDetails);
                dbContext.Users.InsertOnSubmit(user);
                dbContext.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

Note that, in here we interchanged the mapping, because now we had to read from Model and bind to our DTO fror Create Action, so just interchange the mapping, and run the application,Now our T1 is Model and T2 is DTO.

Step5: Edit Action:

Existing Code

  public ActionResult Edit(int? id)
        {
            var dbContext = new MyDBDataContext();
            var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            var user = new LearningMVC.Models.User();
            if (userDetails != null)
            {
                user.UserId = userDetails.UserId;
                user.FirstName = userDetails.FirstName;
                user.LastName = userDetails.LastName;
                user.Address = userDetails.Address;
                user.PhoneNo = userDetails.PhoneNo;
                user.EMail = userDetails.EMail;
                user.Company = userDetails.Company;
                user.Designation = userDetails.Designation;
            }
            return View(user);
        }

New Code with AutoMapper

public ActionResult Edit(int? id)
        {
            Mapper.CreateMap<LearningMVC.User, LearningMVC.Models.User>();
            var dbContext = new MyDBDataContext();
            var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            var user = Mapper.Map<LearningMVC.User, LearningMVC.Models.User>(userDetails)
            return View(user);
        }


Step6: Delete Action:

Existing Code

public ActionResult Delete(int? id)
        {
            var dbContext = new MyDBDataContext();
            var user = new LearningMVC.Models.User();
            var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            if (userDetails != null)
            {
                user.FirstName = userDetails.FirstName;
                user.LastName = userDetails.LastName;
                user.Address = userDetails.Address;
                user.PhoneNo = userDetails.PhoneNo;
                user.EMail = userDetails.EMail;
                user.Company = userDetails.Company;
                user.Designation = userDetails.Designation;
            }
            return View(user);
        }

New Code using AutoMapper

public ActionResult Delete(int? id)
        {
            var dbContext = new MyDBDataContext();
            Mapper.CreateMap<LearningMVC.User, LearningMVC.Models.User>();
            var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            var user = Mapper.Map<LearningMVC.User, LearningMVC.Models.User>(userDetails);
            return View(user);
        }



 ForMember() and MapFrom() in AutoMapper:

 The two important functions in AutoMapper play an important role in object mapping, Suppose our model/viewmodel class have a property as FullName, and from the DTO we want to add the FirstName and Last Name of the user to make it a full name nad bind it to model,to overcome these kind of scenarios ForMember() and MapFrom() come in action,See below code,

Mapper.CreateMap<LearningMVC.User, LearningMVC.Models.User>().ForMember(emp => emp.Fullname,
                            map => map.MapFrom(p => p.FirstName + " " + p.LastName));

Here we are saying that ForMember FullName in our model class, map properties from FirstName and LastName of User DTO.
The code is itself self explanatory.
This kind of mapping is also called Custom Mapping.

Conclusion:

In this article we learnt how to do custom mapping and entity to entity mapping with the help of AutoMapper. Since this was just a glimpse of the concept there is lot more to explore in this topic in detail.
I have skipped the POST methods for Edit and Delete, this will be a kind of homework for you. Once you completely follow and understand, you can easily complete those two pending Actions as well.Let me see the source code J as well.





Share/Bookmark