.Net ASP.Net – Forms Based Authentication With Textboxes

0 Comments

There are a number of different ways to do Forms Authentication in ASP.Net. In this tutorial, we will deal with Forms Authentication using two standard TextBoxes.

So first, we are going to create a new ASP.Net application project. You can give it whatever name you want to.

Once the project has been created, we will need to add a new WebForm to the project. This is done by right-clicking on the project –> Add –> New Item… –> WebForm

1

Next, we are going to simply add 3 Labels, 2 Textboxes, and a Button. Here is the markup…

<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <asp:Label ID="label1" runat="server" Text="Username:" />
                </td>
                <td>
                    <asp:TextBox ID="txtUserName" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="label2" runat="server" Text="Password:" />
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnLogin" runat="server" Text="Login" onclick="btnLogin_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblInformation" runat="server" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>

Just a really simply form with a textbox for the Username and Password. The third label will be used to show an error if the login fails.

Next, we are going to have our login code…

public partial class Login : System.Web.UI.Page
{
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        bool validLogin = false;

        validLogin = IsValidUser(txtUserName.Text.Trim(), txtPassword.Text.Trim());

        if (validLogin)
            // this will redirect the user back to the page they were originally trying to visit.
            //   if the user came directly to the Login page, it will redirect to the "defaultURL" from
            //   the web.config
            FormsAuthentication.RedirectFromLoginPage(txtUserName.Text.Trim(), false);
        else
            // not a valid login
            lblInformation.Text = "Incorrect Login Information";
    }

    private bool IsValidUser(string userName, string password)
    {
        // this is a very simple example where I am looking for this exact
        //   user name and password.  This could be any type of validation.
        if (userName == "admin" && password == "password")
            return true;
        else
            return false;
    }
}

The FormsAuthentication.RedirectFromLoginPage method will redirect users to the page they were trying to visit before they were redirected to the Login page. If they came directly to the login page, this code will redirect them to the defaultUrl from the web.config.

We now need to make some changes to the web.config file.

<system.web>
  <!-- some other attributes -->

  <authentication mode="Forms">
    <forms
      name=".LOGIN"
      loginUrl="Login.aspx"
      defaultUrl="Default.aspx" />
  </authentication>

  <authorization>
    <deny users="?"/>
  </authorization>
</system.web>

Some explanation about some of the authentication attributes:

name - this can really be anything.
loginUrl - this is the page where the user will be redirect to when they are not authenticated.
defaultUrl - this is the page that the user will be redirected to after authentication IF they came directly to the login page.

There are other attributes, but these are the only necessary ones.

The <deny users=”?”/> means to deny all non-authenticated users. So anybody who is not authenticated will be redirected to the login page.

Now, on our Default.aspx page, we are simply going to add a label that will display the user name that logged in.

<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblUserDisplay" runat="server" />
    </div>
    </form>
</body>

And the code for the Default.aspx page is just as simple…

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblUserDisplay.Text = "Hello " + User.Identity.Name;
    }
}

Now, if you set the Login.aspx page as the Startup page in Visual Studio(right-click on page –> Set As Startup Page) then start debugging, you will see the login screen come up. Put in “admin” for the user name, and “password” for the password, then hit the Login button, you will now be redirected to the defaultUrl(most likely the default.aspx page). You will also notice that you are greeted with a message.

Now, add a third WebForm to the project. This will be just a dummy form. Set it as the startup page, then run the project. You will now be redirected to the Login page, and after logging in, you will be redirected back to the dummy page.

This is only one way to do Forms Authentication in ASP.Net.

Enjoy.

Tags: ,

.Net C# – Get Windows Mobile Theme Color

1 Comment

I recently had a business requirement to color the background of a TextBox in Windows Mobile to a specific color.  After completing the tasks, I noticed that the color that was chosen(blue) didn’t look right on devices that used a different theme like red or green.  So I decided to figure out how to set the background color to match the theme color.

The theme system colors are located in the registry entry HKLM\System\GWE\SysColor.  This registry entry is a BLOB that contains 29 DWORD values that correspond to the different colors of the theme.

For my application, I decided to use the color of the title bar of active windows.  This color is normally the dominate color of the theme.  This color is the third DWORD value in the registry entry.

Each DWORD value in the registry entry is a 4 byte HEX value that corresponds to a specific color.  The first byte is the RED value, second value is the GREEN value, third value is the BLUE value, and the fourth value is always 0.

For this code, I used the OpenNetCF framework to get the registry values.

/// <summary>
/// Gets the theme color
/// </summary>
/// <returns> Returns a Color or null</returns>
public Color? GetThemeColor()
{
    try
    {
         // gets the registry key
         RegistryKey keyColor = Registry.LocalMachine.OpenSubKey(@"System\GWE");

         // keyColor will be null if registry key was not found
         if (keyColor == null)
             return null;

        byte[] data = (byte[])keyColor.GetValue("SysColor");

        if (data[8] != 0 && data[9] != 0 && data[10] != 0)
        {
             // the third set of values is for the color of the
             //    title bar of an active window.
             int red = Convert.ToInt32(data[8]);
             int green = Convert.ToInt32(data[9]);
             int blue = Convert.ToInt32(data[10]);

             return Color.FromArgb(red, green, blue);
        }

        return null;
    }
    catch
    {
         return null;
    }
}

Usage is pretty simple for the method…

Color? themeColor = GetThemeColor();

if(themeColor != null)
   txtComments.BackColor = themeColor;
Tags: , ,

.Net C# – XML Element Value Generic Extention Method

2 Comments

Recently, I was working on integrating a help desk API into one of our applications.  The API would return XML and I was using LINQ-To-XML to get the values of the elements.  However, a number of the elements in the API were allowed to be null, like a field for the completed date of a help desk ticket.  So, I started out writing my code like this…

// constructor for Ticket class
public Ticket(XElement element)
{
     AssignedDate = (!string.IsNullOrEmpty(element.Element("assigned-date").Value)) ? DateTime.Parse(element.Element("assigned-date").Value) : (DateTime?)null;

     // .... on and one for about 40 elements
}

I looked back and thought I should come up with a better way of getting the data from the Element and into the datatype that I needed.  So I came up with this generic extension method…

/// <summary>
/// Gets the value of the element.  Will convert the value to specified type if
///    possible.  If not possible, will return default value for type.
/// </summary>
/// <typeparam name="T">Type that should be returned</typeparam>
/// <param name="ele"></param>
/// <returns></returns>
public static T GetElementValue<T>(this XElement ele)
{
    // if the element is null, then return the default
    if (ele == null)
        return default(T);

    // if value is blank or null, just return the default value
    //   for the type.
    if (string.IsNullOrEmpty(ele.Value))
        return default(T);

    // since the type of the Value property is a string, no need
    //   to do anything fancy.  Just return the value.
    if (typeof(T) == typeof(string))
        return (T)Convert.ChangeType(ele.Value, typeof(T));

    // creates new object of type T to store converted value
    T newObject = default(T);

    // check to see if it's a nullable type.  If so, get the underlying
    //   type.
    // Nullable types don't have a Parse method.  Therefore, we need the
    //   underlying type so we can call the Parse method through reflection
    //   to convert the value.
    PropertyInfo[] properties = typeof(T).GetProperties();
    Type underlyingType = typeof(T);

    // Nullable types will have two properties.  The first is the HasValue
    //   property.  The second is the underlying type.  However, some other
    //   types(such as String), and custom classes/structs could also have
    //   only two properties.  So we check to make sure that there are only
    //   2 properties, then we make sure the first property is the HasValue
    //   property.  Theoretically, this could still give a false positive.
    if (properties.Count() == 2 &&
        string.Equals(properties[0].Name, "HasValue", StringComparison.InvariantCultureIgnoreCase))
        underlyingType = properties[1].PropertyType;

    try
    {
        // calls Parse method for the type
        MethodInfo method = underlyingType.GetMethod("Parse", new[] { typeof(string) });
        newObject = (T)method.Invoke(null, new[] { ele.Value });
    }
    catch (Exception)
    {
        throw;
    }

    return newObject;
}

Now with this extension method, it really cuts down on the amount of code I have to write.  I can now use it like this..

public Ticket(XElement element)
{
     AssignedDate = element.Element("assigned-date").GetElementValue<DateTime?>();
}

I hope this can help out somebody.

Tags: , , ,