ASP.NET membership using SQL Server - sql-server

I am trying to create an MVC 3 app using asp.net membership in a sql server database. I want to be able to use the Entity Framework for development on this app.
I have created by database and used the aspnet_regsql utility to add the membership tables to the database. The part I'm stuck on is how to connect to this database using my application.
I have added an entity model to the project which generated a new connection string in the web.config and I have tried changing the connectionStringName property on all the membership related entries to the new string like so:
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="BlogV1Entities" applicationName="/" />
but this is not working as I am getting errors when trying to create a user through the app or ASP.NET Configuration utility
An error occurred while attempting to initialize a System.Data.SqlClient.SqlConnection object. The value that was provided for the connection string may be wrong, or it may contain an invalid syntax. Parameter name: connectionString
Can anyone point me in the right direction to properly get this setup so my app can access the database?
EDIT: In response to first comment this is what the connection string looks like this:
connectionString="metadata=res://*/BlogV1Model.csdl|res://*/BlogV1Model.ssdl|res://*/BlogV1Model.msl;provider=System.Data.SqlClient;provider connection string="data source=jesse-laptop;initial catalog=BlogV1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

the entity framework connection string won't work when using asp.net membership. I have dont in my project like this;
i-e You need separate connection string for that;
your membership connection string;
<add name="DAConnection" connectionString="Data Source=.\sqlexpress;initial catalog=E:\MYWORK\DIGITALASSETSMVC3\DAMVC3\APP_DATA\DAMVC3.MDF;integrated security=True" providerName="Syste.Data.SqlClient" />
you entity framework connection string;
<add name="DAEntities" connectionString="metadata=res://*/Models.DAModel.csdl|res://*/Models.DAModel.ssdl|res://*/Models.DAModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=E:\MYWORK\DIGITALASSETSMVC3\DAMVC3\APP_DATA\DAMVC3.MDF;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

It's not a valid connection string which can be used by Membership, it's kind of special connection string just can be used by EF (because of different provideName which Membership expect AFAIK).
Add a clear regular connection string and reference to it instead.

Related

Cannot attach the file ".mdf" as database "aspnet-"

I'm using web sockets and SqlDependency to build a game server. An error with the SqlDataReader indicated that I should call SqlDependency.Start. I included the following in my Global.Asax:
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
This line always ends with the SqlException, with message:
Cannot attach the file 'C:...aspnet-ProjectName-11111111111.mdf' as database 'aspen-ProjectName-11111111111'.
I've been trying to fix this for two days. I've started a fresh MVC 4 WebAPI app, with a basic model, context, and seed, and can't get around this error. I've tried the various solutions in the following:
https://social.msdn.microsoft.com/Forums/en-US/ae041d05-71ef-4ffb-9420-45cbe5c07fc5/ef5-cannot-attach-the-file-0-as-database-1?forum=adodotnetentityframework
ASP.NET MVC4 Code First - 'Cannot attach the file as database' exception
EF5: Cannot attach the file ‘{0}' as database '{1}'
No change. I'm running MVC4 API in Visual Studio 2012, SQL Server is 2014.
This is a DB connection problem, right? The .mdf file in my AppData folder (both it and the log file are there in both projects) can't be connected to SQL Server? Also, help?
I encountered the same problem as you.
In your Web.config file, find you connection string, copy and paste it and then remove everything after the 'MultipleActiveResultSets' - apart from the providerName.
So in mine, it changed from this:
<add name="ApplicationName" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ApplicationNameContext-20151023111236; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|ApplicationNameContext-20151023111236.mdf" providerName="System.Data.SqlClient" />
Became this:
<add name="NotificationConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=ApplicationNameContext-20151023111236; Integrated Security=True;" providerName="System.Data.SqlClient" />
And as you will notice the connection has a different name.
The connections will still query the same database.
Now modify your connection string name in the Dependency.Start parameter to be your the name of the connection string you just created:
SqlDependency.Start(ConfigurationManager.ConnectionStrings["NEW_CONNECTION_NAME"].ConnectionString);
Remove the Initial Catalog property in your connection string.
You should see this answer: https://stackoverflow.com/a/20176660/161471

Azure: The context is being used in Code First mode with code that was generated from an EDMX

I have MVC app running fine in local. After updating to Azure, it started throwing the error:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project.
I have checked if there is any difference between the local web.config and azure web.config. except the credentials, everything is same. And it read:
<add name="DBEntities"
connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;
provider=System.Data.SqlClient;
provider connection string="data source=xx;initial catalog=xx;persist security info=True;user id=xx;password=xx;MultipleActiveResultSets=True;application name=EntityFramework""
providerName="System.Data.EntityClient" />
I am using EF 6.1.3, MVC5
I ran into the same error message and managed to solve it with the help of this post here on StackOverflow.
In the Azure Management / Web Apps / [Your web app] / CONFIGURE / connection strings , make sure of 3 things :
The connection string has the same name as the connection string in your project.
The connection string Value contains all of the metadata as appears in the connection string in your project. Mine looks like this:
metadata=res://\*/Models.[MyModel].csdl|res://\*/Models.[MyModel].ssdl|res://\*/Models.[MyModel].msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[myDBServer].database.windows.net,1433;Database=[myDB];User ID=[myDBUser]#[myDBServer];Password=[myPassword];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
The third column (default set to SQL Database) is set to Custom
Found a simpler solution than adding all the stuff in the Azure connection string. I just changed the connection string name in Azure. It worked..
I had to deal with the same issue. The solution was
Connect to the website by FTP
Edit web.config
Add following connection string:
add name="NewDatabaseEntities" connectionString="metadata=res:///NewDatabase.csdl|res:///NewDatabase.ssdl|res://*/NewDatabase.msl;provider=System.Data.SqlClient;provider connection string="Data Source=tcp:your.database.windows.net,1433;initial catalog=your;integrated security=False;User Id=your;Password=your;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
Thanks Microsoft for poorly documentation of EntityFramework Database First on Azure.
You need to change this line metadata=res:///NewDatabase.csdl|res:///NewDatabase.ssdl|res://*/NewDatabase.msl;
to
metadata=res://*/;

"Unable to find the requested .Net Framework Data Provider. It may not be installed."

I know that there have been a lot of other postings on this error but none have been able to shed any light or help on my issue. I am using a straight up connection to SqlExpress, so no special Oracle or MySQL databases or anything. It seems like this should just fit like a glove.
So the scenario is this, I have created a solution, comprised of a handful of projects; Repositories, Data (EF5.0), Utilities, a Test project and an MVC Web Application. The goal is to simply access an underlying SQL Express database via the Data classes via repositories in the Repositories project using EF5 and some repositories from the test project and the MVC Application.
The test project works and is able to access and update the database with no issue.
The MVC Web Project, however, is throwing the "Unable to find the requested .Net Framework Data Provider. It may not be installed." error, which I do not understand as it uses the same connection string as the Test Project.
[ArgumentException: Unable to find the requested .Net Framework Data Provider. It may not be installed.]
System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName) +1426271
WebMatrix.Data.DbProviderFactoryWrapper.CreateConnection(String connectionString) +64
WebMatrix.Data.<>c__DisplayClass15.<OpenConnectionStringInternal>b__14() +16
WebMatrix.Data.Database.get_Connection() +19
WebMatrix.Data.Database.EnsureConnectionOpen() +12
WebMatrix.Data.Database.QueryValue(String commandText, Object[] args) +63
WebMatrix.WebData.DatabaseWrapper.QueryValue(String commandText, Object[] parameters) +14
WebMatrix.WebData.SimpleMembershipProvider.GetUserId(IDatabase db, String userTableName, String userNameColumn, String userIdColumn, String userName) +232
WebMatrix.WebData.SimpleMembershipProvider.ValidateUserTable() +85
I have ...
Registered the System.Data.SqlClient in the web.config.
Verified that the registered version (2.0.0.0) of System.Data exists in the GAC per this article
Made sure that there were no typos in the Connection String.
Here's what I have in the web.config ...
<connectionStrings>
<add name="DBCatalogContext"
connectionString="metadata=res://*/DBCatalog.csdl|
res://*/DBCatalog.ssdl|
res://*/DBCatalog.msl;
provider=System.Data.SqlClient;
provider connection string="data source=.\SQLEXPRESS;
initial catalog=DBCatalog;
integrated security=True;
multipleactiveresultsets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<add name="SqlClient Data Provider"
invariant="System.Data.SqlClient"
description=".Net Framework Data Provider for SqlServer"
type="System.Data.SqlClient.SqlClientFactory,
System.Data,
Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</DbProviderFactories>
</system.data>
The only thing I see that doesn't make sense to me is, when I select the "System.Data" reference under the "References" folder and look at the properties it says that it's version 4.0.0.0, but when I change the version in the "DbProviderFactories" section of the config site I still get the error. Also I don't even see the reference to this library in the Test project which works.
I am confident that this is an oversight or that I am missing some config setting, but I do not know where else to look at this point, so any help would be appreciated.
Thanks,
G
I had apparently left out some ultimately pertinent information when I originally posted. This included the fact that the error was being thrown by the membership services; specifically the ... SimpleMembershipInitializer ... originally this class specified the connection string ... "DefaultConnection" defined in the web.config, to be used when initializing the database connection.
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "UserId", "UserName", autoCreateTables: false);
I had changed it to use the "DBCatalogContext" connection string I had added to the web.config, thinking that I would use this single connection string instead. The problem, of course, is that the new connection string that I added was an Entity Framework connection string which the membership services did not recognize resulting in the data provider error.
I simply added back the original, regular connection string, in addition to the Entity Framework connection string and now everything works. Well everything relating to this issue ...
<connectionStrings>
<add name="DBCatalogContext"
connectionString="metadata=res://*/DBCatalog.csdl|
res://*/DBCatalog.ssdl|
res://*/DBCatalog.msl;
provider=System.Data.SqlClient;
provider connection string="data source=.\SQLEXPRESS;
initial catalog=DBCatalog;
integrated security=True;
multipleactiveresultsets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="data source=.\SQLEXPRESS;initial catalog=DBCatalog;integrated security=True;multipleactiveresultsets=True;App=EntityFramework" />
</connectionStrings>
I hope that someone else can find this helpful.
I had the exact same issues.
I am doing the following:
I extended the UserProfile model to have a new property, Email.
I though I must also add the Email column to this call:
WebSecurity.InitializeDatabaseConnection("AgileBoardDB", "UserProfile", "UserId", "UserName", "Email", autoCreateTables: true);
This never worked, I always get "... Provider not found." I tried everything with no luck.
I turns out that EF is smart enough and automatically creates the Email column so I removed the extra Email parameter from WebSecurity.InitializeDatabaseConnection and all is working fine now.
PS: I am using the same EF connection string to connect to my DB.

How to create a valid connection string for Entity Framework - The underlying provider failed on Open?

Given the following connection string:
<add name="PrimaryDBConnectionString" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=10.1.1.101;Initial Catalog=primary;Persist Security Info=True;User ID=myuserid;Password=mypassword;MultipleActiveResultSets=True;Application Name=EntityFramework"" />
I attempt to open a connection in my DAL with the following:
using (PrimaryDBContext ctx = new PrimaryDBContext(ConfigurationManager.ConnectionStrings["PrimaryDBConnectionString"].ToString()))
{
try
{
ctx.Connection.Open();
var result = ctx.sq_newsfeed_GetProfileByID(profileID);
The error I get is:
The underlying provider failed on Open
I have messed around with the EF connection string and replaced all the provider prefix stuff with "metadata=res://*/;" but still no go.
Can anyone shed some light on this please?
Thanks.
-- Update --
Thank you for the response...
I ended up just creating a new db connection from the UI and modifying the connection string to match my needs:
<add name="PrimaryEntities" connectionString="metadata=res://*/PrimaryModel1.csdl|res://*/PrimaryModel1.ssdl|res://*/PrimaryModel1.msl;provider=System.Data.SqlClient;provider connection string="data source=10.99.108.42;initial catalog=primary;user id=dbuserID;password=somepw;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I kept the metadata portion. The trick was to ensure that your .csdl, .ssdl and .msl file name prefix matches your db context.
Are you using Code First/DbContext (your question is filed under entity-framework-4.1)? If so then your connection string should be just a regular connection string - something like this:
<add name="PrimaryDBConnectionString" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=squirtprimary;Persist Security Info=True;Integrated Security=true;MultipleActiveResultSets=True;Application Name=EntityFramework" />
(You also don't have to do magic with configuration manager - you can just provide the name of the connection string to your ctor like this:
"name=PrimaryDBConnectionString"
and it should work)
On the other hand, if you are not using DbContext but ObjectContext (the exception you get would indicate this - you did not get an exception saying that your connection string is wrong or you are missing the providerName parameter). Then you would need to check if you are able to connect to the database without EF. A few hints:
you use an IP address as your Data Source - if this is a remote server are you sure you enabled accepting external clients? (AFAIR this is disabled in Sql Server by default)
you are using user/pwd for authentication - are you sure that these are correct
One of the ways to check the above is to open Sql Server Management Studio on your machine and provide the data you have in your connection string.
The exception you are seeing does not indicate any problems with metadata part. It is specifically about not being able to open the connection to the database.

External SQL Server access in MVC 3 + Entity Framework for query-only

I'm devoloping a system using MVC 3 with EF 4. In this system, I need to lookup some information that already exists in an external database.
Saving me project's information on my database is OK. I defined my Models on it and let DbContext create the tables on my server.
The problem is when I try to query some data from the external database. I've added the connection string in the properly place on Web.config:
<connectionStrings>
<add name="ExtDBConnectionString" connectionString="Data Source=path.to.server;Initial Catalog=DBName;Persist Security Info=True;User ID=user;Password=pass;Pooling=True;Min Pool Size=5;Max Pool Size=60;Connect Timeout=2;" providerName="System.Data.SqlClient" />
</connectionStrings>
Is it possible to just create some queries to this server on my project without the overload of recreating all the Models from this external database? I know I can recover this connection string on my code by using the command System.Configuration.ConfigurationManager.ConnectionStrings["ExtDBConnectionString"].ConnectionString, but how can I create a connection and instantiate my queries?
Thanks in advance!
Edit: #rouen called my atention I didn't explicitly said the databases are differents. They do not share the same schema! The external database is the output of a report; so, I need to traverse it on my project to import the relevant lines to the local database.
I would just use standard ADO.NET. Use the SqlConnection and SqlCommand classes.
ADO.NET Examples on MSDN:
http://msdn.microsoft.com/en-us/library/dw70f090.aspx
Is the remote database schemantically identical as your local ? If yes, you can pass connectionstring to constructor of ObjectContext/DbContext, and it will use that database.
http://msdn.microsoft.com/en-us/library/gg679467%28v=vs.103%29.aspx

Resources