Click here to Skip to main content
Click here to Skip to main content

Fully configured ASP.NET Membership Website Template

By , 7 Jul 2009
 

Introduction 

The attached Visual Studio template is used to instantly create a website project that contains all the boiler plate code usually tedious to development (login/logout, displaying messages, Master page, CSS, JavaScript, error handling, changing passwords, etc...). This article provides a fully configured starting point for website project development with all that boiler plate code already completed.

Background

The starting point in an application usually takes the longest getting the application configured properly to display messages in a uniform way, or to get the login features working. In order to speed up this portion of the application development process, I built this application template for use with Visual Studio 2008 to provide a stepping stone for all further website development.

If you don't know about Visual Studio project and item templates, surf over to here for an overview before continuing on. If you don't know about Base Pages and their uses, please surf over to here for an overview before continuing on. If you don't know about Master Pages and their uses, please surf over to here for an overview before continuing on.

Using the code

Place the attached .zip file into your Project Templates folder associated with Visual Studio 2008. The default location is {drive}:\...\Documents\Visual Studio 2008\Templates\ProjectTemplates. If you don't know where yours is, then open Visual Studio -> Tools -> Options -> Projects and Solutions, and look at the "user project templates location" textbox to see where Visual Studio is looking for custom project templates.

After placing the .zip file in your Project Templates folder, open Visual Studio 2008 and click File-> New Website. Name your website and click OK. A new website project will be in your solution, and it will contain the following items different than a normal website project:

  • Admin/{Default.aspx, web.config}
  • App_Code/{BasePage.cs, BaseMasterPage.cs}
  • App_Data/Web.sitemap
  • DefaultMaster.master
  • Global.asax
  • Login.aspx
  • Logout.aspx
  • web.config
  • Stylesheets/stylesheet.css
  • Scripts/JScript.js
  • Images/{Warning.gif, Error.gif, Information.gif}

Plus the normal Default.aspx but it is different in that it references the DefaultMaster.master as its Master page.

Go to the web.config file and change the connection string to point to a valid database that contains the ASP.NET membership tables. Confirm that the applicationName="" attribute that the membership and role sections of the web.config file points to are named correctly.

<roleManager enabled="true">
  <providers>

    <clear />
    <add name="AspNetSqlRoleProvider" 
         type="System.Web.Security.SqlRoleProvider, System.Web, 
               Version=2.0.0.0, Culture=neutral, 
               PublicKeyToken=b03f5f7f11d50a3a"         
         connectionStringName="appNameConnectionString" 
         applicationName="appName" />

  </providers>
</roleManager>
<membership>
  <providers>
    <clear />
      <add name="AspNetSqlMembershipProvider"

           type="System.Web.Security.SqlMembershipProvider, System.Web, 
                 Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
           connectionStringName="appNameConnectionString"
           ...
           applicationName="appName" .../>
      </providers>

    </membership>

Add your header image to the Images folder. On the DefaultMaster.master page, add the ImageUrl="" attribute to the imgHeader image control to point to your header image.

Ensure the Regular Expression for passwords is correct in the web.config. The current expression requires a password between 8 and 15 characters, and requires the use of:

  1. a number (?=.*\d)
  2. a lower case letter (?=.*[a-z])
  3. an uppercase letter (?=.*[A-Z])
  4. and a special symbol (?=.*[!@#$%^&amp;*()_+])
<membership>

  <providers>
    <add ... passwordStrengthRegularExpression="" />
    <appSettings>
    ...
    <add key="PasswordRegEx" 
         value="(?=^.{8,15}$)
                (?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&amp;*()_+])
                (?!.*\s).*$"/>

  </appSettings>

Develop some way to log errors that occur in the application, and place that code in the Global.asax Application_Error method and the BasePage.HandleException(Exception ex) method:

public void HandleException(Exception ex)
{
    if (ConfigurationManager.AppSettings["Environment"] == "Development")
    {
        Master.ErrorMessage = ex.Message;
    }
    else
    {
        Master.ErrorMessage = "An unexpected error has occured in" + 
           "the application. If it continues, please contact the administrator.";
    }
    // TODO Log the exception somehow, either with
    // Microsoft.Practices.EnterpriseLibrary.Logging or some other mechanism
}

void Application_Error(object sender, EventArgs e) 
{
    // Code that runs when an unhandled error occurs

    //get reference to the source of the exception chain
    Exception lastError = Server.GetLastError();
    Exception ex;
    if (lastError.InnerException != null)
        ex = lastError.InnerException;
    else
        ex = lastError.GetBaseException();
    // TODO: Log the error somehow.
}

User Administration

Inside the Admin/Default.aspx page, there is a basic user administration piece that would allow someone with the Admin role to Approve/Unapprove, Unlock, and Add/Remove roles to users in the system.

Points of interest

Message are passed to the user via code-behind calls to:

  • base.InformationMessage = "My Information Message";
  • base.ErrorMessage = "My Error Message";
  • base.WarningMessage = "My Warning Message";

Although the "base." syntax is not necessary, I always place it so any future developer knows that some base page contains the definition for these properties and not the current page.

These message sections are initially invisible, and become visible when a string message passed to them (see BaseMasterPage.ErrorMessage for more details) sets EnableViewState = false, so they will disappear when the application does a postback.

The Master page utilizes the CodeFileBaseClass="BaseMasterPage" so the BaseMasterPage.cs file could expose the Labels and divs containing them via properties so a page could reference them.

<%@ Master Language="C#" AutoEventWireup="true" 
    Inherits="DefaultMaster" CodeFile="~/DefaultMaster.Master.cs"
    CodeFileBaseClass="BaseMasterPage" %>

The BasePage class hides the Page.Master property and casts the MasterPage as a BaseMasterPage so all a page has to reference is its ErrorMessage property.

public new BaseMasterPage Master { get { return (BaseMasterPage)base.Master; } }

public string ErrorMessage
{
  set { Master.ErrorMessage = value; }
}

Adding Just ASP.NET Membership and Roles Tables to a Database

Adding just the ASP.NET Membership tables to the database is easy to do, but requires you to use the command line of the aspnet_regsql.exe file. Look here for more information on using just the features you want for the ASP.NET membership.

History   

  • June 26th, 2009 - Initial post.
  • July 7th, 2009 - Added User Admin section

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Stephen Inglish
Software Developer (Senior) Harland Financial Solutions
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberFarhan Ghumra17 Jun '12 - 23:09 
Excellent
QuestionVisual Studi 2010memberMehdi Keramati8 Jul '11 - 14:02 
How can I use this template in Visual Studio 2010?
AnswerRe: Visual Studi 2010memberzwalton1 Sep '11 - 8:54 
I second that.
Generaldude great workmemberbheeem26 Jan '11 - 2:36 
Smile | :) Smile | :) Smile | :)
Questionhow can i protect the page from user without user in membership asp.net with c sharpmemberdesaihardikj@gmail.com9 Dec '10 - 14:09 
i am asp.net developer but membership is new for me i hv 60% knowledge of tht.<br>
 
now the problem is i wanted to protect the page form user without login<br>
 
ex. i hav made website with <br>
1) login.aspx <br>
2) logout.aspx<br>
3) inbox.aspx <br>
now without login user should not access inbox.aspx page
like <b>if user input page url in address bar then he should be redirect to login page if he is not logged in.</b>
<br>
Please if anybody know ? i am stuck into it. <br>
Thanks in advance Smile | :)
QuestionHaving a problem in web.configmemberdastarr18 Jun '10 - 15:00 
I am adding an additional page where it states:
 
<!-- Place any other pages here-->
<siteMapNode title="Pictures" url="Pictures.aspx" />
 
However, it does not add another button next to home and login when I navigate the the default.aspx page. Am I missing something?
 
Thanks in advance!
QuestionAdmin Account does not bring me to admin/default.aspx [modified]memberdastarr18 Jun '10 - 8:44 
When I click on the login button it will bring me to the login screen. I log in with admin credentials and it brings me right back to the default page that says place any details you want Anonymous and Logged in users to see here. I was expecting it to bring me to the admin/default.aspx page where I could manage user accounts. Any help on this issue would be greatly appreciated.
 
Thanks in advance!

modified on Friday, June 18, 2010 3:11 PM

GeneralMy vote of 1memberAndrey Mazoulnitsyn9 May '10 - 1:17 
bad
QuestionTemplatememberkhaksaraziz13 Apr '10 - 18:20 
I dint Understand very well kindly if you can explain in more easy way
GeneralThanksmemberthe_bg14 Feb '10 - 9:11 
Thanks for the contribution. This is a real time saver. I successfully converted this to VB as well.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 7 Jul 2009
Article Copyright 2009 by Stephen Inglish
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid