ASP.NET MVC Partial View Validation From Client Side

I have come across one problem regarding client side validation for form submit where form resides in partial view
I have gone through many forums and articles but very few have explained it with complete example

Guess what I have done? Made one simple and small demo that I am going to explain

How unobtrusive validation works and problem associated with partial view
  • Unobtrusive validation is a unique feature. One can easily bind server side validation to client side validation provided by JQuery plugin.
  • Unobtrusive validation binds special attributes to field on load event, which are used to bind your own rules defined inside the model with rules implementation provided by JQuery library.
  • However, when you create a partial view fields in new form are without those special attributes and so validation is not working.
  • One of the solution is to load unobtrusive .js file again. It works but you need to load something twice wasting resources.
  • There is a method “parse” in unobtrusive plugin , which is responsible for creating validation
  • There is a method “parse” in unobtrusive plugin , which is responsible for creating validation attributes , adapters and also what’s really important errorPlacement adapter. Everything you need. Knowing all of this we can just use this “parse” on the form and everything should work fine.

Higher level we could divide this exercise in three sections moving forward step by step we are going to try to accomplish each section

Section 1 : Setup & Configuration

  • STEP 1 : Bundle following files in BundleConfig class BundleConfig
    • JQuery (for DOM management)
    • JQuer UI (for Dialogue box)
    • jquery.unobtrusive & jquery.validate (for validation)
    • “~/Content/css” for site.css (for site design)
    • “~/Content/themes/base/css” JQuery UI CSS (for dialogue box design)
  • STEP 2 : _layout page  _layout
    • Add STEP 1 bundles in _layout page
    • Note replace render section of script to bottom after jquery, jqueryui & jqueryval bunder
  • STEP 3 : Add appsettings in web.config  Web.config
    • set ClientValidationEnabled true
    • set UnobtrusiveJavaScriptEnabled true

#Section 1 is completed let us move forward to section 2


Section 2 : Back-end side

  • STEP 1: AddUserViewModel Model that includes following  Model
    • Properties
    • validate properties using DataAnnotations using System.ComponentModel.DataAnnotations
  • STEP 2: Create partial view incorporates followings  Partial View
    • Associated Model
    • Form elements without submit as it will be taken care of by dialogue box button
    • Validation message
  • STEP 3: HomeController has two responsibilities  HomeController
    • Render partial view (i.e. AddUserPartialView)
    • Handle submit data on form POST (i.e. AddUserInfo)

#Section 2 is completed let us move forward to section 3


Section 3 : Front end side (Index.chtml)

  • STEP 1: Add dialogue box container and adduser button Ref Code
  • STEP 2: Add button click event to open dialogue box (i.e. $(“#AddUserForm”).dialog({…}) Ref Code
  • STEP 3: Load rendered partial view in dialogue box
    • (i.e. $(‘#AddUserForm’).load(‘@Url.Action(“AddUserPartialView”, “Home”)’, function () {…}) ) Ref Code
  • STEP 4: Call “parse” in unobtrusive plugin, which is responsible for creating validation attributes Ref Code
  • STEP 5: Register form submit event on load of dialogue box (i.e. $form.submit(function () {..}) ) Ref Code
  • STEP 6: post serialized form data to /Home/AddUserInfo action by AJAX Ref Code
  • STEP 7: AJAX event has two handlers success and error Ref Code
  • STEP 8: Last but not the least add two buttons “Add User” and “Cancel” in dialogue box Ref Code
    • “Add User” call form submit
    • “Cancel” close dialog box

Source code:-
https://github.com/ganesha8shiva/MVCPartialViewValidation
Video Help :-


Note: If anybody faces error while building project

  • Right click on solution
  • Enable NuGet Package Restore (will take few minutes to finish)
  • Tools -> Library Package Manager -> Package Manager Console
  • Some NuGet Packages are missing from this solution. Click to restore.
  • Press Restore (will take several minutes)
  • Build Successful and works like charm

Video Help :-

Both Left Join & Group By In Single LINQ Query

I had encountered with the complicated requirement, requirement was to display category and total products against it, I need both left outer join and group by on CategoryID of Categories table

I had provide below solution which I had tested on LINQPad Below is tested solution

I applied simple rule while I was coding and that is “Break one complex problem in small but reasonably simple problems” (Tip: Divide & Rule)

Step 1: Left Join Categories Products

var LO =  from a in Categories 
	       join b in Products			
	       on a.CategoryID equals b.CategoryID into leftjoin
	       from c in leftjoin.DefaultIfEmpty()			
	       select new {
		 ProductID = c.ProductID == null ? 0 : 1,
		 CategoryID = a.CategoryID,
		 CategoryName = a.CategoryName,
	       };

Step 2: Group by { CategoryID, CategoryName, ProductID }

var Group = from d in LO
		 group d by new {d.CategoryID, d.CategoryName, d.ProductID} into groupby
		 select new {
			CategoryID = groupby.Key.CategoryID,
			CategoryName = groupby.Key.CategoryName,
			Total = groupby.Sum(x => groupby.Key.ProductID)
		 };

Step 3: Iteration

foreach(var i in Group) {
	Console.WriteLine(i);
}

Output

Category ID: 1; Category Name: Beverages;      Total Products: 12
Category ID: 2; Category Name: Condiments;     Total Products: 12
Category ID: 3; Category Name: Confections;    Total Products: 13
Category ID: 4; Category Name: Dairy Products; Total Products: 10
Category ID: 5; Category Name: Grains/Cereals; Total Products: 7
Category ID: 6; Category Name: Meat/Poultry;   Total Products: 6
Category ID: 7; Category Name: Produce;        Total Products: 5
Category ID: 8; Category Name: Seafood;        Total Products: 12
Category ID: 9; Category Name: New;            Total Products: 0

Cheers !!!

JQuery Virtual Keyboard

A quick post on virtual keyboard which can be used to enter user name / password / Pine number, etc… Internet banking highly recommend to use while logging into Internet Banking Site.

Below are the advantages of virtual keyboard

  • The virtual keyboard can be an additional precautionary measure, protects you against malicious key logger programs which might have infected your  computer.
  • A key logger program can capture the keystrokes you enter in the physical keyboard to login which may be accessing your PC without your knowledge or permission.
  • A virtual keyboard prevents your username or password from being stolen, especially while using public computers, such as those available in Internet cafes. Also, the sequence in which the keys appear will change everytime the page is refreshed.

Before I start with an example go through Keith Wood’s solution for it build on top of JQuery

It is very clean, well documented, higly compatible and scalable solution, if I have to rate, I rate 5 out of 5 stars and highly recommended solution

Virtual Keyboard:  http://keith-wood.name/keypad.html

Quick Reference: http://keith-wood.name/keypad.html

jQuery Keypad Reference:     http://keith-wood.name/keypadRef.html

Last but not the least I am going through simple yet quick example before signing off

Step 0:- Create Folder structure as below

  • main
  • main/css
  • main/javascript

Step 1:-  Add jquery.keypad.css in main/css folder

Step 2:-  Add jquery-1.7.1.min.js and jquery.keypad.js in main/javascript folder

Step 3:-  Add index.html in main folder and copy-paste below code into index.html  “please read code carefully before copying it blindly :D”

<html>
<title>Virtual Keyboard</title>
<head>
 <link type="text/css" href="css/jquery.keypad.css" rel="stylesheet" />  
 <script type="text/javascript" src="javascript/jquery-1.7.1.min.js"></script>
 <script type="text/javascript" src="javascript/jquery.keypad.js"></script> 
    <script type="text/javascript">
        $(document).ready(function () {                    
            $("input[id$='chkKeyboard']").click(function () {            
                if (!$(this).is(':checked')) {
                    $('#txtUsername').keypad('destroy');
                    $('#txtPassword').keypad('destroy');
                } else {
                    $('#txtUsername').keypad({ keypadOnly: true, layout: $.keypad.qwertyLayout, randomiseAlphabetic: true, randomiseNumeric: true, randomiseOther: true });
                    $('#txtPassword').keypad({ keypadOnly: true, layout: $.keypad.qwertyLayout, randomiseAlphabetic: true, randomiseNumeric: true, randomiseOther: true });                    
                }
            });
        });
    </script>       

</head>

<body>
   <div style="text-align: left; margin-top: 15px;">                           
      Username : <input type="text" id="txtUsername" /><br/>
      Password : <input type="Password" id="txtPassword"></asp:TextBox><br/>
      <input type="checkbox" id="chkKeyboard" /> Use virtual keyboard (Recommended)<br/>
      <input type="button" id="btnSubmit" value="Submit"  />
   </div>
</body>

</html>

Step 4:- Open index.html in any browser (ie, chrome, firefox, etc…)
virtual_keyboard

Quote: “Great solutions are described in few words”

Abstract Factory Pattern Using Generics

As we know through Factory Pattern, client class can choose type of instance but not factory, however Abstract Factory add up one more option to client class factory type selection

Before read further, first must go through Factory Patter, Ref Factory Pattern or search on internet will get plenty details on this topic

Let’s visualize a shop where customer can choose stuffed animal for free while ordering food and shop make stuffed animal and hand over as gift once food is finished completely

# So in this case we need two units

  • First one is food unit to make as per request
  • second one is stuffed animal unit to make as per request

# Very basic diagram for this pattern seems not complex to understand

Factory Pattern

# Fun part let’s create units (Note consider unit is factory which creates things as per request)

///Abstract Stuffed Animal
abstract class Animal
{
  public abstract void voice();
}
class Dog : Animal
{
  public override void voice()
  {
      Console.WriteLine("dog voice");
  }
}
class Cat : Animal
{
  public override void voice()
  {
      Console.WriteLine("cat voice");
  }
}

///Abstract Food
abstract class Food
{
  public abstract void Taste();
}
class Curry : Food
{
  public override void Taste()
  {
      Console.WriteLine("it is hot indian curry");
  }
}
class Vadapav : Food
{
  public override void Taste()
  {
      Console.WriteLine("it is awesome mumbai vada pav.");
  }
}

We are done with units code

# Abstract out unit by generics (WARNING !!!! Not for faint hearted)

abstract class AbstractUnit<P>
{
    public abstract P create<T>() where T : P, new();
}

class AnimalUnit<A> : AbstractUnit<A> where A : Animal
{
    public override A create<T>()
    {
        T obj = new T();
        return obj;
    }
}
class FoodUnit<F> : AbstractUnit<F> where F : Food
{
    public override F create<T>()
    {
        T obj = new T();
        return obj;
    }
}

# Now we need more intervention to select factory here it is !!!

/// Select Unit
class Unit
{
    public static P SelectUnit<P>() where P : new()
    {
        P factory = new P();
        return factory;
    }
}

# Final and the most import part customer come to shop just pick and choose things so simple, is’t it.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("##### Order Food #####");
        Unit.SelectUnit<AnimalUnit<Animal>>().create<Dog>().voice();
        Unit.SelectUnit<AnimalUnit<Animal>>().create<Cat>().voice();
        Console.WriteLine();
        Console.WriteLine("###### Choose Stuffed Animal #####");
        Unit.SelectUnit<FoodUnit<Food>>().create<Curry>().Taste();
        Unit.SelectUnit<FoodUnit<Food>>().create<Vadapav>().Taste();
        Console.WriteLine();
    }
}

# OUTPUT

##### Order Food #####
dog voice
cat voice

###### Choose Stuffed Animal #####
it is hot indian curry
it is awesome mumbai vada pav.

Press any key to continue . . .

Even I wonder about existence of such kind of shops !!! Visualization some times take you out of track…..

Factory Pattern Using Generics

The basic functionality of Factory Pattern Design to create instances as per client’s request

It could be achieved by few lines of generics collection program

Before we go through a quick example, visualize one  factory (factory class) where stuffed animals are created and delivered as per customer’s need (client object), now let’s start to implement factory

# Animal can be any animal hence it is abstract

abstract class Animal 
{
   public abstract void voice();
}

# Create more specific animal (subtype)

class Dog : Animal
{
   public override void voice()
   {
      Console.WriteLine("dog voice");
   }
}

# Create more specific animal (subtype)

class Cat : Animal
{
   public override void voice()
   {
      Console.WriteLine("cat voice");
   }
}

# Factory which creates stuff animal as per client’s requirement

class Factory
{
   public static Animal create() where T : Animal, new()
   {
      T obj = new T();
      return obj;
   }
}

# For one moment consider Program a customer it ask for cat and dog from factory

class Program
{ 
   static void Main(string[] args)
   {
      Animal cat =   Factory.create();
      cat.voice();

      Animal dog = Factory.create();
      dog.voice();
   }
}

# OUTPUT…

cat voice
dog voice
Press any key to continue . . .

WCF Transactional Queue vs Non-Transaction Queue

If queue message is part of transaction process then we could consider two cases

Case1: message must not queue up in MSMQ if one of transaction scope statement  fails
Case2: message should queue up even if one of transaction statement fails

Without further due straight jump to quick example

# STEP 1: Create transactional queue name “msmqtest”

# STEP 2: Data contract

[DataContract]    
public class Message
{
  [DataMember]
  public string payload;
}

# STEP 3: Create service contract

[ServiceContract]
public interface IRequestService
{        
  [OperationContract(IsOneWay=true)]
  void ProcessRequest(Message msg);
}

# STEP 4: Impletement service contract

public class RequestService : IRequestService
{
  public void ProcessRequest(Message msg)
  {
      Console.WriteLine(String.Format("Received message at {0} : {1}", DateTime.Now, msg.payload));
  }                
}

# STEP 5: Service Self Hosting

class SelfHost
{
  public static void HostMSMQService()
  {
      using (ServiceHost sht = new ServiceHost(typeof(WCFSelfHosting.Services.RequestService)))
      {                
          NetMsmqBinding nbind = new NetMsmqBinding(NetMsmqSecurityMode.None);          
          sht.AddServiceEndpoint(new ServiceEndpoint(ContractDescription.GetContract(typeof(WCFSelfHosting.Contract.IRequestService)), nbind, new EndpointAddress("net.msmq://localhost/private/msmqtest")));
          sht.Open();
          Console.WriteLine("Please enter to stop service");
          Console.Read();
          sht.Close();
      }
  }
}

# STEP 6: Create client for different cases (i.e  transaction pass, fail and process without transaction scope)

class Program
{
  static void Main(string[] args)
  {
      NetMsmqBinding nmsmq = new NetMsmqBinding(NetMsmqSecurityMode.None);            
      using (ChannelFactory chf = new ChannelFactory(nmsmq, new EndpointAddress("net.msmq://localhost/private/msmqtest")))
      {
          chf.Open();

          // CASE 1
          using (TransactionScope transScope = new TransactionScope(TransactionScopeOption.Required))
          {
              WCFSelfHosting.Contract.IRequestService srv = chf.CreateChannel();
              srv.ProcessRequest("Transaction Fail Message");

              int j = 0;
              int i = 100 / j;
              transScope.Complete();
          }

          using (TransactionScope transScope = new TransactionScope(TransactionScopeOption.Required))
          {
              WCFSelfHosting.Contract.IRequestService srv = chf.CreateChannel();
              srv.ProcessRequest("Transaction PASS Message");

              int j = 10;
              int i = 100 / j;
              transScope.Complete();
          }

          // CASE 2
          WCFSelfHosting.Contract.IRequestService srv = chf.CreateChannel();
          srv.ProcessRequest("Transaction Scope Message");

          int j = 0;
          int i = 100 / j;

          chf.Close();
      }
   }
}

# Start service client and check private queue two messages are queued

Yes you guessed it right !!! Due to transaction fail first message is not queued

transaction_img

# Start service and check which message we are pulled to reconfirm

service_msg

***Analysis on WCF Transactional Queue vs Non-Transaction Queue

– Firstly, transaction scope works because “msmqtest” is transactional queue
– Food for thought what if there is non-transactional, does TransactionScope make sence or worth to use ?

I say no…

Generic Extension Methods

Extension methods are used across .NET library more often than not, Let’s see through below example

using System;
using System.Collections.Generic;
using System.Text;
class Program
{        
     static void Main(string[] args)
     {
         IEnumerable list = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
         list.
     }
}

When we dot there are only five methods you can see an images, where are other methods like select, count, sum etc….
See below visual reference

Step1
Food For Thought
First of let me clear all these methods are extension methods of IEnumerable to use these methods we need Enumerable under System.Linq namespace contains all extension methods, See below visual reference of Enumerable class much like utility class
Step2

Just add using System.Linq; will include all necessary extension methods see below , can be seen arrow going bottom against  methods indicating extension methods
Step3

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace LinqToSql
{
    class Program
    {        
        static void Main(string[] args)
        {
            IEnumerable list = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            list.Sum();
        }
    }    
}

Last but not the least below is complete example to create new generic extension method of IENumerable

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace LinqToSql
{
    /// Extension Or Utility Class 
    public static class Enumerable
    {
        /// Syntax For Extenstion Method
        /// static Type MehodeName(this Type)
        public static IEnumerable NumberFilter(this IEnumerable list, Predicate condition)
        {
            foreach (var item in list)
            {
                if (condition(item))
                {
                    yield return item;
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable list = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            /// NumberFilter Available Without Doing Much
            IEnumerable filterEven = list.NumberFilter(x => x % 2 == 0);
            foreach (var item in filterEven)
            {
                Console.WriteLine("Even Number:{0}", item);
            }
            IEnumerable filterOld = list.NumberFilter(x => x % 2 != 0);
            foreach (var item in filterEven)
            {
                Console.WriteLine("Odd Number:{0}", item);
            }
        }
    }
}

Visual Reference For New Generic Extension Method

Step4