Contents tagged with ASP.NET MVC

  • elmah.io - Logging Exceptions to the Cloud

    Elmah stands for Error Logging Modules and Handlers is a great open source application logging utility for ASP.NET which is available for some time now. Some of the features provided by Elmah are given below.

    • Logging Unhandled exceptions
    • Provides a web page to view the logged exceptions
    • Also provides a web page to view all the details of a logged exception
    • Option to send an email notification when an error occurs
    • RSS feed for the last 15 errors from the log
    • Options for backing store for the log includes in-memory, SQL Server, flat file, Oracle, SQL Lite etc

    Normally when we log exceptions we will keep the info in a flat file or in the database, but Elmah got another option which is to directly store all the logs in the cloud via elmah.io without much change to your existing framework.

    Set Up  elmah.io

    First you need to create an account in elmah.io, it's pretty simple and even you can use any of social logins provided by Twitter, Facebook, Outlook or Google. Once you create the login, just create a log for your application from the dashboard. Just give a name for the log and click save. We will leave the other options for the time being. Also whenever a log is created, Elmah will create a unique id for the log, keep a note of it as we need it later when we configure it in our project.

    Setup your project to use elmah.io

    Now, in our project we need to add a Elmah logger by installing the following command in the Nuget Package Manager Console.

    Install-Package elmah.io

    Categories: Web Developement, MVC

  • RemoteValidation Attribute in ASP.NET MVC

    One great feature we have in ASP.NET MVC is ability to do client side validations using Data Annotations and it definitely save a lot of time from writing mundane client side scripts for validations such as required, number formats, email formats etc. When we decorate properties with validation attributes, the runtime will inject JavaScript automatically when the page is rendered to do that validation. But in some scenarios we will need to do the validation in the server side say in cases such as we need to verify an user exists or not when the data is entered in the text box. Most of us will invoke an ajax call on the blur event to achieve this, but in MVC there is validation attribute that can do this for you with minimal amount of code.

    Remote Validation Attribute

    Remote Validation is the process in which we perform the validation in the server side for a specific control without posting the entire form information to the server. In ASP.NET MVC, we will use the Remote attribute in the System.Web.MVC namespace to the decorate the property. Let's take an example wherein we need to validate an username exists or not when he type it in the form field.

    Step 1 : Decorate the property

    Decorate the property with the Remote attribute with first param being the action name that needs to be executed, second one is the controller name and third is the message that needs to be shown when validation fails.

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

    public class User
    {
    [Required]
    [Display(Name = "Enter Username")]
    [Remote("CheckExistingUser", "User", ErrorMessage = "Username already exists!")]
    public string UserName { get; set; }
    }

    Step 2 : Create the Action Method and Validation Logic

    Now you need to create the action method in the controller which specified in the attribute. Here I have created a method for validating the username which will return a false if the text entered in the field is admin or administrator.

    public ActionResult CheckExistingUser(string UserName)
    {
         try
         {
              return Json(ValidateUser(UserName), JsonRequestBehavior.AllowGet);
         }
         catch (Exception ex)
         {
              return Json(false, JsonRequestBehavior.AllowGet);
         }
    }
    

    private bool ValidateUser(String UserName)
    {
    	if (UserName.ToLower().Equals("admin") || UserName.ToLower().Equals("administrator"))
            	return false;
            else
    		return true;
    }
    

    Categories: Web Developement, MVC

  • Consolidate Model Validation Errors as a Single String in ASP.NET Web API

    As we all know that we can do validation in ASP.NET MVC by decorating the model with validation attributes and when the page is generated by the framework it will automatically generate the client side validation scripts. You can read more about it in the Microsoft Documentation here. Normally the output will be like in the figure given below.

    Let's see how we can use the same mechanism in ASP.NET WebAPI to do the validation. I have created a model class as shown below

    public class Employee
        {
            [Required]
            [MaxLength(50, ErrorMessage="First name should not exceed 50 characters")]
            public string FirstName { get; set; }
            [Required]
            [MaxLength(50, ErrorMessage="Last name should not exceed 50 characters")]
            public string LastName { get; set; }
            [Required]
            [MaxLength(200, ErrorMessage="Address should not exceed 200 characters")]
            public string Address { get; set; }
            [Required]
            [EmailAddress(ErrorMessage="Email is invalid")]
            [MaxLength(50, ErrorMessage="EmailAddress should not exceed 50 characters")]
            public string EmailAddress { get; set; }
        }
    

    And created a POST method as given below which basically validates the model and if any errors are found then returns an error as response.

    public HttpResponseMessage Post([FromBody] Employee emp)
            {
                if (!ModelState.IsValid)
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ModelState);
                return Request.CreateResponse(HttpStatusCode.Created, emp);
            }
    

    Categories: C#, Web Developement, MVC, Web API

  • Model First Development Using EF 5.0 – Updating the Model

    In my earlier post, Getting started with Model First development using EF, I have shown you to create a database from the model class and how to persist the data to the database. In the second part of the series, I am going to show how the changes made to the underlying database can be reflected in the model class.

     

    So let’s try to add a column to our user table.

    ALTER TABLE MT_USER
    ADD Gender Varchar(5)

     

  • Getting Strated with Model First Development using Entity Framework.

    What is Model First ?

     

    In Model First approach you will create a model of your domain entity using the EF designer and then generate database schema based on it. It stores the meta data in a EDMX file and model classes that interact with our business objects are automatically created from this EDMX file.

    Let’s create a small console application for demonstrating this approach and name the project as EFModelFirst.

     

    clip_image002

     

    I am using VS 2012 and with EF 5.0.0 which can be downloaded from nugget using the command in your package manager console as shown below.

     

    clip_image004