Travis Collins

February 2008 - Posts

AJAX Timeout Server Control

Don't you hate it when you are idle on a web app for just a bit too long, and your membership session gets timed out without warning?  Your users sure do!  Often times the user may not even realize he has been timed out until he finishes completing a form, and clicks the submit button.  At which time not only has the user lost his session, he has lost his data too.

In this post, I will provide a custom control, complete with source code, which will improve this experience for your users by displaying a nice message to inform them that their session is about to expire.  It will do this without any popups or postbacks by using the ASP.NET AJAX frameworkDownload the control, and source code, here.

timeout1

Implementation is easy. Just add the control to your Visual Studio toolbox, and drag it on to your master page wherever you would like the message to appear. Set the properties to your situation and enter markup into the template section as seen here:

<tsc:Timeout 
    ID="Timeout1" 
    runat="server"
    Enabled="true"
    AboutToTimeoutMinutes="28" 
    TimeoutMinutes="30" 
    TimeoutURL="~/Default.aspx?timeout=true"
    CssClass="timeout" 
    DisplayButton="false" 
    ButtonCssClass="btn" 
    ButtonText="Continue My Session!"
    >
    <Template>
        For your safety and protection, your session is about to expire.  If you wish to continue your session, please click here.
    </Template>
</tsc:Timeout>

This control needs the ASP.NET AJAX framework to be included in your project.  It will also require a Script Manager control.  Following is a description of each property

  • Enabled - Whether the control is enabled or not.  I typically place the control on a master page, and set the enabled property in code behind based on whether the user is logged in or not.  If they are not logged in, they can't very well timeout can they?
  • AboutToTimeoutMinutes - Idle minutes until the user is informed that their session is about to time out.
  • TimeoutMinutes - Idle minutes until the membership session will time out.  This should match the forms authentication timeout property in the web.config.
  • TimeoutURL - URL to redirect the user, in the event of a membership session timeout
  • CssClass - CSS class name applied to the control
  • DisplayButton - Whether the button is visible.  If this is false, the entire control is clickable by the user to restore their session.
  • ButtonCssClass - CSS class name applied to the button control
  • ButtonText - The text to be displayed on the button
  • Template - Enter your html or asp.net markup here.  This is the message that will be displayed when the user's membership session is about to timeout.

Enjoy, and please post here if you see any room for improvement in the source.  This is my first attempt at a AJAX enabled custom control.  Download the control, and source code, here.

Dramatic Password Reveal - in ASP.NET

Jeff Atwood recently blogged about a nice feature of Vista, when you are entering your wireless network key.  This feature provides the user with a checkbox to toggle the obfuscation of the wireless key being entered.

As Jeff mentions, this is a nice technique, and one that I have recently investigated for my own web applications. However, doing this on the web is a little trickier because you aren't able to change the type attribute of an input element using JavaScript.  Shown below, I have developed a way to accomplish the same result.

First, surround your password text field with a simple span

<span id="spanPass"><asp:TextBox ID="Password" runat="server" TextMode="Password" CssClass="txt" /></span>

Add a checkbox to toggle the password obfuscation

<input type="checkbox" id="chkReveal" onclick="toggleReveal();" /><label for="chkReveal">Reveal my password</label>

 

Finally a bit of JavaScript, and we're done

<script type="text/javascript">
    function toggleReveal()
    {
        var chkReveal = $get('chkReveal');
        var txt = $get('<%= this.Login1.FindControl("Password").ClientID %>');
        var spanPass = $get('spanPass');
        
        if (chkReveal.checked)
            spanPass.innerHTML = '<input type="text" name="' + txt.name + '" id="' + txt.id + '" value="' + txt.value + '" class="'+ txt.className +'" />';
        else
            spanPass.innerHTML = '<input type="password" name="' + txt.name + '" id="' + txt.id + '" value="' + txt.value + '" class="'+ txt.className +'" />';
    }
</script>

Note I am using the handy $get which comes with ASP.NET AJAX.  If you are not using this framework, you can just as easily replace $get with document.getElementById(). 

This small JavaScript method simply rewrites the contents of the span tag with a new input control, copying the previous name, id, value, and class values.  The only thing that gets changed is the type attribute.  Now I know what you're thinking, and no, JavaScript is not able to change the type attribute directly.

I have tested this in IE6, IE7, Firefox and Safari.  It works as expected in all of these browsers.

Check Username Availability with ASP.NET AJAX

Here is a little trick you can use to spice up your asp.net registration pages. I will use ASP.NET AJAX to inform the user whether the username they have entered is available. Rather than use the UpdatePanel, I will slim down the amount of data going over the wire for each ajax request. I will accomplish this using the PageMethods feature.

This tutorial assumes that you have a working knowledge of how to start an ASP.NET AJAX web application, drop a script manager control onto your form, and use the CreateUser wizard control, or another method of registering users.  A little JavaScript knowledge will help too.

In order to use PageMethods, I will need to set the EnablePageMethods property to true on my ScriptManager.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
My registration page is called register.aspx. I will create a static method in the code behind for this page. The method will check to see if a username exists, and return a Boolean indicating whether the username is available or not.
[WebMethod]
public static bool IsUserAvailable(string username) 
{
    MembershipUser usr = Membership.GetUser(username);
     return (usr == null);
}

The WebMethod attribute is needed to mark this as a method that can be executed from Javascript.

Now I will go ahead and create some markup create some markup for my username field on your registration page. Something like this should do.

<asp:Label ID="lblUserName" runat="server" AssociatedControlID="UserName">Desired Username</asp:Label>
<asp:TextBox ID="UserName" runat="server" CssClass="txt" onkeyup="usernameChecker(this.value);" />
<span id="spanAvailability"></span>

There are a couple of things to take note of here. The onkeyup javascript event will be fired every keypress, and will be used to check the availability of the username entered.  Also take note of the span with an id of spanAvailability. The JavaScript will use this span to write output letting the user know whether the username is available.

Here's the last part, the Javascript that wires everything together.  I will insert this at the bottom of my register.aspx page:

<script type="text/javascript">
var usernameCheckerTimer;
var spanAvailability = $get("spanAvailability");

function usernameChecker(username) 
{
    clearTimeout(usernameCheckerTimer);
    if (username.length == 0)
        spanAvailability.innerHTML = "";
    else
    {
        spanAvailability.innerHTML = "<span style='color: #ccc;'>checking...</span>";
        usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
    }
}

function checkUsernameUsage(username) 
{
    // initiate the ajax pagemethod call
    // upon completion, the OnSucceded callback will be executed
    PageMethods.IsUserAvailable(username, OnSucceeded);
}

// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{
    if (methodName == "IsUserAvailable")
    {
        if (result == true)
            spanAvailability.innerHTML = "<span style='color: DarkGreen;'>Available</span>";
        else
            spanAvailability.innerHTML = "<span style='color: Red;'>Unavailable</span>";
    }
}
</script>

This effect is pretty easy to do, and adds a nice value to the user experience.  I hope you are able to find use for this technique in your applications.

Update: Download a sample project here

Unit next time,

Travis

There Goes The Neighborhood

Well I've decided to join the blogging trend, and hopefully pay it forward with some help to the community.  This should also force me to more thoroughly research topics which interest me.  Keep an eye on this space for the latest things I've learned in .NET, ASP.NET, Visual Studio, AJAX, or whatever technology I happen to be using today.

We'll see how long this lasts...

XOXO
Travis

More Posts