Adding advanced validation to an existing ASP.NET application

by rmendez 17. October 2008 04:19

What are we facing?

I want to add validation to an existing ASP.NET application. The business entities used by the application are defined on a separate assembly, used by other desktop applications. The validation mechanism provided by ASP.NET is not enough because:

  • I want to easily add my own customized, complex validation rules.
  • I’d like to avoid defining the same rules on both the desktop applications and the web applications.

 

The solution

You can use the Validation Application Block (VAP) included in the version 4.0 of Enterprise Library. When using the VAP you decorate your business entities with attributes indicating the validation performed against their properties. For instance, you might have a class Person which defines, among other members, the property Age as an integer number between 21 and 100.

In order to specify the constraint just described with VAP, the property Age in your Person class should be decorated with a RangeValidator, just as follows:

[RangeValidator(21, RangeBoundaryType.Inclusive, 100, RangeBoundaryType.Inclusive, Ruleset = "GenericPerson", MessageTemplate = "Invalid value")]

public int Age

{ … }

Back to your ASP.NET application, we assume you already have a Web Form to collect Person data. The markup corresponding to the control used to collect the age value might look as follows:

<asp:TextBox ID="AgeTextBox" runat="server"></asp:TextBox>

The first thing you need to do in order to take advantage of VAP and your already defined validation rules is adding references to Microsoft.Practices.EnterpriseLibrary.Validation and Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet –which allows connecting VAP with ASP.NET applications through the usage of the PropertyProxyValidator class. You may also need to add a reference to the assembly where the business entities are defined, along with their validation rules. More details on how to prepare your ASP.NET application in order to use the Validation Application Block can be found on the block’s documentation.

Once your application has the needed references you’ll need to register the namespace in which the VAP classes are defined. This can be accomplished by inserting the following code after the Page directive in your ASPX markup:

<%@ Register Assembly="Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet"

Namespace="Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet"

TagPrefix="vab" %>

Now you can add validators to your controls, associating them to the existing controls in your web form. The resulting markup should look like follows:

<asp:TextBox ID="AgeTextBox" runat="server" CausesValidation="True"></asp:TextBox>

<vab:propertyproxyvalidator id="AgeValidator" runat="server" ControlToValidate="AgeTextBox" PropertyName="Age" RulesetName="GenericPerson" SourceTypeName="BusinessLayer.Person">Please enter a number between 21 and 100</vab:propertyproxyvalidator>

That’s it! Your form has got validation through the usage of the VAB. You can also use the validation defined by the referenced business entities in other web forms or in a desktop application. Now if an invalid value is submitted an error message will be displayed:

clip_image002[4]

 

Some external references

  • The Validation Application Block provides several other validators besides the RangeValidator used in this post. For more information about other validators please refer to this topic on the online documentation.
  • You can add customized validators for more complex validation rules. Please refer to this topic for more details on how to extend existing validators and how to develop your new ones. 

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net

Showing interactive content in a Web slice

by César Muñoz 16. October 2008 12:56

What are we facing?

I am working with a web page that has a Web slice defined with the normal syntax.  I want to change the Web slice in order to show interactive web content.

The Solution

Web slices are a new useful feature shipped with IE8.  They allow users to subscribe to content directly within a web page.  Users can review content changes directly from the IE8 Favorites bar.

Web slices are defined with simple, semantic HTML code that indicates a web page fragment which a client browser can be subscribed to.  The following fragment specifies a basic Web slice:

<div class="hslice" id="offer">  
       
<h2 class="entry-title">Moon Airlines</h2>
  
       
<p onmouseover="animateMe(this);">Today’s offer
     
           
<span class="entry-title"><%=TodaysOfferPrice()%></span>.
        </p>
</div>

When IE8 is subscribed to this web slice you will see its title in the Favorites bar and in the preview window you will see the cached offer information, from which the active content such as script or ActiveX controls is removed.  In this case, the animation produced by the animateMe() function won’t show up in the preview window.

In order to make this animation work the previous code needs to be changed to:

<div class="hslice" id="offer">   
  
<h2 class="entry-title">Moon Airlines</h2>
   
     
<a rel="entry-content
         href="myWebslicePreviewPage.aspx" style="display:none;">
      </
a>
      
      <
p onmouseover="animateMe(this);">Today’s offer
       
                                
<span class="entry-title"><%=TodaysOfferPrice()%></span>.
      </p>
</div>

It will also be necessary to extract a copy of the p block and place it in a new web page, which in this case is called myWebslicePreviewPage.aspx.   Also the animateMe() and TodaysOfferPrice() functions and all its dependencies must be available in the new page.

Some external references

Subscribing to Content with Web Slices

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net | ie

Overriding ASP.NET themes’ skin attributes

by César Muñoz 16. October 2008 07:28

What are we facing?

I am using ASP.NET Themes and someone defined a .skin file with default visual attributes for common controls in my website.  I need to change some attributes but need to preserve the default values for the rest of them.

The Solution

ASP.NET Themes are collections of appearance-related resources that will be applied to web controls on a website.   Themes include images, control skins, CSS style sheets, and additional files (http://msdn.microsoft.com/en-us/library/de93t31k(VS.80).aspx).

Default attributes for ASP.NET web controls are specified in a .skin file including an entry with the same syntax as a normal web control, for example:

<asp:Label runat="server" BackColor="Red" ForeColor="Blue"></asp:Label> 

Then, the .skin file can be applied to an ASP.NET page by adding the Theme attribute to the corresponding Page directive, for example:

<%@ Page Language="C#" Theme="MySkinFile"%>

Now, the situation is that you need to override some of the default asp:Label attributes for a specific label control.  Let’s start with an example; the objective is to make the following label display with a yellow foreground color, given that the current skin file specifies that labels will be displayed with red background color and blue foreground:

<asp:Label ID="Label1" runat="server" Text="Label">This is the sample label text</asp:Label>

This objective should be achieved by changing only the specific attribute in order to keep the code maintainable, and keep redundancy low.  However, this change is not as easy as it might be.

One first attempt is to change the attribute in the control instance we are interested in:

<asp:Label ID="Label1" runat="server" Text="Label" ForeColor="Yellow">This is the sample label text</asp:Label>

Unfortunately this doesn’t work; the entries in the skin file have precedence over the attributes in specific controls.

The attribute EnableTheming="false" can be used to allow the specific label control to apply different attribute values, however the rest of skin attributes, which we want to reuse, is not applied.

The SkinID attribute can be used in the .skin file entry to make it specific to a control with the same id, this option does not allow us to reuse the attributes specified in the more “generic” asp:Label skin entry.

The attributes specified in the .skin file entry will be processed by the ASP.NET server, rendering them as CSS attributes and including them in the style attribute of the applicable page elements, for example, our original asp:Label would be rendered as:

<span id="Label1" style="color:Blue;background-color:Red;">This is the sample label text </span>

This gives us the final clue to achieve our objective.  A style attribute can be added to the asp:Label control in order to override the default attributes provided by the .skin file.  The source code would be:

<asp:Label ID="Label1" runat="server" Text="Label" Style="color:yellow;">This is the sample label text</asp:Label>

This would be finally rendered as:

<span id="Label1" style="color:Blue;background-color:Red;color:yellow;">This is the sample label text</span>

Some external references

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net | css

Creating a databound grid view control from a sample wireframe table

by César Muñoz 15. October 2008 04:40

What are we facing?

I am an ASP.NET programmer and need to complete some web pages that I received from a web graphic designer.  I have to provide an implementation for a read-only table with specific visual characteristics and it must get its data from a database.

The Solution

One possible solution is to use an ASP.NET 2.0 GridView control.  You can reuse part of the code that the designer has already written.

It will be necessary to perform the following tasks:

  1. Add a GridView control to the web page.
  2. Add a SQLDataSource control to the web page and assign it to the GridView.
  3. Move the table’s style info into the GridView.
  4. Remove the original table.
  5. Complete the code to populate the GridView.

Steps 1 through 4 can be summarized with html-like pattern syntax in the following way:

Original code:

<table id="productList" {Table tag attributes} style="{Table style values}"> 
   <tr style="{Row 1 style values}"> 
      {Sample data 1} 
   </tr> 
   <tr style="{Row 2 style values}"> 
      {Sample data 2} 
   </tr> 
   ...
</table>

Final code:

<asp:GridView ID="productList" runat="server" DataSourceID="SqlDataSource1" 
   {Conversion of Table tag attributes} Style="{Table style values}"> 
   <RowStyle {Conversion of Row 1 style values} /> 
   <AlternatingRowStyle {Conversion of Row 2 style values} />
</asp:GridView>        

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
   DataSourceMode="DataReader" 
   ConnectionString="<%$ ConnectionStrings:MyDatabase%>" 
   SelectCommand="SELECT Column1, Column2,... FROM MyTable"/>

In this sample, curly brackets indicate a collection of html attributes or elements, these collections are reused in the final code in their original form or converted to the corresponding AS.NET tag attributes.

Some external references

Currently rated 3.3 by 12 people

  • Currently 3.25/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net | html

Converting existing rendering of ASP.NET Controls to CSS Friendly code using adapters

by David Alfaro 15. October 2008 00:01

What are we facing?

I have an ASP.NET Website using the built-in ASP.NET server controls, but now I want them to render code that use CSS styling and a more semantic markup. I downloaded the ASP.NET 2.0 CSS Friendly Control Adapters, but the download page doesn't give any explanation of how to make my already created ASP.NET code to produce CSS friendly code.

The Solution

Actually, there are two ways to do it. The first way is provided by Fritz Onion in the post Steps for adding a CSS Control Adapter. Since the big amount of steps needed, I would rather recommend you to read that post enterily. However if you are hunger for a simpler way to do it, Simone Chiaretta enumerates the following very few steps for changing the rendering of your code using the downloaded CSS Control Adapters

  • Download the CSS Friendly Adapter from CodePlex: http://www.codeplex.com/cssfriendly.
  • Reference the CSSFriendly.dll inside your web project.
  • Create the ASP.NET App_Browser folder under your website root, and copy the CSSFriendlyAdapters.browser file in this folder.

Some external references

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net | css | marking up

Adding a Captcha to your ASP.Net page

by Will Vásquez 8. October 2008 04:15

What are we facing?

Perhaps the most common use for dynamic web pages is the retrieval of information from users, this retrieval is made using web forms. A common problem faced by the web developers is the existence of automated scripts that submit forms automatically mainly to send spam or try to saturate the server with more requests than it can handle. To avoid this kind of problems, the sites need a way to ensure that the form is being submitted by a person, not a computer program.

A CAPTCHA is a "type of challenge-response test used to ensure that the response is not generated by a computer"1, the most common type of challenge consists of an image with letters and/or numbers, often with a distorted background or with external symbols or lines, easy to recognize for a human but very difficult for a program, even with OCR capabilities.

There are many companies that offer components to add a CAPTCHA to your form, for this article we will see how to use the reCAPTCHA implementation, this is the implementation recommended by the CAPTCHA creators.

The Solution

The use of reCAPTCHA is really easy, and there are implementations for most programming environments. To add it to an ASP.Net Web Form, we need to follow these steps:

  1. Download the free component from the official reCAPTCHA page
  2. Register in the page to get the keys needed to generate and validate the CAPTCHA (In order to use the free service you will need to specify the domain where your page with the CAPTCHA will be hosted).
  3. Create our form with the information we need to retrieve.
  4. Add to your site a reference to the dll that comes with the library code (In the downloaded file, in the path recaptcha-dotnet\library\bin\Release\Recaptcha.dll).
  5. Register the recaptcha component in your .aspx page

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

  6. Add the captcha control to the form, setting the values for the public and private keys (obtained in step 2).
    		<recaptcha:RecaptchaControl
    	ID="recaptcha"
    	runat="server"
    	PublicKey=""            
    	PrivateKey=""
    	/>
    	
    After this, the CAPTCHA should be working, now you only have to validate that the entered value is correct.
  7. Validate the entered value in server side by calling the ASP.Net property Page.IsValid, if it returns true, then the value in the CAPTCHA is right, otherwise you should display a validation error.

After this, your form will have a CAPTCHA field that will look like this one (taken from the reCAPTCHA site)

Sample of a reCAPTCHA

With this you'll add a very simple (yet effective) security element to your web form in a very easy way.

Some External References

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

asp.net

About Aggiorno KC

Aggiorno RSS Feeds As Web developers, we are always hunting for pieces of wisdom spread all over the Web, by friends, by books, or both. Normally it requires time and effort to search and locate that wisdom and then even more to implement it. Knowledge Capsules provide you with a consolidated place to find all the specific pieces of code and advice you are commonly looking for, all provided by fellow Web developers.

IE8 Compatibility Wizard

Automatically upgrades your website to render correctly in IE8!

Internet Explorer 8 Compatibility Wizard

Get it today!


ArtinSoft Corporation ArtinSoft is Microsoft Certified Partner ISV/Software Solutions and Microsft Visual Studio Partner

With over fifteen years of experience, ArtinSoft has proven to be a key player in software evolution, by allowing customers from all over the world to ensure business continuity and compliance through software migration solutions and developer tools created upon principles of artificial intelligence. At present time, ArtinSoft Corporation remains a private firm in constant growth through a strategic partner network. Read More...