Friday, February 11, 2011

Form Validation

ASP.NET makes it really simple, maybe to simple, to add form validation to your web forms. Suppose we had a simple form that consisted of these fields:


  • First Name
  • Last Name
  • Email Address
The code for such a form would probably resemble this:

  1.  <form id="simpleForm" runat="server">
  2.     <div>
  3.    
  4.         First Name:<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
  5.         <br />
  6.         Last Name:<asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
  7.         <br />
  8.         Email Address:<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
  9.         <br />
  10.        
  11.     </div>
  12.  </form>

After we add our validation controls, which you can add from the "Validation" tab of the Toolbox, the code looks like this:

  1.     <form id="signUp" runat="server">
  2.     <div style="width: 957px">
  3.    
  4.         First Name:<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
  5.         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
  6.             ControlToValidate="txtFName" ErrorMessage="First Name Required"></asp:RequiredFieldValidator>
  7.         <br />
  8.         Last Name:<asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
  9.         <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
  10.             ControlToValidate="txtLName" ErrorMessage="Last Name Required"></asp:RequiredFieldValidator>
  11.         <br />
  12.         Email Address:<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
  13.         <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
  14.             ControlToValidate="txtEmail" ErrorMessage="Enter a vaild email address"
  15.             ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
  16.         <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
  17.             ControlToValidate="txtEmail" ErrorMessage="Email address required"></asp:RequiredFieldValidator>
  18.         <br />
  19.        
  20.     </div>
  21.     </form>

And what will happen now is our web form will make the First Name, Last Name and email fields required, as well as validate that the email address is really an email address.

Yield: Button redirection

Sometimes it is necessary to provide a way to get from one web page to another. Normally this is done with links, but sometimes you might come across a situation where you need to do this from within your code.

This can be accomplished in ASP.NET by using the "Response" property of the current web form. Keep in mind that the "Response" property is just a System.Web.HttpResponse(), and this means that anything we could do with the System.Web.HttpResponse(), we can do with the "Response" property of our web form.

Linking to an external web page using the "Response" property of the web form:
  1. Response.Redirect("http://ibreakcode.blogspot.com")

Linking to an internal web page using the "Response" property of the web form:
  1. Response.Redirect("Default2.aspx")

And thats about all there is to that.

Creating A Blank ASP.NET Project

Microsoft Visual Studio 2010 gives you a few options to create an ASP.NET website pre-loaded with a bunch of websites already built for you. This is great if you just want something to play around with something, but don't do you much good if you don't know whats going on.

For this reason, the remainder of the ASP.NET posts, unless otherwise noted will be using blank ASP.NET website projects.

To create a blank ASP.NET website project, open Microsoft Visual Studio and follow these steps:



  1. Click the "File" menu option on the main menu
  2. Click the "New" sub-menu option
  3. Click the "Web Site..."
After you click the menu option in Step 3 , the following dialog will appear (Note: I'm using Microsoft Visual Studio 2010 Professional):


On the dialog box, you will see something titled "Web location" and you should have the following options:
The "New Web Site" dialog.

  • File System
    • This creates a website on your local file system. Such as C:\Websites. These website are not available to the actual Internet via IIS or other server technologies, unless you create a virtual directory pointing to them. 
  • HTTP
    • These are IIS websites located on the local computer, or a remote computer.
  • FTP
    • These are websites that you connect to with FTP. You will need to provide credentials to access the FTP server.
More information on ASP.NET web locations can be found here.
    When selecting the project template, choose "ASP.NET Empty Web Site". This will create a blank ASP.NET project where you can add your own web site components.

    Microsoft has an example project that you can play around with if you choose "ASP.NET Web Site"

    Monday, January 24, 2011

    The Frog Database

    The AmphibiaWeb website shows the different amphibians in different regions of the world. The link will show you the amphibians in the United States, organized by U.S. states.

    We are going to create a simple database that uses some of the data from this website. This post will use the data from Wyoming, located here.

    The website contains the following columns from their database:
    • Scientific Name
    • Photo
    • Map
    • Sound
    • IUCN Red List Status
    • Vernacular Name
    • Family
    Our database table will only utilize four of the columns:
    • Scientific Name
    • IUCN Red List Status
    • Vernacular Name
    • Family
    Here will be our database structure:

    Database: Amphibians
    Table(s): Wyoming

    First, lets create the database and table. We will only insert a few of the records:

    1. CREATE DATABASE Amphibians;
    2. GO
    3. USE Amphibians;
    4. GO
    5. CREATE TABLE Wyoming
    6. (
    7.     amph_ID INT IDENTITY(1,1) PRIMARY KEY
    8.     , scientific_Name VARCHAR(100)
    9.     , rl_Status VARCHAR(75)
    10.     , vernacular_Name VARCHAR(100)
    11.     , family VARCHAR(100)
    12. );
    13. INSERT INTO Wyoming
    14. (
    15.     scientific_Name
    16.     , rl_Status
    17.     , vernacular_Name
    18.     , family
    19. )
    20. VALUES
    21. (
    22.     'Bufo baxteri'
    23.     , 'Extinct in the Wild (EW)'
    24.     , 'Wyoming Toad'
    25.     , 'Bufonidae'
    26. );
    27. INSERT INTO Wyoming
    28. (
    29.     scientific_Name
    30.     , rl_Status
    31.     , vernacular_Name
    32.     , family
    33. )
    34. VALUES
    35. (
    36.     'Bufo boreas'
    37.     , 'Near Threatened (NT)'
    38.     , 'Western Toad'
    39.     , 'Bufonidae'
    40. );
    41. INSERT INTO Wyoming
    42. (
    43.     scientific_Name
    44.     , rl_Status
    45.     , vernacular_Name
    46.     , family
    47. )
    48. VALUES
    49. (
    50.     'Bufo cognatus'
    51.     , 'Least Concern (LC)'
    52.     , 'Great Plains Toad'
    53.     , 'Bufonidae'
    54. );
    55. INSERT INTO Wyoming
    56. (
    57.     scientific_Name
    58.     , rl_Status
    59.     , vernacular_Name
    60.     , family
    61. )
    62. VALUES
    63. (
    64.     'Bufo hemiophrys'
    65.     , 'Least Concern (LC)'
    66.     , 'Canadian Toad'
    67.     , 'Bufonidae'
    68. );

    If you run a select all query on the new Amphibians table, you should get this result:

    ---------------------------------------------------------------------------------------

    amph_ID scientific_Name rl_Status vernacular_Name family
    1 Bufo baxteri Extinct in the Wild (EW) Wyoming Toad Bufonidae
    2 Bufo boreas Near Threatened (NT) Western Toad Bufonidae
    3 Bufo cognatus Least Concern (LC) Great Plains Toad Bufonidae
    4 Bufo hemiophrys Least Concern (LC) Canadian Toad Bufonidae


    Thursday, January 20, 2011

    Table variables and SQL Server

    In a recent post, I mentioned temporary tables (you can find that post here). An alternative to temporary tables are table variables. Tablevariables are a lot like temporary tables, except the table variable has a few advantages over temporary tables:

    • Table variables usually use fewer resources than a temporary table, which makes it a little bit faster
    • Table variables will not exist after the procedure that called it exits, so there is no clean-up required with DROP statements like temporary tables
    We declare table variables sort of like other variables, but the syntax looks like this:

    DECLARE @<VariableName> TABLE
    (
    <COLUMNS>
    );

    Here is an example, using the Library database I created in an earlier post:

    1. USE Library
    2. DECLARE @SomeAuthors TABLE
    3. (
    4.     authorID INT
    5.     , first_Name VARCHAR(50)
    6. );

    Here is a way we could use table variables:

    1. USE Library
    2. DECLARE @SomeAuthors TABLE
    3. (
    4.     author_ID INT
    5.     , first_Name VARCHAR(50)
    6. );
    7. INSERT INTO @SomeAuthors SELECT author_ID, first_Name
    8. FROM Authors WHERE first_Name = ' Geoffrey';
    9. UPDATE Authors SET Authors.last_Name = 'We updated this column'
    10. WHERE Authors.first_Name IN (SELECT first_Name FROM @SomeAuthors);
    11. SELECT * FROM Authors;

    What this is doing is created a table variable called "SomeAuthors" and it is going to take the records from the Authors table in our Library database and put them into our SomeAuthors temporary variable. Then this little script is going to update all our records in the Authors table based on what is in the SomeAuthors variable. This can be expanded to do some rather cool things when we need to update records. The final line is just there to return the records of the Authors table to see what our script has done.

    Temporary tables and SQL Server

    When dealing with SQL Server and tables, sometimes you want to move data, make changes to a table just to see what happens and not affect your existing table structure. This might seem like a taboo thing, or part of the SQL Server Black Magic, but it is fairly simple to do this with temporary tables.

    There are two types of temporary tables in Microsoft SQL Server:

    • Local - these tables visible only in the current session, and they are created like a normal table but with a # in from of the table name
    • Global - these temporary tables are visible to all sessions, and they are created like a normal table but with a ## in from of the table name
    Here are a few rules regarding temporary tables:

    • Creating temporary tables using the CREATE TABLE syntax supports constraint definitions, except for FOREIGN KEY constraints
    • Temporary tables cannot be referenced in FOREIGN KEY constraints
    • All local temporary temporary tables are dropped automatically at the end of the current session
    • A local temporary table created in a stored procedure is dropped when the stored procedure is finished
    • A local temporary table can be referenced by any nested stored procedures called by the stored procedure
      • This means that if there is stored procedure "A", "B", and "C" and a temporary table is created in B, and stored procedure C is called with in B, and B is called by A, the temporary table can be referenced in both B and C, but not A.
    • Local temporary table names cannot exceed 116 characters
    To create a temporary table, we use the normal CREATE TABLE syntax, except we add a "#" right before the table name. Let's create a temporary table named "TempUsers"

    1. CREATE TABLE #TempUsers
    2. (
    3.     firstName VARCHAR(30)
    4.     , lastName VARCHAR(30)
    5.     , nickName VARCHAR(30)
    6. );

    As you can see, it looks almost exactly the same as creating a normal table, except for the use of the "#". And we can pretty much do everything else with the temporary table (except using foreign key constraints, of course). For example, we can insert records into it:

    1. INSERT INTO #TempUsers
    2. (
    3.     firstName
    4.     , lastName
    5.     , nickName
    6. )
    7. VALUES
    8. (
    9.     'John'
    10.     , 'Doe'
    11.     , 'Jimmy'
    12. );

    And if we did a select all on our table we can actually see the data entered with our insert statement:

    1. SELECT * FROM #TempUsers;

    Output:


    firstName
    lastName
    nickName
    John
    Doe
    Jimmy


    And, if you want the overly complicated MSDN description of everything there is on temporary tables in Microsoft SQL Server, click here.

    Wednesday, January 19, 2011

    Selecting and Viewing Records

    In the I Break Code’s Inserting Records post we inserted two authors into our Authors table and two books into our Books table, which reside in our Library database. After we insert this information into our database, we need some means of retrieving that information. We can do that with the SELECT statement.

    The SELECT statement is fairy simple to use. We can use it to select specific columns, or all columns.

    Let’s say we wanted to view all our records, or rows, in our Authors table. We would write it like this:

    1. USE Library;
    2. GO
    3.  
    4. SELECT * FROM Authors;

    And SQL Server would return this output when executed:

    author_ID

    first_Name

    last_Name

    1

    Geoffrey

    Chaucer

    2

    William

    Shakespeare

    And if we wanted to select our books from our database we would do it like so:

    1. USE Library;
    2. GO
    3.  
    4. SELECT * FROM Books;

    And SQL Server would return this output when executed:

    book_ID

    title

    genre

    description

    1

    The Cantebury Tales

    Classic/Poetry

    A great collection of poems and stories.

    2

    Macbeth

    Classic/Play

    "Fair is foul, and foul is fair". - ( Quote Act I, Scene I).

    We can also specify exactly what columns we want to select from our tables too:

    1. USE Library;
    2. GO
    3.  
    4. SELECT first_Name, last_Name FROM Authors;
    5. SELECT title FROM Books;

    And SQL Server would return this output:

    Output from line 4:

    first_Name

    last_Name

    Geoffrey

    Chaucer

    William

    Shakespeare

    Output from line 5:

    title

    The Cantebury Tales

    Macbeth

    Try  experimenting by selecting different combinations of column names, in different orders, or the same column names multiple times to see what kind of output you can come up with.

    I Break Code Where code gets done.
    ASP.NET | HTML | SQL Server | VB.NET | Request A Topic |