Total Pageviews

Monday, August 3, 2009

ASP.NET Validation Controls

With ASP.NET, there are six(6) controls included.

They are:

  • The RequiredFieldValidation Control
  • The CompareValidator Control
  • The RangeValidator Control
  • The RegularExpressionValidator Control
  • The CustomValidator Control

All of the validation controls inherit from the base class BaseValidator so they all have a series of properties and methods that are common to all validation controls. They are:

  • ControlToValidate – This value is which control the validator is applied to.
  • ErrorMessage – This is the error message that will be displayed in the validation summary.
  • IsValid – Boolean value for whether or not the control is valid.
  • Validate – Method to validate the input control and update the IsValid property.
  • Display – This controls how the error message is shown. Here are the possible options:

o None (The validation message is never displayed.) o Static (Space for the validation message is allocated in the page layout.) o Dynamic (Space for the validation message is dynamically added to the page if validation fails.)

The RequiredFieldValidation Control ———————————–

The first control we have is the RequiredFieldValidation Control. As it’s obvious, it make sure that a user inputs a value. Here is how it’s used:

Required field: *

The CompareValidator Control —————————– Next we look at the CompareValidator Control. Usage of this CompareValidator is for confirming new passwords, checking if a departure date is before the arrival date, etc. We’ll start of with a sample:

Textbox 1:
Textbox 2:
*

Here we have a sample where the two textboxes must be equal. The tags that are unique to this control is the ControlToCompare attribute which is the control that will be compared. The two controls are compared with the type of comparison specified in the Operator attribute. The Operator attribute can contain Equal, GreterThan, LessThanOrEqual, etc. Another usage of the ComapareValidator is to have a control compare to a value. For example:

Field: *

The RangeValidator Control ————————–

Range validator control is another validator control which checks to see if a control value is within a valid range. The attributes that are necessary to this control are: MaximumValue, MinimumValue, and Type. Sample:

Enter a date from 1998: *

The RegularExpressionValidator Control ————————————–

The regular expression validator is one of the more powerful features of ASP.NET. Everyone loves regular expressions. Especially when you write those really big nasty ones… and then a few days later, look at it and say to yourself. What does this do? Again, the simple usage is:

E-mail: *

The CustomValidator Control —————————–

The final control we have included in ASP.NET is one that adds great flexibility to our validation abilities. We have a custom validator where we get to write out own functions and pass the control value to this function.

Field: *

We notice that there are two new attributes ClientValidationFunction and OnServerValidate. These are the tell the validation control which functions to pass the controltovalidate value to. ClientValidationFunction is usually a javascript funtion included in the html to the user. OnServerValidate is the function that is server-side to check for validation if client does not support client-side validation.

Client Validation function:

>

Server Validation function:

Sub ServerValidate (objSource As Object, objArgs As ServerValidateEventsArgs) ‘ Code goes here End Sub

Validation Summary ——————-

ASP.NET has provided an additional control that complements the validator controls. This is the validation summary control which is used like:

Saturday, August 1, 2009

User Control Events

Communication between a user control and a web page can occur through events.With methods and properties, the user control reacts to a change made by the web page code. With events, the story is reversed: the user control notifies the web page about an action, and the web page code responds. Creating a web control that uses events is fairly easy. In the following example, you’ll see a version of the LinkMenu control that uses events. Instead of navigating directly to the appropriate page when the user clicks a button, the control raises an event, which the web page can choose to handle. The first step to create this control is to define the events. Remember, to define an event, you must first choose an event signature. The .NET standard for events specifies that every event should use two parameters. The first one provides a reference to the control that sent the event, while the second incorporates any additional information. This additional information is wrapped into a custom EventArgs object, which inherits from the System.EventArgs class. (If your event doesn’t require any additional information, you can just use the predefined EventArgs class, which doesn’t contain any additional data. Many events in ASP.NET, such as Page.Load or Button.Click, follow this pattern.) The LinkMenu2 control uses a single event, which indicates when a link is clicked: public partial class LinkMenu2 : System.Web.UI.UserControl { public event EventHandler LinkClicked; ... } This code defines an event named LinkClicked. The LinkClicked event has the signature specified by the System.EventHandler delegate, which includes two parameters—the event sender and an ordinary EventArgs object. That means that any event handler you create to handle the LinkClicked event must look like this: protected void LinkMenu_LinkClicked(object sender, EventArgs e) { ... } This takes care of defining the event, but what about raising it? This part is easy. To fire the event, the LinkMenu2 control simply calls the event by name and passes in the two parameters, like this: // Raise the LinkClicked event, passing a reference to // the current object (the sender) and an empty EventArgs object. LinkClicked(this, EventArgs.Empty); The LinkMenu2 control actually needs a few more changes. The original version used the HyperLink control. This won’t do, because the HyperLink control doesn’t fire an event when the link is clicked. Instead, you’ll need to use the LinkButton. The LinkButton fires the Click event, which the LinkMenu2 control can intercept, and then raises the LinkClicked event to the web page. The following is the full user control code: public partial class LinkMenu2 : System.Web.UI.UserControl { public event EventHandler LinkClicked; protected void lnk_Click(object sender, EventArgs e) { // One of the LinkButton controls has been clicked. // Raise an event to the page. if (LinkClicked != null) { LinkClicked(this, EventArgs.Empty); } } ------------- Happy Programming

Tuesday, July 14, 2009

Split value function SQL SERVER

Create FUNCTION [dbo].[SplitValues](@Str varchar(max),@Deliminator varchar(100)) returns @t table (numberval numeric(25), stringval varchar(100), DateVal datetime) as begin declare @i int; declare @c varchar(100); --set @Str = @Str + ',' set @Str = @Str + @Deliminator set @i = 1; set @c = ''; while @i <= len(@Str) begin --if substring(@Str,@i,1) = ',' if substring(@Str,@i,1) = @Deliminator begin insert into @t values (CASE WHEN isnumeric(@c)=1 THEN @c else Null END, rtrim(ltrim(@c)), CASE WHEN isdate(@c)=1 then @c else Null END) set @c = '' end else set @c = @c + substring(@Str,@i,1) set @i = @i +1 end return end ---------------- to call this function,use following... select * from dbo.SplitValues('1,2,3,4,5',',') ------------- this will return following results... items -------- 1 2 3 4 5

Tuesday, July 7, 2009

AutoCompleteExtender Control in the ASP.NET AJAX Toolkit

The AutoCompleteExtender Control in the ASP.NET AJAX Toolkit is an awesome way to offer suggestions to users in your ASP.NET Web Applications. It is also very easy to use. Create an ASP.NET AJAX Website and toss a TextBox and the AutoCompleteExtender Control on the page. Fill out the details of the control to specify the appropriate ServicePath and ServiceMethod of the web service that the AutoCompleteExtender Control will call. In this case I have a web service, called MyAutocompleteService, with a web method, called GetSuggestions. The control will start offering me suggestions once the first character is typed into the TextBox and ask for up <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox> <ajaxToolkit:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="txtCountry" ServicePath="AutoComplete.asmx" ServiceMethod="GetCountriesList" MinimumPrefixLength="1" EnableCaching="true" /> The GetSuggestions WebMethod on the WebService echos back what was typed in an just appends up to 12 characters ( A- L ) to the text typed in. Note the addition of the [ScriptService] Attribute to use the WebService with AJAX. [WebMethod] public string[] GetCountriesList(string prefixText) { DataSet dtst = new DataSet(); SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]); string strSql = "SELECT CountryName FROM Tbl_Countries WHERE CountryName LIKE '"+ prefixText+"%' "; SqlCommand sqlComd = new SqlCommand(strSql,sqlCon); sqlCon.Open(); SqlDataAdapter sqlAdpt = new SqlDataAdapter(); sqlAdpt.SelectCommand = sqlComd; sqlAdpt.Fill(dtst); string[] cntName = new string[dtst.Tables[0].Rows.Count]; int i = 0; try { foreach (DataRow rdr in dtst.Tables[0].Rows) { cntName.SetValue(rdr["CountryName"].ToString(), i); i++; } } catch { } finally { sqlCon.Close(); } return cntName; }

Friday, July 3, 2009

Fetch Numer/AlphaNumeric value from Varchar table's Field In SQL SERVER

Following function keeps only numeric characters in string and removes all the other
character from the string. This is very handy function.

    Create FUNCTION dbo.GetNumberFromVarcharField
( 
 @string VARCHAR(max) -- varchar field value 
)
RETURNS VARCHAR(max) 
AS 
BEGIN 
DECLARE @IncorrectCharLoc SMALLINT 
SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string)

WHILE @IncorrectCharLoc > 0 
BEGIN 
 SET @string = STUFF(@string, @IncorrectCharLoc,1, '') 
 SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string) 
END 
SET @string = @string

RETURN @string 
END 

--- test 

SELECT dbo.GetNumberFromVarcharField('sadas????ASDa######10')

Following function keeps only Alphanumeric characters in string and removes all
the other character from the string. This is very handy function too.

    CREATE FUNCTION dbo.GetAlphaNumericString 
( 
 @string VARCHAR(8000) 
) 
RETURNS VARCHAR(8000) 
AS 
BEGIN

DECLARE @IncorrectCharLoc SMALLINT 
SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%',@string) 

WHILE @IncorrectCharLoc > 0 
BEGIN 
 SET @string = STUFF(@string, @IncorrectCharLoc,1, '') 
 SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string) 
END 
SET @string = @string 

RETURN @string 
END 
GO 

-- Test 
SELECT dbo.GetAlphaNumericString('ABC”_I+{D[]}4|:e;””5,<.F>/?6')

Wednesday, July 1, 2009

True Random and Unique AlphaNumeric Number Generator

public string GetRandomUniqueAlphaNumericCode(int length, bool lowerCase) { int maxSize = 8; char[] chars = new char[62]; string a; a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; chars = a.ToCharArray(); int size = maxSize; byte[] data = new byte[1]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(data); size = maxSize; data = new byte[size]; crypto.GetNonZeroBytes(data); StringBuilder result = new StringBuilder(size); foreach (byte b in data) { result.Append(chars[b % (chars.Length - 1)]); } strCode = (result.ToString()).ToUpper(); bool flag = false; for (int i = 0; i < strCode.Length; i++) { if (char.IsDigit(strCode, i)) { flag = true; } } if (flag == false) { GetRandomUniqueAlphaNumericCode(); } return strCode; } here strCode is static class variable. this will generate random and unique alphanumeric string.

Forums for Microsoft .NET developers

Hi begginers to Microsoft.NET world, here a list of forums and educational sites where you can post your queries and get ur answers from professionals. this may help you to increase your knowledge and also help if u stuck with some issues…become a regular member(its free) so that source code access is easy ….and also contibute wen u have enough greymatter to solve complex issues of .NET. Comment on this post and add more forums which i might have missed …..

www.eggheadcafe.com

www.c-sharpcorner.com

www.vbdotnetheaven.com

www.dotnetheaven.com

forums.asp.net

www.codeproject.com

www.eggheadcafe.com

www.4guysfromrolla.com

www.aspalliance.com

www.devasp.net

DotNetCommunity

www.w3schools.com

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...