I am creating unit tests for my website base on Unit framework. In my unit test, I need to create a MembersMembershipProvider of Umbraco, but it threw null exception:
System.NullReferenceException : Object reference not set to an instance of an object.
at Umbraco.Web.Security.Providers.MembersMembershipProvider..ctor()
at Tests.Controllers.MemberControllerTests.Test_ValidateUser() in
This is my unit test:
[TestFixture]
public class Test_ProxyMembershipProvider
{
[Test]
public void Test_ValidateUser()
{
var s = new MembersMembershipProvider();
}
}
What should I fix or I missed something? Any help are highly appreciate!
Cheer!
The null reference occurs because the MembersMembershipProvider uses IMembershipMemberService in the constructor. If you use the constructor without parameters it will try to get the IMembershipMemberService from the ApplicationContext (which is null since you're running unittests). You can add a mocked version of this service to the constructor parameters:
var mServiceMock = new Mock<IMembershipMemberService>();
var s = new MembersMembershipProvider(mServiceMock.Object);
For more implementation details of MembersMembershipProvider check out the github sourcecode
I recently had the same issue. I was able to resolve the problem by adding an app.config file to my test project.
Within the app.config file, you will need the system.web/membership section. You also need a connectionStrings section, if you are using a Sql provider.
<configuration>
<connectionStrings>
<add name="MyDataBase"
connectionString="data source=localhost;Integrated Security=SSPI;Initial Catalog=MyDataBase"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<membership defaultProvider="UnitTestSqlMembershipProvider">
<providers>
<clear/>
<add
name="UnitTestSqlMembershipProvider"
type="Membership.Unit.Provider.UuuSqlMembershipProvider, Membership.Unit.Provider, Version=1.0.0.0, Culture=neutral"
connectionStringName="MyDataBase"
applicationName="mylittleapp"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="3"
passwordAttemptWindow="10"
minRequiredPasswordLength="8"
minRequiredNonalphanumericCharacters="0" />
</providers>
</membership>
</system.web>
</configuration>
Additionally, if you want to Mock your provider, then you can create an interface for your custom provider
eg Mock _mbrInfrastructe = new Mock();
at this point you can lean on obj.Setup calls to add additional control over unit tests.
I wanted to build a membership system at the beginning of my MVC project and I used Membership.ValidateUser method to verify credentials. However I could not understand how does this method access my database and check my email and password informations.
[HttpPost]
[ActionName("Login")]
public ActionResult Login(LoginModel loginModel)
{
if (Membership.ValidateUser(loginModel.Email, loginModel.Password))
{
FormsAuthentication.SetAuthCookie(loginModel.Email, true);
return Json(true);
}
return new JsonNetResult()
{ Data = new { Error = true, Messages = new[] { new { Message = "Wrong username or password" } } } };
}
It' used the MembershipProvider specified on your Web.config file to validate the user. By default, it uses DefaultMembershipProvider
Membership.ValidateUser method at first check membership defaultProvider in your web.config file which matches with name that you provide like below:
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider"
connectionStringName="Context" applicationName="myapp"
enablePasswordRetrieval="false" enablePasswordReset="true"
requiresQuestionAndAnswer="false" requiresUniqueEmail="true"
passwordFormat="Hashed" minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="0" />
</providers>
</membership>
Above configuration will call .net framework abstraction class MembershipProvider -> ValidateUser (abstract method) which implementation lies in SqlMembershipProvider -> ValidateUser method that you have configured in your web.config file [like above].In that method it simply call two store procedures of your database , first one is aspnet_Membership_GetPasswordWithFormat which check your application name, username , last login activity date and current time and based on that makes you authenticate and secondly call to other store procedure which name is aspnet_Membership_UpdateUserInfo which is self explanatory as you realize which update aspnet_membership table with columns like islockedout, lastlockoutdate, failedpasswordattemptcount.. etc.
Hope this helps you.
I am going to use the default built in membership provider in my app. If the first provider does not validate the user then I want to try to validate the user against another provider.
I have my secondary provider set up in my web.config like this:
<membership>
<providers>
<add name="SecondaryMemberShipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Version 4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
enableSearchMethods="true"
connectionUserName="MyDoman\user"
connectionPassword ="password"
connectionStringName ="ADConnectionString" />
</providers>
</membership>
I added a class "SecondaryMemberShipProvider" that inherits from MembershipProvider. I am unsure of how I code the ValidateUser method on my new class.
I am using C# MVC using .NET 4.0
I am trying to implement the ASP.NET Profile Properties seen at
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
First, I added the following in my web.config file. Note that I am trying to store the Location for a given user:
<profile>
<properties>
<add name="Location" />
</properties>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
Within my code, I used the following:
After I post, I used the following my in controller:
Profile.Location = model.Location;
I am getting an error, Cannot resolve 'Profile'. Has anybody used the Profile Property that can offer any assistance? Note that I wasn't even able to find the class that is mentioned in the article.
Thanks
A profile would have to belong to a User/Member so you would have to load or create a new User before adding any profile properties to it.
See this SO post on a similar question
Got the following ProviderException :
The Role Manager feature has not been enabled.
So far so good.
Is there somewhere a method that can be called to check if the Role Manager has been enabled or not?
You can do this by reading from the boolean property at:
System.Web.Security.Roles.Enabled
This is a direct read from the enabled attribute of the roleManager element in the web.config:
<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>
Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx
If you got here because you're using the new ASP.NET Identity UserManager, what you're actually looking for is the RoleManager:
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
roleManager will give you access to see if the role exists, create, etc, plus it is created for the UserManager
I found 2 suggestions elsewhere via Google that suggested a) making sure your db connectionstring (the one that Roles is using) is correct and that the key to it is spelled correctly, and b) that the Enabled flag on RoleManager is set to true. Hope one of those helps. It did for me.
Did you try checking Roles.Enabled? Also, you can check Roles.Providers to see how many providers are available and you can check the Roles.Provider for the default provider. If it is null then there isn't one.
I found this question due the exception mentioned in it. My Web.Config didn't have any <roleManager> tag. I realized that even if I added it (as Infotekka suggested), it ended up in a Database exception. After following the suggestions in the other answers in here, none fully solved the problem.
Since these Web.Config tags can be automatically generated, it felt wrong to solve it by manually adding them. If you are in a similar case, undo all the changes you made to Web.Config and in Visual Studio:
Press Ctrl+Q, type nuget and click on "Manage NuGet Packages";
Press Ctrl+E, type providers and in the list it should show up "Microsoft ASP.NET Universal Providers Core Libraries" and "Microsoft ASP.NET Universal Providers for LocalDB" (both created by Microsoft);
Click on the Install button in both of them and close the NuGet window;
Check your Web.config and now you should have at least one <providers> tag inside Profile, Membership, SessionState tags and also inside the new RoleManager tag, like this:
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=NUMBER" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
Add enabled="true" like so:
<roleManager defaultProvider="DefaultRoleProvider" enabled="true">
Press F6 to Build and now it should be OK to proceed to a database update without having that exception:
Press Ctrl+Q, type manager, click on "Package Manager Console";
Type update-database -verbose and the Seed method will run just fine (if you haven't messed elsewhere) and create a few tables in your Database;
Press Ctrl+W+L to open the Server Explorer and you should be able to check in Data Connections > DefaultConnection > Tables the Roles and UsersInRoles tables among the newly created tables!
If you are using ASP.NET Identity UserManager you can get it like this as well:
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roles = userManager.GetRoles(User.Identity.GetUserId());
If you have changed key for user from Guid to Int for example use this code:
var roles = userManager.GetRoles(User.Identity.GetUserId<int>());
<roleManager
enabled="true"
cacheRolesInCookie="false"
cookieName=".ASPXROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
defaultProvider="AspNetSqlRoleProvider"
createPersistentCookie="false"
maxCachedResults="25">
<providers>
<clear />
<add
connectionStringName="MembershipConnection"
applicationName="Mvc3"
name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add
applicationName="Mvc3"
name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
Here is the code that you need to put in your Account Controller in MVC5 and later
to get the list of roles of a user:
csharp
public async Task<ActionResult> RoleAdd(string UserID)
{
return View(await
UserManager.GetRolesAsync(UserID)).OrderBy(s => s).ToList());
}
There is no need to use Roles.GetRolesForUser() and enable the Role Manager Feature.