Checkboxlist Validation in Asp.Net

In this post, I would like to illustrate a simple requirement of Checkboxlist Validation. It is a common requirement to validate if a user has selected at least one item from available choice of items in an Asp Checkboxlist Control. Although, there are ways using Javascript etc. but I like to keep a strict control so this solution uses a Asp Custom Validator Control.

Here is a Checkboxlist; for sake of simplicity I have bound this to a DataSource, you can bind to either a datasource or a static set of options.


<asp:CheckBoxList ID="cblChoices" DataValueField="ChoiceID" DataTextField="Title" RepeatDirection="Horizontal" RepeatColumns="2" RepeatLayout="Table" CellPadding="1" CellSpacing="5" runat="server" />

Now, add a Custom Validator Control that works in conjunction with the above.


<asp:CustomValidator ID="CheckboxChoiceRequiredValidator" runat="server" ErrorMessage="Please opt in by selecting at least one choice" ValidationGroup="MyValGroup" Font-Bold="true" ForeColor="Red" OnServerValidate="CheckboxChoiceRequiredValidator_ServerValidate">

In the above, the most important attribute is OnServerValidate which listens to a method CheckboxChoiceRequiredValidator_ServerValidate which you need to have in the code behind. Lets, add the method in the code behind. [C# example; Use Tools to get Telerik Code Convertor for VB]

protected void CheckboxChoiceRequiredValidator_ServerValidate(object source, ServerValidateEventArgs args)

{

int cnt = 0;

for (int i = 0;i < cblChoices.Items.Count; i++)

{

if (cblChoices.Items[i].Selected) { cnt++; }

}

if (cnt == 0)

{

args.IsValid = false;

}

else

{

args.IsValid = true;

}

}

In the method above, a simple iteration to find out if there are selections made by user, and returning args as Boolean. Here I am using the if (cnt == 0) to check against zero but you can check for example (2) to ensure user have selected at least two choices. The main thing is of course, that Button Click event that checks for Checkboxlist Validation needs to have (see below) To ensure the Checkboxlist Validation is fired everytime a Button is clicked.

If (page.isValid) { }

Hope this was helpful.

Advertisements

Google Captcha with Asp.Net

In this post I would like to discuss and share how I have integrated the Google’s prominent and renowned Captcha with Asp.Net. For more details on Google Captcha works in conjunction with websites and the advantages of using Captcha please visit the link below:

http://www.google.com/recaptcha/captcha

To begin with you will need to download reCAPTCHA ASP.Net Library at:

https://developers.google.com/recaptcha/docs/aspnet

On the link above are examples on the use of the API and illuminates Asp.Net developers on how they can easily integrate Google Captcha to their websites as and when required. Please ensure you have signed (with Google account) and obtain the Keys that will be required for the code examples below.

When you add the reference to your Website/ Web Application Project the .dll namely recaptcha.dll and recaptcha.dll.refresh will be added to your BIN folder. You can also manually copy the .dll and paste them to your BIN folder.

Now, let’s begin with writing some code. Following the line of API examples in the link above, I add the following reference to the page where you would like your Captcha to be working on.

<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

Now, that the user control is registered, it can be used in the following way.

<recaptcha:RecaptchaControl ID="captcha" runat="server" PublicKey="YOUR_PUBLIC_KEY" PrivateKey="YOUR_PRIVATE_KEY"/>

As soon as you embed the control on the page, it is ready in action. In my case I have placed the captcha control inside the Asp Form Validation Group to makes it mandatory to be filled by end users.

Finally, there’s no guaranteeing your end users have entered the right text presented to them on the captcha. So this is where Asp CustomValidator comes handy.

<asp:CustomValidator ID="CaptchaValidator" runat="server" ErrorMessage="Please enter information correctly" Font-Bold="true" ForeColor="Red"       SetFocusOnError="true" Display="Dynamic" ValidationGroup="CaptchaValidationGroup"></asp:CustomValidator>

And finally the code behind for the CustomValidator above.

Protected Sub CaptchaValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CaptchaValidator.ServerValidate
captcha.Validate()
args.IsValid = captcha.IsValid
End Sub

There you have it, a fully working Google Captcha with your Asp.Net website. On a final note, here’s something interesting,

Captcha abbreviates to “Completely Automated Public Turing test to tell Computers and Humans Apart

Reference: http://support.google.com/a/bin/answer.py?hl=en-uk&hlrm=en-uk&hlrm=en&answer=1217728

Connection Strings Without Web Config in Asp.Net

In this post, I am writing how to employ and utilise Asp.Net Connection Strings in when you don’t have the all-important Web.Config file at your disposal and you are disabled from using the Asp.Net ConfigurationManager class to establish the connection string.

Please review the link below to ensure you are using right Connection String format fitting your development environment and SQL instance.

Reference: http://www.connectionstrings.com/sql-server-2008

For establishing SQL Server Connection, running SQL Query / Stored Procedure you would require a Connection String. The code below uses a declarative connection string where Web.Config is not available.


Dim SqlConnectionString As String = "Server=SQLSERVER;Database=DB;User ID=Username;Password=password"
Dim ConnStringSettingObj As ConnectionStringSettings = New ConnectionStringSettings("constr", SqlConnectionString)

Dim path As String = ConnStringSettingObj.ConnectionString
Dim conn As SqlConnection = New SqlConnection(path)

Dim cmdText As String = "StoredProcedure_OR_SQL_Query"
Dim cmd As SqlCommand = New SqlCommand(cmdText, conn)

cmd.CommandType = CommandType.StoredProcedure
Dim _Param As SqlParameter = New SqlParameter("_SqlArgumentIfAny", SqlDbType.VarChar)
_Param.Value = "something"

cmd.Parameters.Add(_Param)

' If data return is required / otherwise ignore
Dim adaptr As SqlDataAdapter
Dim ds As New DataSet

Try
conn.Open()
adaptr = New SqlDataAdapter(cmd)
adaptr.Fill(ds)
Catch ex As Exception
Throw New ConfigurationErrorsException
Finally
conn.Close()
End Try

Periodically Invoking Asp.Net Web Service

This is a quick post on a method that explains how to invoke Asp.Net Web Service(s) periodically. It is inevitable, that once in a while there will be a requirement where you will be pushing / pulling data via Asp.Net Web Services periodically. As much this is a common requirement, however there are several ways in which it can be engineered.

JQuery Call, JavaScript Timer based call, Asp ScriptManager control to invoke web service are some of the ways to name a few.

In the code below, I have used a Asp:Timer object to fire a desired web service periodically (every 1 minute or 60 seconds or 60,000 milliseconds). I don’t claim this is innovative way of doing this. Needless to say, this could be just one of the ways in which such a requirement can be achieved.

Declare your Asp:Timer control; requires a ScriptManager Control to work

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Timer ID="WebSvcPeriodInvoke" runat="server" Interval="60000"></asp:Timer>

Declare the native Tick() method for Asp.Timer; code-behind


Protected Sub WebSvcPeriodInvoke_Tick(sender As Object, e As System.EventArgs) Handles WebSvcPeriodInvoke.Tick

' Invoke WebService Programmatically

Dim WebSvcObj As NameOfWebService = New NameOfWebService
Dim _MethodCall As int = WebSvcObj.NameOfYourMethod(Arg1, Arg2)

' Do Something with _MethodCall Variable

End Sub

Using the method above, your .aspx page is now using a Asp:Timer control to invoke an Asp.Net Web Service periodically after every 1 minute. This is super handy, you can easily pass in parameters if required to Web Service and play with the result or be imaginative where required.

Formatting EVAL expressions in Asp.Net

This is a quick post on examples on the use of EVAL expression to render special formatting on DataBound Controls in Asp.Net webforms. With Asp.Net DataBinding, developers sometimes require binding data returned back from SQL Stored Procedure or SQL Function to be represented on webforms in a certain way, which is more readable and user friendly.

The Syntax for EVAL is <%# Eval(“ColumnName”)%>

Example: Date Formatting

Project Started: <%#Eval(“ProjectStartDate”, “{0:dd, MMM yyyy}”)%>
You want to show ’12, December 2012′ instead of 2012-12-12 13:30:00
Project Started: <%#Eval(“ProjectStartDate”, “{0: HH:mm}”)%>
You want to show ’13:30′ instead of 2012-12-12 13:30:00
* use the Tools section to learn more about the Asp.Net Date Time String Formats

Example: Yes/No Boolean Type Column

Likes Asp.Net: <%#(Eval(“LikeAsp”).Equals(true)? “Yes”:”No”)%>
You want to show ‘Yes’ and ‘No’ instead of 1 / 0

Example: String Formatting

Name: <%#String.Concat(Eval(“Roger”),”-Moore 007″)%>
You want to show Roger-Moore 007 instead of Roger

Example: IIf / If Condition : Change visibility of control

Link: <asp:HyperLink ID=”LinkForManager” runat=”server” Text=”Manager” Visible='<%# IIf(Eval(“AnyColumn”) Is DbNull.Value, “False”,”True”) %>’  NavigateUrl=”~/link.aspx”/>
You want to show Manager Link only when Bit Column is True / 1

Example: IIf / If Condition: Show Text based on Boolean

Gender: <%#IIf(Eval(“CandidateGender”).Equals(True), “Male”, “Female”)%>
You want to show ‘Male’ or ‘Female’ on CandidateGender Boolean column

* updated 10 Jan 2013

Example: Visibility of Control based on Bit / Boolean Column Value
<asp:Button ID=”Button1″ runat=”server” Text=”Button1″ Visible='<%#Convert.ToBoolean(Eval(“BitColumn”))%>’ />
Where 0 is button1.visible = false and 1 is button1.visible = true
Reference: http://stackoverflow.com/questions/7921077/set-value-for-visible-property-in-aspx-page-programatically

I will keep updating this post if I discover some examples in future.
The above can also be used with BIND expression as well.

Further Reference: http://support.microsoft.com/kb/307860

Regular Expression for Email Validation in Asp.Net

This is the Regular Expression I use for Validating Email Address from end user responses.

<asp:RegularExpressionValidator ID="EmailExpressionValidator" runat="server"
     ControlToValidate="InputEmail"
     Display="Dynamic"
     ErrorMessage="Email format is invalid"
     Text="*"
     SetFocusOnError="true"
     ValidationExpression="^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$"
     ValidationGroup="FormValidationGroup">
</asp:RegularExpressionValidator>

Reference
I would like to acknowledge thanks to Dave for sharing this with everyone.
http://stackoverflow.com/questions/936870/best-regular-expression-for-email-format-validation-with-asp-net-3-5-validation

Get Array from DataTable

Have you ever wanted to obtain a particular column in a data table as an array?

I am sure you will find this as a common requirement sometimes specially when running SQL queries against data and returning back DataTable in your SqlDataAdapter.Fill() method call.
Use the following to create desired array from a column in DataTable. I am using a String() array, you can customise DataType to suit your requirements.

Private Function GetArrayFromDataTable(dt As DataTable) As String()
     Dim _arr As String() = Nothing
     If Not dt.Rows.Count.Equals(0) Then
        ' Now the magic of one line trick
        _arr = dt.AsEnumberable().[Select](Function(row)  row.Field(Of String)(“Column Name”)).ToArray()
     End If
End Function

That’s it, you got your array of values from a DataTable.