Sunday, September 27, 2009

Calling multiple validation group

Recently I had this requirement where in a single button click I need to call multiple Validation groups. The scenario is something like this. I had a ASP.NET page where there were 5 user controls and each had their own validation controls embedded in them. Each user control had its own validation controls and they had their own Validation group defined. All these user controls were placed in a single page which only had two button “Submit” and “Canel”. On click of the “Submit” button all the validation controls in the form should execute. The problem here is that there are five different validation groups in the same page. To top it all you can only assign one validation group to a button’ ValidationGroup property. If you don’t assign any validation group then on click of the submit button the validation controls which don’t have any validation group defined for them will only be fired. Validation controls which have validation group property defined will not get fired. This is the default behavior of validation controls. So how to call the validation controls of different groups? The answer lies in calling the “Page_ClientValidate” javascript method with the validation group name.

Lets try to understand how this all words with some code.The HTML code of the page looks something like this.

   1: <table width="100%"> 
   2:         <tr> 
   3:             <td> 
   4:                 <asp:TextBox ID="TextBox1" 
   5: runat="server"></asp:TextBox> 
   6:                 <asp:RequiredFieldValidator 
   7: ID="RequiredFieldValidator1" runat="server" 
   8: ErrorMessage="RequiredFieldValidator" 
   9: ValidationGroup="Group1" ControlToValidate="TextBox1"> 
  10: </asp:RequiredFieldValidator> 
  11:             </td>            
  12:         </tr> 
  13:         <tr> 
  14:             <td> 
  15:                 <asp:TextBox ID="TextBox2" 
  16: runat="server"></asp:TextBox> 
  17:                 <asp:RequiredFieldValidator 
  18: ID="RequiredFieldValidator2" runat="server" 
  19: ErrorMessage="RequiredFieldValidator" 
  20: ValidationGroup="Group2" ControlToValidate="TextBox2"> 
  21: </asp:RequiredFieldValidator> 
  22:             </td> 
  23:         </tr> 
  24:         <tr> 
  25:             <td> 
  26:                     <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="RequiredFieldValidator" 
  27: ValidationGroup="Group3" ControlToValidate="TextBox3"> 
  28: </asp:RequiredFieldValidator> 
  29:             </td> 
  30:         </tr> 
  31:         <tr> 
  32:             <td> 
  33:                 <asp:TextBox ID="TextBox4" 
  34: runat="server"></asp:TextBox> 
  35:                 <asp:RequiredFieldValidator 
  36: ID="RequiredFieldValidator4" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox4"> 
  37: </asp:RequiredFieldValidator> 
  38:             </td> 
  39:         </tr> 
  40:         <tr> 
  41:             <td> 
  42:                 <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="javascript:return 
  43: validatePage();" /> 
  44:                 <asp:Button ID="btnCancel" runat="server" Text="Cancel" /> 
  45:             </td> 
  46:         </tr> 
  47: </table>

From the above markup you can make out that there are four required field validators and out of the four validators three have validation group property defined. In such a scenario when you click the submit button only the validator which doesn’t have validation group will be executed i.e. RequiredFiedlValidator4 will only be executed. Since there are more than one validation group assigning button’ ValidationGroup wont work as it will execute only validator controls which belong to the assigned validaiton group. Other validator controls belonging to other validation group won’t execute. Also there is no way to specify multiple validaiton group using the ValidationGroup property of the button control.

The way to solve this problem is to call Page_ClientValidate javascript function. Page_ClientValidate is a javascript function generated by ASP.NET. The function takes validation group name as an argument. The javascript function which gets called when the submit button is clicked is pasted below.


   1: <script language="javascript" type="text/javascript"> 
   2: function validatePage() 
   3: { 
   4:     //Executes all the validation controls associated with group1 validaiton Group1. 
   5:     var flag = Page_ClientValidate('Group1'); 
   6:     if (flag) 
   7:     //Executes all the validation controls associated with group1 validaiton Group2. 
   8:         flag = Page_ClientValidate('Group2'); 
   9:     if (flag) 
  10:     //Executes all the validation controls associated with group1 validaiton Group3. 
  11:         flag = Page_ClientValidate('Group3'); 
  12:     if (flag) 
  13:     //Executes all the validation controls which are not associated with any validation group. 
  14:         flag = Page_ClientValidate(); 
  15:     return flag; 
  16: } 
  17: </script>

In the above code you can see the Page_ClientValidate function is called four times, first by passing the first validation group name, second time passing on the second validation group name and so on. If you see the last call to Page_ClientValidate, it is called with an empty argument. When call Page_ClientValidate with no argume/validation group name it executes all the validation controls in the page which don’t have a validation group assigned to them. So if one wants to execute validation controls which are not having any validation group associated with them you can call the Page_ClientValidate without any parameter.

So using Page_ClientValidate javascript function one can execute all the validation controls in the page by passing the validation group name or without any validation group name.


Try to know more.


Sandeep

Saturday, September 19, 2009

Some important .NET functions. Part – 1

.NET is a big ocean. Each day when I work I find one or the other function which are very useful in day to day programming. So I thought I will start a series of blog on some .NET function which I feel  are very useful. Here is the first list of function.

Recently while working in a ASP.NET project I wanted to make use of colors given by the designers in C# code behind file and wanted to change the color of ASP.NET controls. You will be thinking what is so hard in this. There is nothing much other than the color was given in hexadecimal value, like #657468, #AA3212 etc, and .NET controls only understand System.Drawing.Color structure values. So there is my problem. I need to convert the hexadecimal values to System.Drawing.Color values. Luckily I didn’t had to break my head for solving this problem, .NET provides a class just to solve my problem. The class is called ColorTranslator. The method which helped me is FromHtml. Code is pasted below.

DropDownList1.BackColor = System.Drawing.ColorTranslator.FromHtml("#345678");
DropDownList1.BorderColor = System.Drawing.ColorTranslator.FromHtml("Yellow");

The FromHtml method can take the name of the color as well as the hexadecimal value/HTML value. Some other methods of the class are listed below.

ColorTranslator.ToHtml(Color theColor): This is just the opposite of FromHtml i.e. it converts the color to HTML values. So when one wants to convert color to HTML color values/Hexadecimal color value one can make use of the ToHtml method. Sample code is pasted below.

DropDownList1.BackColor =
System.Drawing.ColorTranslator.FromHtml("#ff5678");
DropDownList1.BorderColor =
System.Drawing.ColorTranslator.FromHtml("Yellow");
Console.WriteLIne(System.Drawing.ColorTranslator.ToHtml
(DropDownList1.BackColor));//Output - #ff5678
Console.WriteLine(System.Drawing.ColorTranslator.ToHtml
(DropDownList1.BorderColor));//Output - Yellow

ColorTranslator.ToWin32(Color c) and ColorTranslator.FromWin32(int w32): ToWin32 converts the Color object to the equivalent windows color value whereas FromWin32 does just the opposite i.e. converts a Win32 color value to a System.Drawing.Color object. Sample codes are pasted below.

Console.WriteLine(System.Drawing.ColorTranslator.ToWin32
(System.Drawing.Color.Red));//Output – 255.
System.Drawing.Color color =
System.Drawing.ColorTranslator.FromWin32(255);

ColorTranslator.ToOLE(Color col) and ColorTranslator.FromOLE(int oleValue): ToOLE method converts Color object to OLE equivalent color value and FromOLE converts OLE color value to System.Drawing.Color object.

My ever useful System.IO.Path class

Over my career the class which is mostly used by me is the System.IO.Path class. Though the class has got only 15 or so static methods I use this class a lot while working with file paths. Let me first start with my favorite Combine method of the Path class which I use the most.

Path.Combine(string path1, string path2): The combine method combines two paths and returns you the combined path. The method takes care to add the necessary directory separator before combining the two paths. Also the combine method can be used to combine paths with wild characters like *.pdf or sa*.txt etc. If wild characters are used the combine method takes them as search criteria and doesn’t throw any error. E.g pasted below.

System.IO.Path.Combine(Server.MapPath("."), "images")
//Output: "C:\\aaa\\bb\\WebSite1\\images"
System.IO.Path.Combine(System.IO.Path.Combine(Server.MapPath
("."), "images"), "*.gif")
//Output: "C:\\aaa\\bb\\WebSite1\\images\\*.gif"

Path.GetExtension(string thePath): The GetExtension method returns the extension along with “.” from the path argument passed. So if you want to retrieve only extension from a file path just pass the file path to the GetExtension method and there you go you will have your extension. GetExtension method returns an empty string if the path doesn’t have any extension, also it returns null if the path argument is null. E.g. pasted below.

string filePath = System.IO.Path.Combine(System.IO.Path.Combine(Server.MapPath
("."),  "images"), "*.gif");
Console.WriteLine(System.IO.Path.GetExtension(filePath));
//Output: .gif

Path.GetFileName(string thePath): This method returns the filename with extension from the specified path argument. Returns an empty string if there are no file name. Sample code is pasted below.

string filePath = System.IO.Path.Combine(System.IO.Path.Combine(Server.MapPath
("."), "images"), "tick.gif");
Console.WriteLine(System.IO.Path.GetFileName
(filePath));//Output: tick.gif

Path.ChangeExtension(string filePath, string newExt): This method changes the extension of the file. The method takes two arguments, filename with extension along with/without path  and second one is the new extension with “.” which needs to be applied. If period is not there in the new extension argument then the method adds one. If you just wants to remove the extension then just pass a null value as the new extension parameter. Sample code is given below.

string filePath = System.IO.Path.Combine(System.IO.Path.Combine(Server.MapPath
("."), "images"), "tick.gif");
Console.WriteLine(System.IO.Path.ChangeExtension
(filePath, "jpg"));//Output: C:\\aaa\\bb\\WebSite1
\\images\\tick.jpg

Path.GetFileNameWithoutExtension(string filePath): Function returns the file name without extension. E.g. is shown below.

string filePath = System.IO.Path.Combine(System.IO.Path.Combine(Server.MapPath
("."), "images"), "tick.gif");
Console.WriteLine(System.IO.Path.ChangeExtension
(filePath, "jpg"));//Output: tick

Path.GetRandomFileName(): Returns a random string. The string is generated using cryptographic principles. The string can be used as folder or file name. Sample code is pasted below.

Console.WriteLine(System.IO.Path.GetRandomFileName())//Output: x4zxg224.hva

Path.GetTempFileName(): Function returns a string with a file name along with temporary folder path. The filename returned has a .tmp extension. The method creates a file with .tmp in the temporary folder and then returns the filename along with the temprorary folder path where the file is created. Sample code with output is pasted below.

Console.WriteLine(System.IO.Path.GetTempFileName())//Output: C:\\Documents and Settings\\sandeep\\Local Settings\\Temp\\tmp20C.tmp

Path.GetTempPath(): GetTempPath function returns the system’ temporary folder path. Sample code is pasted below.

Console.WriteLine(System.IO.Path.GetTempPath());//Output: C:\\Documents and Settings\\sandeep\\Local Settings\\Temp\\

Path.HasExtension(string filePath): This function checks whether the file path passed has a file extension. If extension is found the function returns true else false.

So these are some of my favorite and useful functions. Will publish some more over the course of time till then try to know more.

Sandeep