holyprin / Holyprin.Web.Security

ASP.NET Code-First Membership Provider with basic model abstraction
12 stars 3 forks source link

AddUsersToRoles fails #2

Closed Devristo closed 12 years ago

Devristo commented 12 years ago

Exception: Cannot perform runtime binding on a null reference Stacktrace: at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.BindProperty(DynamicMetaObjectBinder payload, ArgumentObject argument, LocalVariableSymbol local, EXPR optionalIndexerArguments, Boolean fEventsPermitted)

On line 45 of RoleProvider.cs: dynRole.Users = new List();

It seems that the error is triggered because dynRole is null (as initialized a few lines above). I don't think its because my configuration, but if needed I can post my web.config.

Devristo commented 12 years ago

If i change the function to the following it works for me. Not sure if this was the intended code:

public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            //Thread Safety
            DbContext DataContext = (DbContext)Activator.CreateInstance(CFMembershipSettings.DataContext);
            DbSet Users = DataContext.Set(CFMembershipSettings.UserType), Roles = DataContext.Set(CFMembershipSettings.RoleType);

            try
            {
                foreach (string roleStr in roleNames)
                {
                    dynamic dynRole = null;
                    dynamic role = Roles.SqlQuery(q("SELECT * FROM $Roles WHERE Name = '{0}'", roleStr)).Cast<dynamic>().FirstOrDefault();

                    if (role != null)
                    {
                        //dynRole.Users = new List<dynamic>();
                        foreach (string userStr in usernames)
                        {
                            //dynamic dynUser = null;
                            dynamic user = Users.SqlQuery(q("SELECT * FROM $Users WHERE Username = '{0}'", userStr)).Cast<dynamic>().FirstOrDefault();

                            if (user != null)
                                if (!role.Users.Contains(user))
                                    role.Users.Add(user);
                        }
                    }
                }

                DataContext.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }

            DataContext.Dispose();
        }
holyprin commented 12 years ago

Thanks for pointing that out, I just fixed the code, will update in the next few minutes.