Roles.CreateRole() creates a new database inside App_Data - asp.net

What could be the reason for Roles.CreateRole("admin") creating a new local database inside App_Data, if my default membership provider is set to use a connection to an actual SQL Server?
I have a connection string like this:
<connectionStrings>
<add name="MembershipDbConnection"
connectionString="Server=.;Initial Catalog=aspnetdb;User Id=*;Password=*" />
</connectionStrings>
and a membership provider defined like this:
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MembershipDbConnection" <-- this is the connection
/>
</providers>
</membership>
The weird thing is, there is an aspnetdb database (populated with tables) in my SQL Server, and if I use Membership.GetAllUsers(), I get the users in that table without problems. Login also works as expected. But Roles.CreateRole creates a new database.

You need to configure the Role manager section if you want to use roles. It is likely you are picking up the inherited RoleManager section that is using a different connection string.

I think you didn't supply "applicationName" attribute in "membership" and "roleManager" tags in Web.Config. Here is an example: -
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MembershipDbConnection" applicationName="/" />
</providers>
</membership>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="MembershipDbConnection" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>

Mansoor Gee's answer provides an excellent template to follow.
Here's a link to documentation of what, and how, should be implemented in the web.config to enable RoleManager:
http://msdn.microsoft.com/en-us/library/vstudio/ms164660(v=vs.100).aspx
Hopefully this will add some context to future readers, as I needed some when I first came across this answer.

Related

ASP.Net Membership Error CREATE DATABASE failed. Some file names listed could not be created. Check related errors

I am trying to add AP.Net membership to my database. I have had success with this in the past so I have some idea of what I am doing. My project is a VB.Net website with Framework 4.5.2. I used asp_regsql.exe in framework 4 to add the schema to my db. I created the following web.config entries (per MSDN articles):
<connectionStrings>
<add name="AFKMSConnectionString" providerName="System.Data.SqlClient" connectionString="working as intended" />
<system.web>
<authentication mode="Forms" >
<forms loginUrl="Account/Login.aspx"
name=".ASPXFORMSAUTH" />
</authentication>
<!--<authorization>
<deny users="?" />
</authorization>-->
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<pages>
<namespaces>
<add namespace="System.Web.Optimization"/>
<add namespace="Microsoft.AspNet.Identity"/>
</namespaces>
<controls>
<add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/>
</controls>
</pages>
<membership defaultProvider="SqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add
name="SqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="AFKMSConnectionString"
applicationName="AFKMS"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
<profile enabled ="true" defaultProvider="SqlProvider">
<providers>
<clear />
<add name="SqlProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="AFKMSConnectionString"
applicationName="AFKMS"
description="SqlProfileProvider for SampleApplication" />
</providers>
</profile>
<roleManager enabled ="true"
defaultProvider ="SqlRoleProvider" >
<providers>
<clear/>
<add name ="SqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="AFKMSConnectionString"
applicationName="AFKMS"/>
</providers>
</roleManager>
My connection string works for my current functions but when I try to register a user I get the following error:
Directory lookup for the file "C:\Users\Dan\Source\Repos\AFKMS\AFKMS\App_Data\aspnet-AFKMS-140073d4-6858-4f19-9555-0edfbaadd43a.mdf" failed with the operating system error 2(The system cannot find the file specified.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
This comes from Accounts/Register,
Dim result = manager.Create(user, Password.Text)
Why is it trying to create a database? What does it look like I am missing?
<connectionStrings>
<add name="AFKMSConnectionString" connectionString="data source=.;Initial Catalog=your_db_name;integrated security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
can you provide us with code of how you create users?
you mentioned: Dim result = manager.Create(user, Password.Text)
i think you need to use:
Membership.CreateUser(UserName, Password, Email)
I'm assuming you've created a new ASP.NET Web Application, using the Web Forms templates?
In which case you appear to be attempting to configure the newer ASP.NET Identity system with the original Membership Provider configuration settings.
As Ahmed noted, you mention the call in the register page to manager.Create(user, Password.Text) - this is using the ApplicationUserManager from ASP.NET Identity.
If you look in the App_Start folder of your project, you should find a file named IdentityConfig.vb (assuming you're using VB.NET), which has a method Create that returns the ApplicationUserManager - this in turn calls the ApplicationDbContext class that is created in the Models folder, that will be defined to use a connection called "DefaultConnection" - by default this is set to be a standalone .mdf file in the App_Data folder named after the project.
You should change this to point at your connection string, but be aware that this uses Entity Framework to create the database schema for you - it should just add it to the existing database, but you should ensure you've backed it up before you start in case it drops everything first.

System.Configuration.Provider.ProviderException: The role 'user' was not found

I'm a bit out of my depth with this so if anyone can help I would be so grateful. I have a website written using asp.net/VB with SQL for the database. On that server and wanted to duplicate it to be able to change it and turn it into a different site. My developer set me up a new database and copied necessary sql files across. When trying to register a new account I get the error: System.Configuration.Provider.ProviderException: The role 'user' was not found but sometimes the site says the email address I'm trying to register already exists.. The database is empty though so I think I have something wrong in my WebConfig file where it's probably trying to connect to the old database ? I have copied the webconfig from that site too and simply renamed the "application Name=" parts.. Below shows the database and then the webconfig. Thank you so much for any help at all.
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/login.aspx" name="freebeeAuth1" slidingExpiration="true" timeout="259200" defaultUrl="~/default.aspx" domain=".freebeepoints.com" path="/" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MembershipConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" maxInvalidPasswordAttempts="10" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/freebee" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="MembershipConnectionString" applicationName="/freebee" />
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="MembershipConnectionString" applicationName="/freebee" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/freebee" />
</providers>
</roleManager>
If you copy over your website to a new location to have a copy of the same website, you should not change the ApplicationName in the asp.net membership stuff. Just change the connectionstring to make sure you're connecting to the right db.
Also make sure you're keeping the same machinekey element.
Hope this helps...

Problems with NauckIT.PostgreSQLProvider

I have a problem with AspSQL Provider for PostgreSQL (http://dev.nauck-it.de/projects/aspsqlprovider).
When I try to create Roles with the ASP.NET Web Site Administration Tool this message keeps coming up:
There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store.
The following message may help in diagnosing the problem: exePath must be specified when not running inside a stand alone exe. (D:\Documents\Programming\Projects\Portal\web.config line 40)
Here is the web.config section:
<membership defaultProvider="PgMembershipProvider">
<providers>
<clear />
<add name="PgMembershipProvider" type="NauckIT.PostgreSQLProvider.PgMembershipProvider" connectionStringName="db" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="bp" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="PgRoleProvider" cacheRolesInCookie="true" cookieName=".AspNetRoles" cookiePath="/" cookieProtection="All" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieTimeout="30" maxCachedResults="25">
<providers>
<clear />
<add name="PgRoleProvider" type="NauckIT.PostgreSQLProvider.PgRoleProvider" connectionStringName="db" applicationName="bp" />
</providers>
</roleManager>
<profile enabled="true" defaultProvider="PgProfileProvider">
<providers>
<clear />
<add name="PgProfileProvider" type="NauckIT.PostgreSQLProvider.PgProfileProvider" connectionStringName="db" applicationName="bp" />
</providers>
<properties>
<add name="FirstName" />
<add name="LastName" />
</properties>
</profile>
<sessionState mode="Custom" customProvider="PgSessionStateStoreProvider">
<providers>
<clear />
<add name="PgSessionStateStoreProvider" type="NauckIT.PostgreSQLProvider.PgSessionStateStoreProvider" enableExpiredSessionAutoDeletion="true" expiredSessionAutoDeletionInterval="60000" enableSessionExpireCallback="false" connectionStringName="db" applicationName="bp" />
</providers>
</sessionState>
I followed the instruction Step By Step
Thanks in advance
Seems like HttpContext.Current can be null. The PgMembershipProvider class checks this to see if its hosted or not. Based on the answer, it attempts to either OpenExeConfiguration (for stand-alone) or OpenWebConfiguration for web hosted applications.
Since HttpContext.Current can be null sometimes in Asp.Net 4.0, the wrong decision is made and the OpenExeConfiguration is called from within a webapplication (big no-no). The fix is to change PgMembershipProvider.Init to use the following check:
Configuration cfg = HostingEnvironment.IsHosted ?
WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath) :
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
instead of the HttpContext.Current != null check.
this bug was fixed in the 2.0.0 Version of the Provider.
See http://dev.nauck-it.de/issues/131
You can download the latest release via NuGet: https://nuget.org/packages/NauckIT.PostgreSQLProvider/

how to change ASP.NET Configuration tool connection string

how can I change ASP.NET Configuration tool-s connection string name?
(Which connection string will ASP.NET Configuration tool will use)
I'm learning ASP.NET and everywhere and in book that I'm reading now theres connection string named: LocalSqlServer.
I want to use my local sql server database instead of sql express to store Roles, Membership and other data.
I have used aspnet_regsql.exe to create needed data structures in my database. after that I changed my web.config to look like:
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Server=(LOCAL); Database=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
but when I run ASP.NET Configuration tool it says that:
"The connection name 'ApplicationServices' was not found in the applications configuration or the connection string is empty."
ASP.NET Configuration tool uses connection string named: ApplicationServices not LocalSqlServer.
cause of that I have to modify web.config to:
<connectionStrings>
<add name="ApplicationServices" connectionString="Server=(LOCAL); Database=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
and everything works fine.
I wish to know why the hell my web site uses connection string named: ApplicationServices and all books and online documentations uses LocalSqlServer? and how to change it to LocalSqlServer?
I have:
Windows 7
Sql Server 2008 R2
Visual Studio 2010 Premium
Project type is website
accidentally I have found my question answer when looking to web.config file.
if you override default machine.config configuration settings in web.config file you can change ASP.NET Configuration tool-s connection string name.
I got my web.config file from book-s code archive and it was the problem.
in web.config u can override which connection string name will be used for: membership, profile and roleManager.
to override membership use:
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/"/>
</providers>
</membership>
where connectionStringName is the name of connection string which will be used for storing membership data.
others are:
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="LocalSqlServer"
applicationName="/"/>
</providers>
</profile>
and
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="LocalSqlServer" applicationName="/"
name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>

ASPNETDB and ASPSTATE database. How to change the connectionstrings?

I have two ASP-specific SQL Server databases
1) ASPState - To store session state
2) ASPNETDB - To store Security/Role stuff.
In my web.config, I am specifying the connection string used to identify the location of the APState database:
<sessionState mode="SQLServer" sqlConnectionString="server=(local)\sql2008b;uid=sa;pwd=iainttelling;" timeout="120"/>
Where is the conenction string specified for the ASPNETDB database? I am trying to point it to a db on a remote server.
I have a feeling it is somewhere in IIS orthe Machine Config. I'd like to add it to my WEB.CONFIG Could someone help me to do this?
Define a connection string in connectionStrings section and then override role/membership settings like this:
<system.web>
<roleManager enabled="true" defaultProvider="SqlRoleManager">
<providers>
<add
name="SqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="DefaultSqlConnection"
applicationName="myApp" />
</providers>
</roleManager>
<membership defaultProvider="SqlMembershipManager" >
<providers>
<clear />
<add
name="SqlMembershipManager"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="DefaultSqlConnection"
applicationName="myApp"
passwordFormat="Hashed" />
</providers>
</membership>
Check this article

Resources