Wednesday, 30 December 2015

Validate Input & AllowHtml attribute .Net MVC

When you develop an app, sometimes your requirements could be you want to send HTML values (for example <h2>Hello World</h2>) from the view to the controller. Sometimes we use HTML Editors, to save some info into the database. By default ASP.NET MVC doesn't allow a user to submit the HTML content.

So let's see how to submit your form with HTML content.
  1. Open Visual Studio then select "New Project" then select "ASP.NET MVC 4 Application".

  1. Provide a project name then click "OK".
  2. Select "Internet Application" then click "OK"


  1. Create a New Model.

    ValidateModel.cs
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    namespace ValidateInputDemo.Models
    {
        public class ValidateModel
        {
            public string description { getset; }
        }
    }
  2. Add a new method to your Controller.

    HomeController.cs
    public ActionResult ValidateInput()
    {
        
    return View();
    }
    [
    HttpPost]public ActionResult  ValidateInput(string description)
    {
        
    ValidateModel validateInputModel = new ValidateModel();
        validateInputModel.description = description;
        
    return View(validateInputModel);
    }
    ValidateInput.cshtml
    @model ValidateInputDemo.Models.ValidateModel
    @{
           ViewBag.Title = "ValidateInput";
    }
    @using (@Html.BeginForm("ValidateInput","Home"FormMethod.Post, new { @id = "form1", @enctype ="multipart/form-data" }))
    {
        <label id="lblDescription">Description</label>
         @Html.TextAreaFor(m=>m.description, new {@id="txtDescription",@name="description" })
        <input type="submit" id="bttn_Submit" />
    }
You can see in the code above, there is a text area and a submit button, have a look in the browser. Press F5. 


You can see in the preceding screen, if you type something into the description and press Submit then  nothing happens.

Now check the following example. Add HTML content into text area.


Now press the "Submit" button.


You will get the error above. This error comes because this is the security from ASP.NET MVC. For applications, a user cannot send HTML values to the controller, but sometimes we want to send values to the controller.

For resolving this issue we have the ValidateInput(false) attribute.

Just put this into your controller and have a look.
[HttpPost]
[ValidateInput(false)]
public ActionResult  ValidateInput(string description)
{
   ValidateModel validateInputModel = new ValidateModel();
   validateInputModel.description = description;
   return View(validateInputModel);
}
Now press F5. After filling in the HTML attribute press the submit button, you will never get an error. So when you want to work with HTML attributes in your app text area or textboxes, don't forget to use validateinpute(false) in your ActionMethod.

Limitation of ValidateInput attribute
This attribute also has the issue since this allow the Html input for all the properties and that is unsafe. Since you have enable Html input for only one-two properties then how to do this. To allow Html input for a single property, you should use AllowHtml attribute.

AllowHtml Attribute
This is the best way to allow the submission of HTML for a particular property. This attribute will be added to the property of a model to bypass input validation for that property only. This explicit declaration is more secure than the ValidateInput attribute.

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

public class BlogModel
{
 [Required]
 [Display(Name = "Title")]
 public string Title { get; set; }

 [AllowHtml]
 [Required]
 [Display(Name = "Description")]
 public string Description{ get; set; }
}


Make sure, you have removed the ValidateInput attribute from Conroller or Action method. Now, the user can submit Html only for the Description property successfully.
Continue Reading →

Friday, 16 October 2015

How to Get Selected CheckBox Values

This Article will Teach you How you can get Selected Checkbox Values with Comma Seperated in a Variable using Jquery.

Create a new Html File Named test.html and add the below code in that file.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>

    <input type="checkbox" class="form" value="E001" />
    <input type="checkbox" class="form" value="E002" />
    <input type="checkbox" class="form" value="E003" />
    <input type="checkbox" class="form" value="E004" />

    <input name="searchDonor" type="button" class="button" value="Get Value" onclick="getvalue()" />
    <script>
        function getvalue() {

            var boxesValue = [];
            $('input:checkbox.form:checked').each(function () {
                var value = (this.checked ? $(this).val() : "");
                boxesValue.push(value);
            });

            var str = boxesValue.join(",");
            alert(str);
        }
    </script>

</body>
</html>

Now Run This html file.
Click the checkboxes and Click on Get Value Button.
You will get Selected Check box Value.

Continue Reading →

Monday, 29 June 2015

Exception Handling in ASP.NET Web API

In this article the focus is to handle exceptions for ASP.NET Web API service. HttpResponseException class plays its role to return HTTP status code as well as further exception details to client.

We can simply return respective error status code from Web API service instead of a 500 generic error code i.e.Internal Server Error

Now, we have Web API service controller StudentController having  GET method taking "Id" as parameter and returns a student against it. If student doesn't exists against a provided student Id, then we can handle and throw the exception with respective status code i.e. "Not Found".

After adding the exception handling code using HttpResponseException class, GET method implementation will be as follows:


public Student Get(string id)
        {
            Student student = StudentRepository.GetStudent(id);
            if (student == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            return student;

        }

It looks nice to return logical status code back to client but what if we wanted to add more error details?
ASP.NET Web API allows us to create response message using HttpResponseMessage class and pass it toHttpResponseException
HttpResponseMessage represents a returning response message having following important properties:
  • StatusCode is HTTP response status code i.e. NotFound in our case.
  • ResonPhrase to return the exception reason along with status code.
  • Content property can be used to set or get HTTP response content.
 public Student Get(string id)
        {
            Student student = StudentRepository.GetStudent(id);
            if (student == null)
            {
                HttpResponseMessage responseMessage = new HttpResponseMessage();
                responseMessage.StatusCode = HttpStatusCode.NotFound;
                responseMessage.ReasonPhrase = "Student not found";
                responseMessage.Content = new StringContent("No student exists against provided student id");

                throw new HttpResponseException(responseMessage);
            }
            return student;
        }

Note: Remember one important thing about HttpResponseMessage class. Initially, we can easily create a type and pass it to HttpResponseMessage class constructor and return that message with data. But now we can only use Content property to set message content.

Hopefully, this web application development tutorial will be helpful in order to understand and implement exception handling in ASP.NET Web API services.
Continue Reading →

Tuesday, 2 June 2015

Factory Design Pattern - C#

Design patterns are general reusable solutions to common problems that occurred in software designing. There are broadly 3 categories of design patterns, i.e., Creational, Behavioral and Structural.

Now, Factory Design Pattern falls under the category of creational design pattern.
Factory design pattern is one of the common design pattern  in software project. Let’s understand the basic of Factory design patern.


         It deals with the problem of creating objects without specifying the exact class of object that will be created. The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. 

Definition:Factory it's such a Design Pattern which defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. Factory Pattern lets a class postpone instantiation to sub-classes.

Factory design pattern is one of the common design pattern  in software project. Let’s understand the basic of Factory design pattern.


See the Simplest Example Code Factory Pattern Example Code in C#

Factory Method Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the factory method design pattern is given below:


The classes, interfaces and objects in the above UML class diagram are as follows:

Product
This is an interface for creating the objects.

ConcreteProduct
This is a class which implements the Product interface.

Creator
This is an abstract class and declares the factory method, which returns an object of type Product.

ConcreteCreator
This is a class which implements the Creator class and overrides the factory method to return an instance of a ConcreteProduct.

C# - Implementation Code

interface Product
{

}

class ConcreteProductA : Product
{
}

class ConcreteProductB : Product
{
}

abstract class Creator
{
    public abstract Product FactoryMethod(string type);
}

class ConcreteCreator : Creator
{
    public override Product FactoryMethod(string type)
    {
        switch (type)
        {
            case "A": return new ConcreteProductA();
            case "B": return new ConcreteProductB();
            default: throw new ArgumentException("Invalid type", "type");
        }
    }
}

Factory Method Pattern - Example


Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:

IFactory - Interface
Scooter & Bike - Concreate Product classes
VehicleFactory - Creator
ConcreteVehicleFactory - Concreate Creator

namespace FactoryDesignPattern
{
    /// <summary>
    /// The 'Product' interface
    /// </summary>
    public interface IFactory
    {
        void Drive(int miles);
    }

    /// <summary>
    /// A 'Concrete Scooter' class
    /// </summary>
    public class Scooter : IFactory
    {
        public void Drive(int miles)
        {
            Console.WriteLine("Drive the Scooter : " + miles.ToString() + "km");
        }
    }

    /// <summary>
    /// A 'Concrete Bike' class
    /// </summary>
    public class Bike : IFactory
    {
        public void Drive(int miles)
        {
            Console.WriteLine("Drive the Bike : " + miles.ToString() + "km");
        }
    }

    /// <summary>
    /// The Creator Abstract Class
    /// </summary>
    public abstract class VehicleFactory
    {
        public abstract IFactory GetVehicle(string Vehicle);

    }

    /// <summary>
    /// A 'ConcreteCreator' class
    /// </summary>
    public class ConcreteVehicleFactory : VehicleFactory
    {
        public override IFactory GetVehicle(string Vehicle)
        {
            switch (Vehicle)
            {
                case "Scooter":
                    return new Scooter();
                case "Bike":
                    return new Bike();
                default:
                    throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
            }
        }
    }


   public class Program
    {
        static void Main(string[] args)
        {
            VehicleFactory factory = new ConcreteVehicleFactory();

            IFactory scooter = factory.GetVehicle("Scooter");
            scooter.Drive(10);

            IFactory bike = factory.GetVehicle("Bike");
            bike.Drive(20);

            Console.ReadKey();
        }
    }
}

Factory Pattern Demo - Output




When to use it?
  1. Subclasses figure out what objects should be created.
  2. Parent class allows later instantiation to subclasses means the creation of object is done when it is required.
  3. The process of objects creation is required to centralize within the application.
  4. A class (creator) will not know what classes it will be required to create.


Some more usefull links are: link1link2
Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)