Friday, March 30, 2012

Asp.Net - TextArea validation using RegularExpressionValidator

The Asp.Net TextArea control doesnot support the MaxLength property, though you set the MaxLength property, the TextArea control will not restrict the users to enter text within the set limit. The MaxLengh property works fine with the TextBox controls, but when it comes to TextArea controls (TextMode = MultiLine) the MaxLength property fails.

The RegularExpressionValidator, control can be used to validate the MaxLength property of the TextArea control. Her’s how this can be accomplished.

Add a TextBox control to your Asp.net form and set its TextMode property to MultiLine, then add a RegularExpressionValidator control with the regular expression to restrict the length of the text in the TextBox.

Here’s the code

<asp:TextBox id="txtProjectDescription"
runat="server"
CssClass="text"
MaxLength="2500"
Width="500px"
TextMode="MultiLine"
Rows="5">
asp:TextBox>

<asp:RegularExpressionValidator
ID="valtxtProjectDescription"
runat="server"
ControlToValidate="txtProjectDescription"
Display="None"
ErrorMessage="Project Description Should be less than 2500 Characters"
SetFocusOnError="True"
ValidationExpression="^([\S\s]{0,2500})$">
asp:RegularExpressionValidator>

Add the Save Button and the Validation Summery control

<asp:Button
ID="cmdSave"
runat="server"
Text="Save"
/>

<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter a text with length more that 2500 characters in the TextArea. You should get an error message

Project Description Should be less than 2500 Characters

That's it, we have implemented the MaxLength property for a TextArea control in Asp.net

Asp.Net - ValidationSummary using ValidationGroup

In Asp.Net the ValidationSummary control consolidates the validation detials and error messages of all the validation controls in the page and provides a summary report of all the validation failures in the page.

Suppose we have a large page and we need to group the validations in the page based on specific groups, here we need to use the ValidationGroup property, the ValidationGroup property should be set to the controls which are part of the group, the ValidationSummary control and the button which will handle the submit/postback of this group.

Here’s the code below

Asp.Net - Date Validation using RegularExpressionValidator

Date validation using Asp.Net RegularExpressionValidator

Asp.Net offers the following validation controls.

RequiredFieldValidator
RegularExpressionValidator
CompareValidator
CustomValidator
RangeValidator

To validate the date, we can use the RegularExpressionValidator. This validator requires a regular expression which will validate the pattern of data entered in the control.

Open an Asp.net page and add a TextBox control, also add a RegularExpressionValidator control to validate the date entered in the TextBox

<asp:TextBox ID="txtDate" runat="server">asp:TextBox>
<asp:RegularExpressionValidator
ID="val txtDate "
runat="server"
ControlToValidate=" txtDate "
Display="None"
ErrorMessage="Enter a valid Date, Format (mm/dd/yyyy)"
SetFocusOnError="True"
ValidationExpression="^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$">
*asp:RegularExpressionValidator>

Now we have the TextBox Control and a RegularExpressionValidator control to validate the same, we should add a ValidationSummary control to handle all the validations in the page, we shall add the summary control, below the Submit button.

<asp:Button ID="cmdSave" runat="server" Text="Save"/>
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter an invalid Date in the textbox and click on the Save button.

You should get the Error message as follows.



Asp.Net - using ValidationControls with ValidationSummary

In Asp.Net we can use the Validation controls which come built in with Asp.net. Asp.Net offers the following validation controls.

RequiredFieldValidator
RegularExpressionValidator
CompareValidator
CustomValidator
RangeValidator

Now suppose we have multiple controls in a form, and each controls is associated with one or more validation controls, we will have to display the summary of all the validation in a single messagebox, to do so we can make use of the ValidationSummary control.

For example let us consider a textbox, which can accept only US Phone numbers, let us try to do the validation for this controls and associate the same with a ValidationSummary control.

Open an Asp.net page and add the control and the validationcontrol

<asp:TextBox
id="txtBusinessOwnerPhone"
runat="server"
CssClass="text"
MaxLength="12">
</asp:TextBox>

<asp:RegularExpressionValidator
ID="valtxtBusinessOwnerPhone"
runat="server"
ControlToValidate="txtBusinessOwnerPhone"
ValidationExpression="[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}[-]"
Display="None"
Text="*"
ErrorMessage="Enter Phone# in the format 999-999-9999">
</asp:RegularExpressionValidator>

Now we have the TextBox Control and a RegularExpressionValidator control to validate the same, we should add a ValidationSummary control to handle all the validations in the page, we shall add the summary control, below the Submit button.

<asp:Button ID="cmdSave" runat="server" Text="Save"/>
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter an invalid Phone number in the textbox and click on the Save button.

You should get the Error message as follows.



That's it, we have implemented the ValidationSummary control for the Asp.Net Validation controls.

Asp.Net Formating Numbers in Text Box, Grid, DataView using JavaScript

There are occasions where we need to format the numbers in Text Boxes, in the EditItemTemplate of GridView, DataList etc, we can achieve this using MaskEdit controls, but these will require additional controls and additional code, we shall see how this can be achieved using JavaScript.

What we are trying to achieve.

Input Format => 10
Output Format => 10.00

Let us now see, how to accomplish this.

Add the required TextBox or Grid/DataView controls to the page.
In the onblur event of the Textbox call a JavaScript function to format the content in the TextBox.


onblur="formatNumber(this);"

Here this refers to the instance of the TextBox, this will be used in the JavaScript function to format the data in the textbox.

The JavaScript function is as follows.


function formatNumber(objTxt)
{
if(isNaN(parseFloat(objTxt.value)))
{
alert('Please enter a valid Number');
objTxt.value = '0.00';
}
else
{
//Converts value 10 into the Format 10.00
objTxt.value = parseFloat(objTxt.value).toFixed(2);
}
}

That's it, the number in the TextBox will get formated, once the focus in moved out of the TextBox.

Thursday, March 29, 2012

Asp.Net Web.config - Reading appSettings & connectionStrings Values from web.config

In Asp.Net we can store constants and global information in the web.config file, these details can be accessed from anywhere in the Asp.net application. Let us see how to save connection strings and other application level constants in the web.config file and how to retrieve them from the application.

Create a new Asp.Net site or Application, open the web.cong file and place the required details under the appSettings & connectionStrings sections.

<appSettings> 
    <add key="Environment" value="local" /> 
</appSettings>

<connectionStrings> 

   <add name="ConnectionString" connectionString="xxxxxxxxx"/>
</connectionStrings>

Now let us see how this information can be accessed from the application.
Before staring add the below assembly reference to the top of the page, from where you are trying to read the details from the web.config file.

using System.Configuration;
string strConn =ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

string strEnvironment = ConfigurationManager.AppSettings["Environment"].ToString();

Once the above lines are executed the variable strConn will contain the value of the connection string, and the variable strEnvironment will contain the value local.

It is advisable to encrypt the connection string and place the same in the web.config, so that if an unauthorized person manages to access the web.config file, he will still not be able to interpret the server connection details.

Wednesday, March 28, 2012

Asp.Net Tab Structure using Asp:Menu Control

In this post we will focus on implementing a Tab Structure in Asp.Net 2.0 using the built in Asp:Menu Control.

Asp.Net 2.0 does not have a built in Tab Structure; we can implement this with some 3rd party controls, but to do so we need to undergo the additional hassle of integrating with the 3rd party assemblies and at time we end up in scenarios where the hosting/production environment does not allow hosting of 3rd party assemblies, or there could be privilege issues in deploying 3rd party assemblies to the hosting/production environment. So what do we do? We still need to have the Tab Structure right!! Here is the work around, we can use the control which ships along with Asp.Net 2.0, configure it in such a way that it looks like a tab control.

Let us now see, how to get a Tab Structure in Asp.Net 2.0 using the built in Asp:Menu Control.

Create a new Asp.Net Project and create a page where we need to implement the Tab Structure.
Add an
Asp:Menu
control to the page, in the location where you need to have the Tab Structure, and add the required tabs as meny items as follows.





The style attributes StaticMenuStyle & StaticSelectedStyle refer to the style sheets defined in the .css file below

.MenuNormal
{
background-color:Silver;
color:Blue;
font-family:Verdana;
font-size:15px;
border-style:solid;
border-color:Black;
border-width:1px;
}

.MenuActive
{
background-color:Maroon;
color:White;
font-family:Verdana;
font-size:15px;
border-style:solid;
border-color:Black;
border-width:1px;
}

The Selected Tab can be identified by implementing the MenuItemClick event as follows

protected void mnuMain_MenuItemClick(object sender, MenuEventArgs e)
{
lblMsg.Text = "You have selected the Tab: " + e.Item.Value;
}

That's it we have implemented a Tab Control structure using the Asp:Menu Control, in Asp.Net 2.0

Tuesday, March 27, 2012

Connecting to Oracle Database from C# .Net

Just like connecting to a SQLServer database, it is also possible to connect to an Oracle Database using the following approach.

Prerequisites
- Install the Oracle Server or Oracle Express Edition.
- If the Oracle server is placed in a different / remote machine then,
Install Oracle Client software, which is compatible to the version of the Oracle server.
- Install the correct version of Oracle Data Access Components (ODAC) which is compatible with the version of the Oracle Client, and the version of the .Net framework. This will provide the supporting assemblies to connect to Oracle.

Both these softwares are available free and can be downloaded from the Oracle site (http://www.oracle.com)

Once the required files are installed, we can connect to the Oracle database from C# .Net code.

Connection String:
strConnection = "Data Source=(DESCRIPTION=" + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxx.xxx.xxx.xxx)(PORT=xxxx)))" + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=xxxxxx)));" + "User Id= xxxxxx;Password= xxxxxx;";

In the above connection string replace xxxxx with the correct values for the following
HOST (IP Address of the Oracle Server)
PORT (Port of connection, by default it is 1521)
SERVICE_NAME (Service name for the Oracle Server)
User Id (User ID to connect to the Oracle Server)
Password (Password to connect to the Oracle Server)

C# Code
Before proceeding with the code, make sure that you add a reference to the System.Data.OracleClient assembly from the GAC

Add the following line to the top of the C# class
using System.Data.OracleClient;

OracleConnection conn = null;
OracleCommand cmd = null;
OracleDataAdapter objDA = null;

conn = new OracleConnection(strConn);

string strQuery = "Select * From Employee";

cmd = new OracleCommand(strQuery, conn);

objDA = new OracleDataAdapter(cmd);

objDA.Fill(dsEmployee,"Employee");

That's it, we have connected to the Oracle Database from C#.Net code.



C# - Implement MINUS Operation in DataTables using LINQ

LINQ can be used to effectively implement the MINUS operation in DataTables.
Suppose we have 2 DataTables A & B and if we need to remove the rows which are present in DataTable B from the DataTable A, then this can be achieved using a LINQ Query

DataTable A
DataTable B
DataTable Result = (A - B)


C# Example
DataTable dtIncludeCodes, dtExcludeCodes, dtResultCodes;
DataRow dr;
//
dtIncludeCodes = new DataTable();
dtIncludeCodes.Columns.Add("Code", typeof(string));
//
dr = dtIncludeCodes.NewRow();
dr["Code"] = "1";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "2";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "3";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "4";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "5";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "6";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "7";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "8";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "9";
dtIncludeCodes.Rows.Add(dr);
dr = dtIncludeCodes.NewRow();
dr["Code"] = "10";
dtIncludeCodes.Rows.Add(dr);
//
dtExcludeCodes = new DataTable();
dtExcludeCodes.Columns.Add("Code", typeof(string));
dr = dtExcludeCodes.NewRow();
dr["Code"] = "4";
dtExcludeCodes.Rows.Add(dr);
dr = dtExcludeCodes.NewRow();
dr["Code"] = "5";
dtExcludeCodes.Rows.Add(dr);
dr = dtExcludeCodes.NewRow();
dr["Code"] = "6";
dtExcludeCodes.Rows.Add(dr);
//
var resRows = from r in dtIncludeCodes.AsEnumerable()
where !dtExcludeCodes.AsEnumerable().Any(r2 => r["Code"].ToString().Trim().ToLower() == r2["Code"].ToString().Trim().ToLower() && r["Code"].ToString().Trim().ToLower() == r2["Code"].ToString().Trim().ToLower())
select r;
//
dtResultCodes = resRows.CopyToDataTable();

Here the DataTable dtIncludeCodes has values 1,2,3,4,5,6,7,8,9,10.
The DataTable dtExcludeCodes has values 4,5,6.

After executing the LINQ expression the resulting DataTable dtResultCodes will contain the values 1,2,3,7,8,9,10

That's it, very simple to implement MINUS using LINQ.