Schema specified is not valid Membership.CreateUser - entity-framework

I've been tasked with migrating from our old half-baked user store (using encrypted passwords) to the default MS membership/role providers. I've done this in other projects no problem.
In this case, I have created the necessary tables using code-first with the 'new' .NET universal providers. I am simply trying to insert new records into the Users table, and have run into a wall.
I have a simple edmx with the 6 tables created by the membership provider. I have set up my web.config to point to the necessary cxn string & membership/role providers (code below).
Web.Config:
<connectionStrings>
<add name="Test" connectionString="metadata=res://*/Entities.Test.csdl|res://*/Entities.Test.ssdl|res://*/Entities.Test.msl;provider=System.Data.SqlClient;provider connection string="data source=[OurServer];initial catalog=[OurDb];integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider" connectionStringName="Test" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<add connectionStringName="Test" applicationName="/" name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider" />
</providers>
</roleManager>
Here is my "update passwords" function:
System.Web.Security.MembershipCreateStatus status = new System.Web.Security.MembershipCreateStatus();
//Get list of existing users, containing Username & encrypted PW
List<UserMigration.Models.Users> usersList = UserMigration.Models.Users.GetUsers();
foreach (var user in usersList)
{
string password = "";
//We have two encryption methods (bogus I know), so I attempt to decrypt with one, then another, using existing utility functions.
if (!EncryptDecrypt.TryDecryptTripleDES(user.Password, out password))
{
EncryptDecrypt.TryDecrypt(user.Password, out password);
}
//if we got a password, lets party
if (!string.IsNullOrEmpty(password))
{
System.Web.Security.Membership.CreateUser(user.Username, password,string.Empty,null,null,true,out status);
}
}
I'm getting an error on the CreateUser call, and I can't for the life of me figure out why. I haven't modified the Entities in any way. This should be dirt simple. The error is:
Schema specified is not valid. Errors:
The relationship 'TestModel.MembershipEntity_Application' was not loaded because the type 'TestModel.Membership' is not available.
The relationship 'TestModel.RoleEntity_Application' was not loaded because the type 'TestModel.Role' is not available.
The relationship 'TestModel.User_Application' was not loaded because the type 'TestModel.User' is not available.
The following information may be useful in resolving the previous error:
The required property 'Roles' does not exist on the type 'System.Web.Providers.Entities.User'.

Related

SQLite + EF6 "DeleteDatabase is not supported by the provider."

Before I begin, existing questions here and here do not solve my problem.
I am using SQLite with EF6, with package SQLite.CodeFirst used to generate my db schema as required. I am running unit tests on my repository class which uses the DBContext on the backend, but the database needs to be cleaned up before running each test such that subsequent tests are not corrupted.
My problem is that when I call dbContext.Database.Delete() I get the following exception:
System.Data.Entity.Core.ProviderIncompatibleException was unhandled by user code
Message=DeleteDatabase is not supported by the provider.
Source=EntityFramework
I want to avoid trying to having to discover the location of the database and deleting it from disk as the location varies depending on application. Has anybody got any suggestions?
Here are excerpts of relevant parts of my code:
App.config
<entityFramework>
<providers>
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6, Version=1.0.103.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<connectionStrings>
<add name="EngineDataContext_LocalDb" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=Engine.DataModel.EngineDataContext;MultipleActiveResultSets=True;Integrated Security=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<add name="EngineDataContext_SQLServer" connectionString="Data Source=.;Initial Catalog=Engine.DataModel.EngineDataContext;MultipleActiveResultSets=True;Integrated Security=True;" providerName="System.Data.SqlClient" />
<add name="EngineDataContext_SQLite" connectionString="Data Source=.\database.sqlite" providerName="System.Data.SQLite" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
Data context
public class EngineDataContext : DbContext
{
public EngineDataContext()
: base("name=EngineDataContext_SQLite")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var sqliteConnectionInitializer = new SqliteDropCreateDatabaseAlways<EngineDataContext>(modelBuilder);
Database.SetInitializer(sqliteConnectionInitializer);
}
}
Repository
public class SqliteRepository
{
private readonly EngineDataContext _dataContext;
public SqliteRepository(EngineDataContext dataContext)
{
_dataContext = dataContext;
}
public void DropCreateDatabase()
{
_dataContext.Database.Delete(); // FAIL
_dataContext.Database.Create();
}
}
It means that the System.data.Sqlite EF provider does not implement the Deletedatabase method (part of Migrations, which is not implemented either). The Devart provider (not free) adds proper support: https://www.devart.com/dotconnect/sqlite/features.html#ef

Exception while deploying ASP.NET Website after Using EF

I have two projects, one containing WS which access to the DB and the other one is front-end.
The two projects are deployed on seperate servers.
Before Using EF and linq for accessing the DB in the WS project, everything was working fine, but after that I got and exception saying "the underlying provider failed on open".
Please ca you help me with that. Thank you in advance.
Here is my ConnectionString (WS Project):
<connectionStrings>
-->
<add name="ConString1" connectionString="Data Source=#address,1433;Initial Catalog = MpCarteCoBrandee;MultipleActiveResultSets=True;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
<!--<add name="ConString" connectionString="Data Source=AOUS-PC;Initial Catalog=TestMobilePayment;Integrated Security=SSPI" providerName="System.Data.SqlClient" />-->
<add name="MobilePaymentEntities" connectionString="metadata=res://*/MobilePayment.csdl|res://*/MobilePayment.ssdl|res://*/MobilePayment.msl;provider=System.Data.SqlClient;provider connection string="data source=#address,1433;initial catalog=MobilePayment;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

ldap authentication using ActiveDirectyoryMembershipProvider on GC port fails in MVC2 application

I am developing an MVC2 application using C# ASP.NET.
In my application I am using ActiveDirectoryMembershipProvider for user authentication. Below is the snippet from my web.config file.
If I use the global catalog port 3268 in my connection string I get the error "LDAP connections on GC port are not supported against Active Directory". I did google on this error message and was unable to find an appropriate solution. Many people have suggested using port 389, some have suggested code changes. But I want to be able to use the GC port to allow users connected to different forests, because it is more cleaner.
Some observations:
The same connection string(with port 3268) is working perfectly for other applications in my company i.
When I change my connection string to point to port 389 it works perfectly i.e people who belong to the local domain are able to log in. However people from another domain cant.
I put breakpoints in my AcconuntModel and AccountController. With connection string pointing to port 3268,Membership.Provider threw "ConfigurationErrorsException".
It would be very helpful if someone can help me resolve this issue.
web.config:
<add name="ADConnectionString" connectionString="LDAP://myADServer.abc.ad:389/DC=abc,DC=ad" />
<membership defaultProvider="MyADMembershipProvider">
<providers>
<clear />
<add connectionStringName="ADConnectionString" maxInvalidPasswordAttempts="1000" connectionUsername="ldapuser#abc.ad" connectionPassword="password" connectionProtection="None" enableSearchMethods="True" name="MyADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="MySqlMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider,MySql.Web,Version=6.5.4.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d" connectionStringName="MySqlMembershipConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" autogenerateschema="true" />
</providers>
</membership>
<!-- Added for custom provider -->
<roleManager enabled="true" cacheRolesInCookie="true" defaultProvider="DDMS_Custom_RoleProvider">
<providers>
<clear />
<add applicationName="/" connectionStringName="ddms_dataEntities2" name="DDMS_Custom_RoleProvider" type="DDMS_sourcecode.Utilities.DDMS_Custom_RoleProvider, DDMS_sourcecode" />
<add connectionStringName="ApplicationServices" applicationName="/" autogenerateschema="true" name="MySqlRoleProvider" type="MySql.Web.Security.MySQLRoleProvider,MySql.Web,Version=6.5.4.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d" />
</providers>
</roleManager>
If it is Global Catalog that you need to search, why dont you try it this way
using (DirectoryEntry searchRoot = new DirectoryEntry("GC://DC=yourdomain,DC=com"))
using (DirectorySearcher ds = new DirectorySearcher(searchRoot))
{
ds.Filter = "(sAMAccountName=userID1)";
ds.SearchScope = SearchScope.Subtree;
using (SearchResultCollection src = ds.FindAll())
{
foreach (SearchResult sr in src)
{
uxFred.Content = sr.Path;
}
}
}

EF4 The provider did not return a Provider Manifest Token string

Yes, one more question about Provider manifest token. Unfortunately all previous 22 questions was not useful to solve my problem. I developing simple web application using MVC4 + Code First + Sql Express.
Here is my context descendant:
public class MCQContext : DbContext
{
public MCQContext()
: base("name=ApplicationConnection")
{
}
...............
}
And here - part of web.config related to the problem:
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ApplicationConnection"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="name=ApplicationConnection" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
So, as you can see, correct connection string passed to base of context class (I got the same error if I rename connection string to "MCQContext" and do not pass anything to parent context class).
I have no idea how to fix it. This behavior reproduced if I creating absolutely empty MVC4 application, remove all packages (I prefer manually specify required assemblies and do not use NuGet) and fix references (including reference to sqlserver express).
The problem with your connection string here is:
<add name="TrempimModel"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.sdf;
User Instance=true"
providerName="System.Data.SqlClient" />
You're basically defining what "server" you're connecting to - but you're not saying what database inside the file to connect to. Also - the file extension for SQL Server Express database files is .mdf (not .sdf - that's SQL Server Compact Edition) - you need to take that into account, too! (was a typo, according to comment by OP).
You need to define an extra database=.... (or Initial Catalog=.....) in your connection string:
<add name="TrempimModel"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
database=YourDatabaseName;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
Then it should work just fine.

ASP.NET MVC2 Authentication form with localization

I have two level authentification, first the user enters their nt/password and it is validated by LDAP and afterward I have a custom role provider that make sure the user has access to said page.
That being said, in my web.config I have:
<authentication mode="Forms">
<forms loginUrl="~/Account.mvc/LogOn" timeout="2880"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<membership defaultProvider="ADMembershipProvider">
<providers>
<add connectionStringName="ADConnString"
name="ADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
attributeMapUsername="sAMAccountName"
enableSearchMethods="false"
applicationName="ProgramName"/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear />
<add name="CustomRoleProvider"
applicationName="ProgramName"
type="ProgramName.Providers.CustomRoleProvider"
attributeMapUsername="sAMAccountName"
/>
</providers>
</roleManager>
Now, If I try to use the language button while in the login form, it calls an action that is unavailable since the user still isn't LDAP-Authenticated. My question is:
Can I avoid the membership check for specific action like I can for role check using the [Authorize] Attribute?
I tried using:
<location path="~/Home.mvc/ChangeCulture">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
And this doesn't work. The action ChangeCulture is never called.
This answer:
ASP.NET MVC Forms authentication and unauthenticated controller actions
shows how to do it for roles, any idea for membership+roles?
Thanks.