Behind MVC Client End Validation

Let’s straight into what things we require to enable validation at client end

STEP 1: Web.Config

Make sure below keys are required to be set true

<appSettings>
      <add key="ClientValidationEnabled" value="true"/>
      <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

 

STEP 2: Create One Model

using System.ComponentModel.DataAnnotations; // Required at least
public class Category
{
     [Required]
     [RegularExpression(@"^[a-z,'\s']+$", ErrorMessage = "Only A to Z with space")]
     public string Name { get; set; }

     [Required]
     [RegularExpression(@"^\d+$",ErrorMessage="Only number 0 to 9" )]
     public int Order { get; set; }
}

Note: Basically we can validate inputs by model by Annotations

 

STEP 3: Create Simple Controller

public class EmployeeController : Controller
{
     [HttpGet]
     public ActionResult create()
     {
          return View();
     }

     [HttpPost]
     public ActionResult Create(Category cat)
     {
          if (ModelState.IsValid == false)
          {
               return View(cat);
          }
          return Content("success");
     }
}

 

STEP 4: Create View

@model MvcApplication1.Controllers.Category
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@{Html.EnableClientValidation(true);}
@using (Html.BeginForm("Create", "Employee", FormMethod.Post))
{
      @Html.ValidationSummary(false)

      @Html.LabelFor(m => m.Name)
      @Html.TextBoxFor(m => m.Name) <br />

      @Html.LabelFor(m => m.Order)
      @Html.TextBoxFor(m => m.Order) <br />

      <input type="submit" value="Submit" />
}

 

Note: Please go to view source to see the magic (validation metadata)  is emitted as data attributes on the input elements.

<label for="Name">Name</label>
<input data-val="true" data-val-regex="Only A to Z with space" data-val-regex-pattern="^[a-z,'\s']+$" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" /> <br />

<label for="Order">Order</label>
<input data-val="true" data-val-number="The field Order must be a number." data-val-regex="Only number 0 to 9" data-val-regex-pattern="^\d+$" data-val-required="The Order field is required." id="Order" name="Order" type="text" value="" />

This metadata is consumed by the jquery.unobtrusive JavaScript library and connected to the jQuery Validate plugin’s validation logic.

 

Add Value:- We have added server-side validation (second gate-keeper) to make sure system won’t process invalid data.

[HttpPost]
public ActionResult Create(Category cat)
{
    if (ModelState.IsValid == false)
    {
        return View(cat);
    }
    return Content("success");
}

Because user submit data and it enters in network (un-secured world) where it can be tempered before it is reached to server

*****
Otherwise no need of SSL 😀 By The Way It provides tunnel from client to server using asymmetric cryptography so client data(soldiers) can reach destination and no-body can see what’s transferring.
*****

MCV Fill DropDownBox !!!

Let’s start with an example how to fill dropdownbox with
a very very simple example of (Employee Grade List) as I believe

– “Solution can be described in few words”

# Fill Dropdownbox
Key Note: We need SelectListItem class of System.Web.Mvc

Employee Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
     public class EmployeeController : Controller
     {
          public ActionResult index()
          {
               var Grade = new List();
               Grade.Add(new SelectListItem() { Text = "A", Value = "1" });
               Grade.Add(new SelectListItem() { Text = "B", Value = "2" });
               Grade.Add(new SelectListItem() { Text = "C", Value = "3" });
               Grade.Add(new SelectListItem() { Text = "D", Value = "4" });
               Grade.Add(new SelectListItem() { Text = "E", Value = "5" });
               Grade.Add(new SelectListItem() { Text = "F", Value = "6" });
               ViewBag.Grade = Grade;
               return View();
          }
     }
}

Employee Index View (index.cshtml):
Employee<br/>
Grade: @Html.DropDownList("Grade")

Step1

# Set Default Text (Note: Just add default text for optionLable)

Employee<br/>
Grade: @Html.DropDownList("Grade","Select Grade")

Step2

# Select value for edit before update (Note: Just add selected true for SelectListItem)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
   public class EmployeeController : Controller
   {
     public ActionResult index()
     {
       var Grade = new List<SelectListItem>();
       Grade.Add(new SelectListItem() { Text = "A", Value = "1" });
       Grade.Add(new SelectListItem() { Text = "B", Value = "2" });
       Grade.Add(new SelectListItem() { Text = "C", Value = "3" });
       Grade.Add(new SelectListItem() { Text = "D", Value = "4" });
       Grade.Add(new SelectListItem() { Text = "E", Value = "5", Selected=true });  // This option will be selected by default
       Grade.Add(new SelectListItem() { Text = "F", Value = "6" });
       ViewBag.Grade = Grade;
       return View();
     }
   }
}

Step3

Note: Grade system creates division among people !!!

Am I Software Engineer or Magic Wand !!!

Can I have right to say no as a Software Developer for things I don’t know

Why people want to listen good news / not bad news

Why they become impatience and try to get work done in hurry

Why they create pressure on software engineer or even worst try to bully Software Developer

This won’t help either end but it makes me think on below quote

“Life is like riding a bicycle. To keep your balance, you must keep moving.” ― Albert Einstein

Explore Microsoft MVC Environment Variables

We start MVC3 example with exploring/listing Environment Variables contains application sessionid, cockie, configuration, browser, etc… details

We try to finish this quest only by Controller without including unnecessary cosmetic things (view :D)

Create Controller: QueryStringController

public class QueryStringController : Controller
{
  public ActionResult Index()
  {
    Parameters();
    return Content("Index page is called");
  }

  [NonAction]
  public void Parameters()
  {
     foreach (string key in Request.Params.Keys)
     {
       Response.Write(string.Format("<strong>{0}:</strong> {1}<br/>", key, Request[key]));
      }
  }
}

HIT: http://localhost/querystring/index

———————————————————————————————————————————

We can make this above controller even shorter remove [NonAction], use Parameters methode as Action

public class QueryStringController : Controller
{
  public void Parameters()
  {
    foreach (string key in Request.Params.Keys)
    {
      Response.Write(string.Format("<strong>{0}:</strong> {1}<br/>", key, Request[key]));
    }
  }
}

HIT: http://localhost/querystring/Parameters

Environment Variables

__atuvc: 9%7C52%2C2%7C1
Nop.customer: 51ceb03d-b130-49ce-a0af-640f745c8e14
ASP.NET_SessionId: 5emy123x0tn2tnzvlev3arrc
ALL_HTTP: HTTP_CACHE_CONTROL:no-cache HTTP_CONNECTION:keep-alive HTTP_PRAGMA:no-cache HTTP_ACCEPT:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 HTTP_ACCEPT_CHARSET:ISO-8859-1,utf-8;q=0.7,*;q=0.3 HTTP_ACCEPT_ENCODING:gzip,deflate,sdch HTTP_ACCEPT_LANGUAGE:en-US,en;q=0.8 HTTP_COOKIE:__atuvc=9%7C52%2C2%7C1; Nop.customer=51ceb03d-b130-49ce-a0af-640f745c8e14; ASP.NET_SessionId=5emy123x0tn2tnzvlev3arrc HTTP_HOST:localhost:58550 HTTP_USER_AGENT:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17
ALL_RAW: Cache-Control: no-cache Connection: keep-alive Pragma: no-cache Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Cookie: __atuvc=9%7C52%2C2%7C1; Nop.customer=51ceb03d-b130-49ce-a0af-640f745c8e14; ASP.NET_SessionId=5emy123x0tn2tnzvlev3arrc Host: localhost:58550 User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17
APPL_MD_PATH:
APPL_PHYSICAL_PATH: C:\bhumip_pro\EF4MVC\MvcApplication1\
AUTH_TYPE:
AUTH_USER:
AUTH_PASSWORD:
LOGON_USER: VIBHUTI-PC2\vibhuti
REMOTE_USER:
CERT_COOKIE:
CERT_FLAGS:
CERT_ISSUER:
CERT_KEYSIZE:
CERT_SECRETKEYSIZE:
CERT_SERIALNUMBER:
CERT_SERVER_ISSUER:
CERT_SERVER_SUBJECT:
CERT_SUBJECT:
CONTENT_LENGTH: 0
CONTENT_TYPE:
GATEWAY_INTERFACE:
HTTPS:
HTTPS_KEYSIZE:
HTTPS_SECRETKEYSIZE:
HTTPS_SERVER_ISSUER:
HTTPS_SERVER_SUBJECT:
INSTANCE_ID:
INSTANCE_META_PATH:
LOCAL_ADDR: 127.0.0.1
PATH_INFO: /querystring/index
PATH_TRANSLATED: C:\bhumip_pro\EF4MVC\MvcApplication1\querystring\index
QUERY_STRING:
REMOTE_ADDR: 127.0.0.1
REMOTE_HOST: 127.0.0.1
REMOTE_PORT:
REQUEST_METHOD: GET
SCRIPT_NAME: /querystring/index
SERVER_NAME: localhost
SERVER_PORT: 58550
SERVER_PORT_SECURE: 0
SERVER_PROTOCOL: HTTP/1.1
SERVER_SOFTWARE:
URL: /querystring/index
HTTP_CACHE_CONTROL: no-cache
HTTP_CONNECTION: keep-alive
HTTP_PRAGMA: no-cache
HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_CHARSET: ISO-8859-1,utf-8;q=0.7,*;q=0.3
HTTP_ACCEPT_ENCODING: gzip,deflate,sdch
HTTP_ACCEPT_LANGUAGE: en-US,en;q=0.8
HTTP_COOKIE: __atuvc=9%7C52%2C2%7C1; Nop.customer=51ceb03d-b130-49ce-a0af-640f745c8e14; ASP.NET_SessionId=5emy123x0tn2tnzvlev3arrc
HTTP_HOST: localhost:58550
HTTP_USER_AGENT: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17

$matches contains a hashtable (Implicit)

The -match operator matches a pattern and returns a result.  However, along with the result, it also sets the $matches variable which contains the portions of the string that are matched by individual parts of the regular expressions.  $matches contains a hashtable where the keys of the hashtable are indexes that correspond to the parts of the pattern that is matched.  The values are the substrings of the target string that are matched.  Here is an example from the excellent Windows PowerShell in Action by Bruce Payette.

PS C:/> "abcdef" -match "(a) (((b)(c))de)f"
True
PS C:/> $matches
Key        Value
---        -----
5          c
4          b
3          bc
2          bcde
1          a
0          abcdef

You’ll noticed that there is one extra entry in the $matches hashtable beyond the 5 specified patterns.  This is because there is always a default element that represents the entire string that matched.

Since PowerShell is built on .NET regular expressions, you are not limited to index based keys as illustrated above.  This can be a pain when trying figure out which key index matches which matched pattern.  The .NET regular expression implementation allows for named captures by palcing the sequence “?” immediate inside the parenthesis that indicate the matching group.  The above example with named keys would look like this:

PS C:/> "abcdef" -match "(?a) (?((?b)(?c))de)f"
True
PS C:/> $matches
Key        Value
---        -----
o1         c
e3         b
e4         bc
o2         bcde
1          a
0          abcdef

XSLT 1.0 How to make text data Title Case Hmmm….. Interesting…..

Here is the solution it is messy but works for XSLT 1.0

I am getting late so straight away going for quick example

————————-
test.xml
————————-

<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet type="text/xsl" href="test.xslt" ?>
<data>
<input>
bhumip safi
</input>
</data>

————————-
test.xslt
————————-

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>

<!--- Consider Below As Function -->
<xsl:template name="ConvertTitleCase">
<xsl:param name="temp" />
<xsl:call-template name="TitleCase">
<xsl:with-param name="text" select="translate(normalize-space($temp), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')" />
</xsl:call-template>
</xsl:template>
<xsl:template name="TitleCase">
<xsl:param name="text" />
<xsl:param name="lastletter" select="' '"/>
<xsl:if test="$text">
<xsl:variable name="thisletter" select="substring($text,1,1)"/>
<xsl:choose>
<xsl:when test="$lastletter=' ' or $lastletter='/' or $lastletter='-'">
<xsl:value-of select="translate($thisletter,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$thisletter"/>
</xsl:otherwise>
</xsl:choose>
<xsl:call-template name="TitleCase">
<xsl:with-param name="text" select="substring($text,2)"/>
<xsl:with-param name="lastletter" select="$thisletter"/>
</xsl:call-template>
</xsl:if>
</xsl:template>

<!--- Consider Below As Caller Of Function -->
<xsl:template match="/">
<xsl:apply-templates select="data" />
</xsl:template>
<xsl:template match="data">
<output>
<xsl:call-template name="ConvertTitleCase">
<xsl:with-param name="temp" select="input" />
</xsl:call-template>
</output>
</xsl:template>

</xsl:stylesheet>

How every need to code much compare to other languages but
Wallah — problem solved