Nannette Thacker ShiningStar.net

ASP.net Web Application Development

Sponsors

News

See all Blog Posts by Nannette.

Nannette Thacker, consultant and owner of Shining Star Services LLC, specializes in development of custom dynamic database driven web applications utilizing ASP.net technologies. Nannette has been developing ASP sites since 1997. Nannette has written numerous articles on web development techniques and tutorials.

Nannette is the owner and developer of ChristianSinglesDating.com.

 Subscribe in a reader





View Nannette  Thacker's profile on LinkedIn

January 2012 - Posts

4 Year Anniversary Posting on Weblogs.Asp.Net!

On January 24th, 2012 I celebrate my 4th year of writing on this blog. I have written over 140 posts and have received over 700 comments.

Thank you readers for your support!

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn

ChangePassword Method for Entity Framework MVC3 Razor Custom Member Provider C# Using LINQ
From my C# MVC3 Razor Custom Membership Provider article and source code, here is the code for the ChangePassword method. I welcome any suggestions for improvement.
public override bool ChangePassword(string username, 
    string oldPassword, string newPassword)
{
    try
    {
        byte[] hashedNewPassword = HashPassword(newPassword.Trim());
        byte[] hashedOldPassword = HashPassword(oldPassword.Trim());
        using (var context = new SSSEntities())
        {
            UserProfile u = context.UserProfiles
            .SingleOrDefault(up => up.UserName == username && 
                up.UserPassword == hashedOldPassword);
            if (u != null)
            {
                u.UserPassword = hashedNewPassword;
                context.SaveChanges();
                return true;
            }
            else
                return false;
        }
    }
    catch (InvalidOperationException ex)
    {
        throw ex;
    }
    catch (ArgumentException)
    {
        throw;
    }
}

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
GetUser Methods for Entity Framework MVC3 Razor Custom Member Provider C# Using LINQ
From my C# MVC3 Razor Custom Membership Provider article and source code, here is the code for the GetUser methods. I welcome any suggestions for improvement.
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
    using (var context = new SSSEntities())
    {
        UserProfile u = context.UserProfiles
                    .SingleOrDefault(up => up.UserId == Convert.ToInt32(providerUserKey));
        MembershipUser membershipUser = GetMembershipUser(u);
        return membershipUser;
    }
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
    using (var context = new SSSEntities())
    {
        UserProfile u = context.UserProfiles
            .SingleOrDefault(up => up.UserName == username);
        MembershipUser membershipUser = GetMembershipUser(u);
        return membershipUser;
    }
}
// custom method to return a UserProfile
public UserProfile GetUser(string username)
{
    using (var context = new SSSEntities())
    {
        UserProfile u = context.UserProfiles
            .SingleOrDefault(up => up.UserName == username);
        return u;
    }
}
// custom method to return a UserProfile
public UserProfile GetUser(object providerUserKey)
{
    using (var context = new SSSEntities())
    {
        UserProfile u = context.UserProfiles
                    .SingleOrDefault(up => up.UserId == Convert.ToInt32(providerUserKey));
        return u;
    }
}


May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
Custom Error Pages and 404 Page Not Found Error Web.Config Setup

When receiving 404 page not found errors on your web site, and you wish to direct users back to your home page, you need to setup two things in your web.config to handle all instances.

If you use IIS7 and go to the Error Pages section and setup the 404 error to "Execute a URL on this site" and have it go to : /default.aspx and select OK to save the changes, it will update your system.webServer section of your web.config file and add these lines:

<httpErrors>
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" prefixLanguageFilePath="" 
path="/default.aspx"
responseMode="ExecuteURL" /> </httpErrors>

This will redirect any pages such as http://www.shiningstar.net/test with no file extensions. But if the URL sends the user to a page with a known file extension, they will still be taken to the 404 error page.

So if you want to redirect a page such as http://www.shiningstar.net/test.aspx you will also need to add custom error handling to your system.web section of your web configuration file:

<customErrors mode="RemoteOnly" 
defaultRedirect="~/ErrorPages/Error.aspx"> <error statusCode="404" redirect="~/default.aspx"/> </customErrors>


The 3 options for the mode are: Off, On, and RemoteOnly. To test your error handling locally, change the mode to "On." Once you've tested it, change it to "RemoteOnly" which will still allow you to receive descriptive errors when developing locally.

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn

CreateUser Method for Entity Framework MVC3 Razor Custom Member Provider C# Using LINQ
From my C# MVC3 Razor Custom Membership Provider article and source code, here is the code for the CreateUser method. I welcome any suggestions for improvement.
public override MembershipUser CreateUser(string username, string password,
    string email, string passwordQuestion, string passwordAnswer,
    bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
    // only first 3 fields are passed in from the AccountModels.cs
    try
    {
        status = UsernameExists(username);
        if (status == MembershipCreateStatus.DuplicateUserName)
        {
            return null;
        }
        status = DuplicateEmail(email);
        if (status == MembershipCreateStatus.DuplicateEmail)
        {
            return null;
        }

        byte[] hashedPassword = HashPassword(password.Trim());
        GetValues gv = new GetValues();
        string ipAddress = gv.getIPAddress();
        int userStatus = 
            Convert.ToInt32(SSS.GlobalListValues.Enums.UserStatusCode.Active);

        using (var context = new SSSEntities())
        {
            UserProfile newUser = new UserProfile()
            {
                Email = email,
                UserPassword = hashedPassword,
                UserName = username,
                DateCreated = DateTime.Now,
                DateUpdated = DateTime.Now,
                DatePasswordLastChanged = DateTime.Now,
                DateLastLogin = DateTime.Now,
                UserStatusCode = userStatus,
                IpAddress = ipAddress,
            };


            // insert the User Role
            int userRole = 
                Convert.ToInt32(SSS.GlobalListValues.Enums.UserRoleCode.User_Public);
            // look up the desired user role : 
            // uses a UserRole join table with a many to many relation
            // between the UserProfile table and the ListValue table
            ListValue ur = context.ListValues
                .SingleOrDefault(lv => lv.ListValueId == userRole);
            newUser.UserProfileUserRoles.Add(ur);

            context.UserProfiles.AddObject(newUser);
            context.SaveChanges();

            // NKT: after creation, go back and retrieve the auto-generated identity key and 
            // update the userId's for the created and updated userId
            int userId = newUser.UserId;
            newUser.CreatedUserId = userId;
            newUser.UpdatedUserId = userId;

            context.SaveChanges();
            status = MembershipCreateStatus.Success;
            return GetMembershipUser(newUser);
        }
    }
    catch (ArgumentException)
    {
        status = MembershipCreateStatus.ProviderError;
        return null;
    }

}

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
DeleteUser Method for Entity Framework MVC3 Razor Custom Member Provider C# Using LINQ
From my C# MVC3 Razor Custom Membership Provider article and source code, here is the code for the DeleteUser method. I welcome any suggestions for improvement.
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
    // deleteAllRelatedData not implemented
    try
    {
        using (var context = new SSSEntities())
        {

            UserProfile u = context.UserProfiles
                .SingleOrDefault(up => up.UserName == username);

            context.UserProfiles.DeleteObject(u);
            context.SaveChanges();
            return true;
        }
    }
    catch
    {
        return false;
    }


May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
UsernameExists & DuplicateEmail Helper Methods for Entity Framework MVC3 Razor Custom Member Provider C# Using LINQ
From my C# MVC3 Razor Custom Membership Provider article and source code, here is the code for the UsernameExists & DuplicateEmail Helper methods. I welcome any suggestions for improvement.
// helper method
public MembershipCreateStatus UsernameExists(string username)
{
    using (var context = new SSSEntities())
    {
        if (context.UserProfiles.Any(
                    u => u.UserName == username))
        {
            return MembershipCreateStatus.DuplicateUserName;
        }
        return MembershipCreateStatus.Success;
    }
}

// helper method
public MembershipCreateStatus DuplicateEmail(string email)
{
    using (var context = new SSSEntities())
    {
        if (context.UserProfiles.Any(
                    u => u.Email == email))
        {
            return MembershipCreateStatus.DuplicateEmail;
        }
        return MembershipCreateStatus.Success;
    }
}

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
GetMembershipUser Helper Method for Entity Framework MVC3 Razor Custom Member Provider C# Using LINQ
From my C# MVC3 Razor Custom Membership Provider article and source code, here is the code for the GetMembershipUser Helper method. I welcome any suggestions for improvement. Since we are working with a UserProfile Entity and the Membership Provider overridable methods require we return a MembershipUser type, below we create our MembershipUser type using values from our UserProfile type so we can return the required type in our methods.
// helper method
public MembershipUser GetMembershipUser(UserProfile u)
{
    // copy pertinent UserProfile data to the MembershipUser 
// data to be returned as a MembershipUser type object userIDObj = u.UserId; MembershipUser membershipUser = new MembershipUser( this.Name, u.UserName, userIDObj, u.Email, string.Empty, string.Empty, true, false, (DateTime)u.DateCreated, (DateTime)u.DateLastLogin, (DateTime)u.DateUpdated, (DateTime)u.DateLastLogin, (DateTime)u.DateLastLogin); return membershipUser; }

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
HashPassword Method for Entity Framework MVC3 Razor Custom Member Provider C# Using LINQ
From my C# MVC3 Razor Custom Membership Provider article and source code, here is the code for the HashPassword method. I welcome any suggestions for improvement.
// helper method
private byte[] HashPassword(string password)
{
    // NKT: This will only work with a new database, 
// otherwise existing passwords will be broken. // If you use this, be sure to set the saltvalue to your own
// customization in the web.config file in your web app // <add key="SaltValue" value="*!ShiningStar!*" /> // This won't work with an existing database, as they won't have the salt value // so make sure you alter the password hash or encryption as needed for an existing database... CryptoProvider crypto = new CryptoProvider(); byte[] hashedPassword = crypto.EncryptData(password.Trim()); return hashedPassword; } public static string GetSaltValue() { string saltValue = ConfigurationManager.AppSettings["SaltValue"]; return saltValue; } public byte[] EncryptData(string dataString) { // NKT: custom method using functionality from this article // http://www.4guysfromrolla.com/articles/103002-1.2.aspx // salting has value //http://www.4guysfromrolla.com/articles/112002-1.aspx // this isn't as secure as a unique salt per user, but if you use a unique salt per site,
//at least they won't know that salt value if they steal the
// database and not the web.config file // store the saltvalue in the web.config file. make unique per website. string saltedString = dataString + GetSaltValue(); MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); byte[] hashedDataBytes = null; UTF8Encoding encoder = new UTF8Encoding(); hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(saltedString)); return hashedDataBytes; }

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
ValidateUser Method for Entity Framework MVC3 Razor Custom Member Provider C# Using LINQ
From my C# MVC3 Razor Custom Membership Provider article and source code, here is the code for the ValidateUser method. I welcome any suggestions for improvement.
public override bool ValidateUser(string username, string password)
{
    // PasswordFormat = Hashed
    byte[] hashedPassword = HashPassword(password.Trim());
    // NKT: LINQ to Entities does not recognize 
    // the method 'Int32 ToInt32(System.Object)' method, 
    // and this method cannot be translated into a store expression.
    int userStatus = 
        Convert.ToInt32(SSS.GlobalListValues.Enums.UserStatusCode.Active);
    using (var context = new SSSEntities())
    {
        var query =
            from u in context.UserProfiles
            where u.UserName == username &&
            u.UserPassword == hashedPassword &&
                u.UserStatusCode == userStatus
            select u;

        bool isUserFound = false;
        foreach (var user in query.Take(1))
        {
            isUserFound = true;
        }
        return isUserFound;
    }
}

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
More Posts Next page »