Join Webhostforasp.net
dailtcode logo

Using client side validation in .Net

clock December 22, 2008 18:13 by author mderaeve

In this next example I will briefly explain the use of validators in ASP.Net

When we create web applications, there is always a need to perform client-site validation on user input. .Net really facilitates this with the use of validators. I will show the use of a regularexpression validator.

I have a form that needs some numeric input. It has to be a positive number. When the input is wrong, I don't want my button event to fire. Since I'm using AJAX no postback will be fire anyway, but still the button event is fired. So this is how to correctly handle a situation like this:

First place the input and button on the screen, next to the input you can place the regularexpression validator.

The ASP code looks like this:

<tr>
                        <td>
                            <asp:Label ID="Label5" runat="server" Text="Lot number"></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtLotNumber" runat="server" ValidationGroup="Numeric">0
			    </asp:TextBox>    
                        </td>
                        <td>
                            <asp:RegularExpressionValidator ID="RegularExpressionValidator3" 
				runat="server" 
                                ControlToValidate="txtLotNumber" 
                                ErrorMessage="Please provide a positive number" 
				ValidationExpression="^\d+$" 
                                ValidationGroup="Numeric"></asp:RegularExpressionValidator>
                        </td>
                    </tr>
                    <tr>
                        <td><asp:Button ID="btnSave" Text="Save" runat="server" 
				OnClick="btnSave_Click" 
                                ValidationGroup="Numeric" Width="100px" /></td>
                    </tr>

The validationexpression is: ^\d+$ More on these expressions you can find here. As you can see I called the validationgroup numeric. This is because we only have numeric validation on this button event. If you have several validations that need to be performed with this button event, then you'll need a more general validation group name, keep in mind that you can only use 1 validationgroup for the button. When the button is in the same validationgroup as the regularexpressionvalidator, the button event will only be fired when the validations are valid. You can use several validationgroups on one page, in case you have more then 1 event that needs validation. No postback or event are triggered making the user expirience on your site better. No time wasted on refreshing screens or manually perfomring validations. No problems with control states.  

After the regular expression was checked, I needed to check on required fields. This is not possible using regular expression validators, so I had to add a required field validator. Using the designer of VS 2008, I added this validator. Then when I tried out the validators, it appeared that the second validator had a space between the control to validate. I googled and found out that you need to set the Display to dynamic. In the following example I changed the first 2 controls, the last I didn't change, you can see the result at the picture below the code:

<tr>
    <td>
        <asp:Label ID="Label3" runat="server" Text="Amount"></asp:Label>
    </td>
    <td>
        <asp:TextBox ID="txtAmount" runat="server" ValidationGroup="SaveArrival"></asp:TextBox>    
    </td>
    <td>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" 
            ControlToValidate="txtAmount" ErrorMessage="Please provide a positive number" 
            ValidationExpression="^\d+$" ValidationGroup="SaveArrival" 
            Display="Dynamic"></asp:RegularExpressionValidator>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="txtAmount" ErrorMessage="Amount is required!" 
            ValidationGroup="SaveArrival" Display="Dynamic"></asp:RequiredFieldValidator>
    </td>
</tr>
<tr>
    <td>
        <asp:Label ID="Label4" runat="server" Text="K number"></asp:Label>
    </td>
    <td>
        <asp:TextBox ID="txtKNumber" runat="server" ValidationGroup="SaveArrival">0</asp:TextBox>    
    </td>
    <td>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
            ControlToValidate="txtKNumber" ErrorMessage="Please provide a positive number" 
            ValidationExpression="^\d+$" ValidationGroup="SaveArrival" 
            Display="Dynamic"></asp:RegularExpressionValidator>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="txtKNumber" ErrorMessage="K number is required!" 
            ValidationGroup="SaveArrival" Display="Dynamic"></asp:RequiredFieldValidator>
    </td>
</tr>
<tr>
    <td>
        <asp:Label ID="Label5" runat="server" Text="Lot number"></asp:Label>
    </td>
    <td>
        <asp:TextBox ID="txtLotNumber" runat="server" ValidationGroup="SaveArrival">0</asp:TextBox>    
    </td>
    <td>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" 
            ControlToValidate="txtLotNumber" 
            ErrorMessage="Please provide a positive number" ValidationExpression="^\d+$" 
            ValidationGroup="SaveArrival"></asp:RegularExpressionValidator>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
            ControlToValidate="txtLotNumber" ErrorMessage="Lot number is required!" 
            ValidationGroup="SaveArrival"></asp:RequiredFieldValidator>
    </td>
</tr>
 

 

As you can see I used SaveArrival as ValidationGroup, because I now have more then 1 validation type.



ASP .Net Calendar: Set selected date by default on today

clock December 20, 2008 19:05 by author mderaeve

As the title tells you, I was trying to set the default selected day of a asp .Net calendar to today. It looked like this:

Calendar1.SelectedDate = DateTime.Now;

But when the page loaded, the selected date was not shown, it was set, but not shown. So I found this solution: You have to use DateTime.Today instead of DateTime.Now.

Calendar1.SelectedDate = DateTime.Today;

That's all.

 



Simple security in ASP.Net pages

clock October 8, 2008 08:00 by author mderaeve

Just use a Masterpage and add this to the page load of the masterpage:

protected void Page_Load(object sender, EventArgs e)
    {
        //Login check
        if (Session["USERObj"] == null)
        {
            Response.Redirect(@"~\login.aspx");
        }
        else
        {
            lnkLogOff.Text = "Logoff " +  ((User)Session["USERObj"]).Name;
            BuildMenu((User)Session["USERObj"]);
        }
    }
 
private void BuildMenu(CCUser cCUser)
    {
	//Here I can build the navigation menu for this user.
 

On the login page you only have to check the users credentials and write the user object to the session.

Take note of the title, its a simple solution with high flexability. There are millions of way to secure a website, this is one of the most simple ways, especially when you want to implement active directory security:

This function checks username and pasword in AD:

public bool IsAuthenticated(string domain, string username, string pwd)
    {
      string domainAndUsername = domain + @"\" + username;
      string path = "";
      DirectoryEntry entry = new DirectoryEntry(path, domainAndUsername, pwd);
      
      try
      {
          DirectorySearcher search = new DirectorySearcher(entry);
 
          search.Filter = "(SAMAccountName=" + username + ")";
          search.PropertiesToLoad.Add("cn");
          SearchResult result = search.FindOne();
 
          if (null == result)
          {
              return false;
          }
      }
      catch (Exception ex)
      {
          throw ex;
      }
 
      return true;
    }

If username and pasword are validated, then write a User object to the session. The masterpage will perform the login check. I created multiple masterpages, if a page is public, I use a different masterpage, this is not needed, but has a lot of advantages. You can enforce a differtent look for public pages and non-public pages, ...

In the public masterpage I still check for a logged in user but there will be no redirect:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["USERObj"] == null)
        {
            lnkLogOff.Text = "Login";
        }
        else
        {
            lnkLogOff.Text = "Logoff " +  ((CCPL.CC_Objects.User)Session["USERObj "]).Name;
        }
    }

 

Tip, make sure the login page uses the public masterpage, else it would keep rederecting or you'll have to write dirty code.

 



Save a HTML page to File

clock May 28, 2008 21:06 by author mderaeve

When I print a report, I create a html page that the user can print. Now, there was a need to backup these reports. So I had to find out how to save the html code to a file. The solution was very simple:

        System.Net.WebClient client = null; 
        try 
        { 
            client = new System.Net.WebClient(); 
            client.Encoding = System.Text.Encoding.UTF8; 
            client.Headers = new System.Net.WebHeaderCollection(); 
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;)"); 
            string url = Request.Url.ToString().Replace("administration","reports"); 
            url = url.Replace("reports.aspx", "reportprint.aspx?reportGuid=" + guid); 
            //string html = client.DownloadString(url); 
            string path = ConfigurationManager.AppSettings["ArchivePath"] + guid +".html"; 
            client.DownloadFile(url, path); 
        } 
        catch (Exception r) 
        { 
            string test = r.Message; 
        } 
        finally 
        { 
            client.Dispose(); 
        } 

The url string had to be the full url, no relative url's. So I took the url of the current page and replaced 2 parts of the url to make the correct url. The path where the report are saved is stored in the config file.



On bubble event

clock May 13, 2008 09:59 by author mderaeve

When you are creating ASP.net pages and content is build up from a DB, you'll probably work with usercontrols, placeholders ...

Recently I encountered another challenge. I was adding usercontrols to a placeholder to a page dynamically. The user controls have a save button which saved the data to the database. But then the parent page needed to be refreshed. I could do this by using a redirect to the page and it would be refreshed. But when data grows, a page refresh is less and less attractive. So I googled and came up with this solution: The OnBubbleEvent. If you want to read on what the event actually does, please google some more, I can show you a practical example.

Put this code on the page that calls holds the user control.   

    protected override bool OnBubbleEvent(object source, EventArgs args)    
    {
        CommandEventArgs e = (CommandEventArgs)args;        
        if (e.CommandName == "Rebind")        
       {            ClearThePlaceHolders();            
            RefreshTheData();       
        }
        return true;
    } 

   

When you finished the event (After you saved the data) on the user control, you can activate the bubble event!

    CommandEventArgs args = new CommandEventArgs("Rebind", String.Empty);
    RaiseBubbleEvent(null, args);
 

So now, only the part we choose is refreshed. This way the asp stays light weight.



Search


Categories





Locations of visitors to this page

About

Mark Deraeve

Blogroll

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

This site was created by Jetro Wils and Deraeve Mark powered by BlogEngine

© Copyright 2009

Sign in