ASP.NET Community Standup

ASP.NET team has started a new initiative. They are organizing weekly community standups live on Google Hangout. Anyone can join to this hangout and ask questions. They have made a website where you can find the date and time (of your time zone) of the next community standup session. You can also watch all the previous episodes on this website. This website is open source on GitHub.

I watched many of the previous episodes before and I like the conversation. The average quality of the questions are good. Today first time I joined a session and asked two questions. The questions are answered very seriously by the ASP.NET team members. If you are working with ASP.NET or want to know about new development of ASP.NET, please join the sessions and ask your questions. Your questions are being answered, it is a nice feeling and it is fun.

— Arnab

Populate drop down list from enum in ASP.NET web form

Drop down list is used to show various items on the user interface to select one from them. It is very useful specially when we have not much space in the user interface. When user click on the list then it drop with all the information, from which one can be selected. It is so common to populate a drop down list from database data. But in other case we need to populate it from other source also, like an enum. So how do we populate a drop down list from an enum?

Continue reading “Populate drop down list from enum in ASP.NET web form”

Download data as .CSV format from ASP.NET web application

CSV file is a comma separated file format. That means all the values in the file is comma separated. This is very simple and useful format to exchange data. You can create and read CSV very easily. It is in human readable as well as you can write your program logic to work with this format very easily. You need to place comma after every value in a line and at the time of reading also keep in mind. Many popular software and service also support CSV format. For example Microsoft Outlook, Gmail etc. Keep in mind that it is not hierarchical data rather it is tabular format which we can express in CSV format.

Continue reading “Download data as .CSV format from ASP.NET web application”

Model validation in ASP.NET MVC 2.0

Input validation is an important topic in software applications. We should always validate the inputs which are coming through for example input form elements. When we are working with Web Form then we can use the various validator controls for validations. Validation controls can do most of the hard working for a developer. In this post our main discussion is input validation in ASP.NET MVC 2.0

Server side validation

Input validation can be done in two places. One is at the server side and another is at the client side. Server side validation is the actual validation and we should always do that. We should not only depend on the client validation, because client validation is done at browser using some client side scripting like JavaScript. One can easily turn off JavaScript in browser and can able to push invalid data to our application. Server side validation is the safe guard of this kind of problems. If our validation logic has some business rule then we should do that only in server side, because any one can easily see the client side JavaScript code.

Client side validation

On the other hand client side validation is for performance. Because to execute server side validation every time the form needs to be submitted. If we do client side validation then before submitting the form to server our input data can be validated. The user can get a better experience with our application.

Both side

So the summary is we should do input validation at both side. Client side is for performance and server side is for the actual validation and the safe guard. If the input data can or can not be validated at client side then server side always validate it. If some one intentionally disable JavaScript or using some old browser also can not push invalid data to our application because of the server side validation.

Validation with ASP.NET MVC

ASP.NET MVC is for better and maintainable patterns for projects. Here we should not put any logic in views. So how we can do input validation in ASP.NET MVC? The answer is we should do input validation at models. Models can be use in various views and controller in MVC. If we do our validation at model level then it will be DRY (don’t repeat yourself) enough to maintain. Also you can use a view specific model for this job.

ASP.NET MVC also provide some functionality using them we can declaratively implement our validation logic which are so common like required field, compare field, regular expression etc. We can also do our custom validation logic by extending the framework’s existing logic.

Here a short example of the model class with various input validation logic in place with declarative approach.

Model

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace ModelValidation.Models
{
    public class Registration
    {
        [Required(ErrorMessage = "Please enter name.")]
        [StringLength(20, ErrorMessage = "Name must be 20 char max.")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter phone number.")]
        [StringLength(10, ErrorMessage = "Phone number must be 10 digit max.")]
        [Display(Name = "Phone Number")]
        public long PhoneNumber { get; set; }

        [Required(ErrorMessage = "Please enter email.")]
        [StringLength(20, ErrorMessage = "Email must be 20 char max.")]
        [DataType(DataType.EmailAddress)]
        [RegularExpression(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", ErrorMessage = "Please enter valid email id.")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter user name.")]
        [StringLength(20, ErrorMessage = "User name must be 20 char max.")]
        [Display(Name = "User Name")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Please enter password.")]
        [StringLength(20, MinimumLength = 6, ErrorMessage = "Password name must be in between 6 to 20 char.")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Compare("Password", ErrorMessage = "Password and confirm pssword must match")]
        [Display(Name = "Confirm Password")]
        [DataType(DataType.Password)]
        public string ConfirmPassword { get; set; }

        public Address AddressDetails { get; set; }
    }

    public class Address
    {
        [Required(ErrorMessage = "Please enter Street name.")]
        [StringLength(20, ErrorMessage = "Streen name must be 20 char max.")]
        [Display(Name = "Street Name")]
        public string StreetName { get; set; }

        [Required(ErrorMessage = "Please enter state.")]
        [StringLength(20, ErrorMessage = "State must be 20 char max.")]
        public string State { get; set; }

        [Required(ErrorMessage = "Please enter country.")]
        [StringLength(20, ErrorMessage = "Country must be 20 char max.")]
        public string Country { get; set; }
    }
}

Repository

public interface IRegistrationRepositary
{
    void Register(Registration reg);
}

public class RegistrationRepositary : IRegistrationRepositary
{
    public void Register(Registration reg)
    {
        // Save new Registration to DB here...
    }
}

Controller

using System.Web.Mvc;
using ModelValidation.Models;

namespace ModelValidation.Controllers
{
    public class RegistrationController : Controller
    {
        public IRegistrationRepositary RegisterRepo { get; set; }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            if (RegisterRepo == null)
            {
                RegisterRepo = new RegistrationRepositary();
            }
            base.Initialize(requestContext);
        } 

        //
        // GET: /Registration/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Registration/Create

        [HttpPost]
        public ActionResult Create(Registration reg)
        {
            try
            {
                // Cleck model state valid or not.
                if (ModelState.IsValid) 
                {
                    // Call the repositary to save the data.
                    RegisterRepo.Register(reg); 
                }
                else
                {
                    return View();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

So we can see here that validating the model state is easy at our controller level.

// Cleck model state valid or not.
if (ModelState.IsValid) 
{
    RegisterRepo.Register(reg);
}

This will enable our server side input validation. For client side validation we simply needs to activate it at view level. The same logic will be implemented at client side using JavaScript.

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>

<% Html.EnableClientValidation(); %> 

If you are using any object relational model which generated model class with designer tool like Entity Framework database first or model first approach then you can do the following procedure for model validation.

Suppose we have a model class ‘Employee’ which is generated by Entity Framework designer tool.

using System.ComponentModel.DataAnnotations;

namespace ModelValidation.Models
{
    [MetadataType(typeof(EmployeeValidation))]
    public partial class Employee
    {
    }

    public class EmployeeValidation
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Please enter name.")]
        [StringLength(10)]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter department.")]
        [StringLength(10)]
        public string Department { get; set; }
    }
}

Now it will be validated with same approach.

Basic Introduction of ASP.NET MVC

MVC is a fresh experience for the Microsoft ASP.NET developer. Last one year I am working with this framework. The most important thing is that ASP.NET MVC build on top of .NET Framework and can take advantage of the exiting .NET features like CLR, BCL, JIT etc. For one who is using ASP.NET Web Form it will be a good fresh experience like me.

What is ASP.NET MVC?

It is always good practice to build application which have different layers and they have less strong dependencies between them. By doing so we can gain some advantages like parallel development, maintainable code, testable code etc. When we are using ASP.NET Web Form then it can not be fully possible, because Web Form having tight relation between presentation layer and application logic by code behind files. We can not test the presentation layer easily because it has tight relation with ASP.NET runtime. The code behind files always hold the application logic and we can not easily decouple it with the aspx page.

On the other hand MVC has three layer with the name Model, View and Controller. Model means the domain objects of our application. View means the pure presentation layer with out any application logic (we should not write any logic here) and the Controller means the application logic of our application. So here the Controller is responsible to populate the model with data and call the view to create the presentation. By using this three layer you can divide the responsibilities. MVC has the option to heavy use of interfaces and dependency injection, so that we can test every layers of the application (also we should create a wrapper for the static classes for testability). We can test the Controller with out any dependencies with the ASP.NET runtime.

ASP.NET MVC is light weight. Almost every component is pluggable here. Like you can use a different view engine or a different validation framework in ASP.NET MVC. Microsoft also implement it as a convention over configuration in mind. That means many things are done simply following the convention, you do not have to be configure it explicitly. For example views are kept on particular folders with the same name of the controller and the controller can find them with out any more coding from the developer’s end. I think the most exiting feature of ASP.NET MVC is model binding. You can create a view specific model and can create a strongly typed view with that model. It will actually render and populate the model object for you. Another fine feature is attribute based model validation in ASP.NET MVC. We can declare attribute for our validation on model properties. By which our validation logic will be DRY (don’t repeat yourself) enough so that where we are using that model our validation will be in one place, easy to maintain. You can also extends validation logic in ASP.NET MVC.

MVC
MVC

Basic demo

Here a small and very basic sample of ASP.NET MVC:

Model:

using System.Collections.Generic;

namespace MvcApplication4.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }

    public class EmployeeDB
    {
        public List<Employee> GetAll()
        {
            // In real application data may be coming from database.
            return new List<Employee>()
            {
                new Employee(){ Id = 1, Name = "Rahul", Department = "Software" },
                new Employee(){ Id = 2, Name = "Mita", Department = "HR" },
                new Employee(){ Id = 3, Name = "Bob", Department = "Sales" },
            };
        }
    }
}

Controller:

using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication4.Models;

namespace MvcApplication4.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            EmployeeDB empDB = new EmployeeDB();
            IList<Employee> emps = empDB.GetAll(); // Get the data.
            return View(emps); // Return view with model data.
        }
    }
}

View:

<%@ Page 
    Title="" 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication4.Models.Employee>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Index</h2>

    <table>
        <tr>
            <th></th>
            <th>Id</th>
            <th>Name</th>
            <th>Department</th>
        </tr>
    <% foreach (var item in Model) 
       { %>
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id = item.Id }) %> |
                <%: Html.ActionLink("Details", "Details", new { id = item.Id })%> |
                <%: Html.ActionLink("Delete", "Delete", new { id = item.Id })%>
            </td>
            <td><%: item.Id %></td>
            <td><%: item.Name %></td>
            <td><%: item.Department %></td>
        </tr>
    <% } %>
    </table>

    <p><%: Html.ActionLink("Create New", "Create") %></p>

</asp:Content>

For more information on ASP.NET MVC please take a look here