Archives

Archives / 2012 / January
  • 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;
        }
    }

    [SIGNATURE]

  • 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;
        }
    }
    
    

    [SIGNATURE]

  • 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;
        }
    
    }

    [SIGNATURE]

  • 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;
        }
    
    

    [SIGNATURE]

  • 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;
        }
    }
    

    [SIGNATURE]

  • 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; }

    [SIGNATURE]

  • 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; }

    [SIGNATURE]

  • 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;
        }
    }
    

    [SIGNATURE]

  • C# MVC3 Razor Entity Framework & LINQ Custom Membership Provider with Custom Role Provider

    This C# project demonstrates how to create an MVC3 Razor Entity Framework & LINQ Custom Membership Provider with Custom Role Provider. Perhaps you are working with a legacy database or you prefer working with a database that uses numeric identity keys instead of Guids. The example UserProfile table in this project uses an integer UserId as the primary key and various other fields that aren't in the default ASP.NET User table. Use the Log On Link in the project and the Register link to create your own account.

  • C# Custom LinkedList Main() method - Learning C# - Part 7



    When we create a console application, our Program class and Main() method are setup by default. Our Main() method is defined as a static method. The "static" keyword instructs the system to create only one instance of the method regardless of how many instances of its class are created.

    In our Main() method, we create a new LinkedList and name it ListItems. Rather than using this to create nodes, as we did with the Head and Next nodes which were also LinkedLists, we are going to use this to call the methods defined in the LinkedList class. When we type "ListItems." intellisense will kick in and display all public methods defined in our LinkedList class. Now we can use this to Push() inventory items to our list, PrintFifo() or PrintLifo(), PopFifo() or PopLifo(), and FindItems(). We want to follow up with Console.ReadLine(); to keep the text from zooping off the screen and returning to the program. Console.ReadLine(); will allows us to stop and wait for input, thus allowing us to see our results.




    In our example above, we print our items in LIFO order, then we remove the top and bottom nodes, then print our remaining items in FIFO order. Then we search for items in the "Electronics" category and display them to the screen. Play around with it, put in break points and step through the code and see what is happening.

  • C# Custom LinkedList FindItems() method - Learning C# - Part 6



    In this "for" loop, we start with the Head node, and as long as the node is not null, we loop through the nodes, reassigning our current node to the node as stored in the "Next" node. As we loop through the nodes, we see if the value of the item or category match the search criteria, and if so, we print the node values to the screen. If an item is found, we set the boolSuccess value to true and at the end of the method, we pass this back to the calling method.

    In our next article, we will look at our Main() program and how to use our new LinkedList class.

  • C# Custom LinkedList PrintFifo method and GetNode by Position - Learning C# - Part 5



    Now we are ready to use the GetNode() method in our PrintFifo() method to print our list in "first in first out" order. Again, we use a "for" loop to loop through the nodes beginning with the node at the bottom of the stack -- the one in our linked list "size." We create a new node and assign it to the value returned from GetNode(i).

    We then utilize the Console.WriteLine() method to print our values to the screen. Utilizing {0} {1} etc. allows us to leave a placeholder for the values following the string you want printed. In our example, the category name retrieved from the node.Category() method will print in the {0} position and the value retrieved from the node.Item() method wil print in the {1} position.

    In our next article, we will create a FindItems() method which will print a listing to the screen of all items based on the category or item name.

  • C# Custom LinkedList Derived Classes, Constructor Initializations - Learning C# - Part 2



    We create two self-referencing members, meaning the type is the same name as their class: "private LinkedList Head" and "private LinkedList Next". The first points to the most recent node added to the list or the top of the stack. The second points to the next node on the list that was just previously added so that we can traverse through the list. Once we traverse to the next node, it again has its own Next node, to point to the previous node, and so forth.

    The "private int size" statement defines an integer used to keep track of how many records are in the list.

    Next we define our constructor: "public LinkedList()." "Constructors: are class methods that are executed when an object of a class or struct is created. They have the same name as the class or struct, and usually initialize the data members of the new object."

    True to our definition, we initialize the Head and Next to null. We set our inventoryCategory to empty using "string.Empty." We could have just as easily set our inventoryCategory to empty by assigning it a value of "" (2 quote marks).

    We set our size to 0. Our list will be 1 based and increment to 1 when the first node is added.

    In Part 3 of our series, we will define our Push and Pop methods.

  • C# Custom LinkedList Console Application and Abstract Base Class and Method - Learning C# - Part 1


    One of the key concepts of object oriented programming is Inheritance along with Abstraction. Inheritance allows you to create a class that allows you to reuse behaviors and definitions.

    We first want to create a base class, Inventory. That means that it is a parent class. To make the Inventory class a base class, we use the keyword "abstract." This means any abstract methods defined in the base class must be implemented in the inherited or derived class. If you do not wish to require implementation, use the "virtual" keyword which means that the derived class "can" override the method with its own implementation, but does not have to.

    In our above example, we have an abstract method "Category" and an implemented string and method: inventoryItem and Item(). Notice we do not define an implementation for the Category() method. The implementation must be defined by the derived class.

    Our linked list will use the Item() and Category() for retrieving our Inventory item names.

    In Part 2 of our series, we will setup our LinkedList derived class and define our properties and setup our constructor.