Entity framework work locally but not on azure - sql

I have a web project which works perfectly locally.
But when I change the connection string in my published web site on Azure to connect to my database on SQL Azure it will start giving this error.
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.
at MyClass.OnModelCreating(DbModelBuilder modelBuilder) in c:\a\src\MyProject\Model.Context.cs:line 25
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector)
My Config has:
<connectionStrings>
<add name="MyDBEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[Removed].database.windows.net,1433;Database=MyDB;User ID=[Removed];Password=[Removed];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"" providerName="System.Data.EntityClient" />
<add name="MyDB" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[Removed].database.windows.net,1433;Database=MyDB;User ID=[Removed];Password=[Removed];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"" providerName="System.Data.EntityClient" />
</connectionStrings>
I tested using my unit test locally with that connection string and it works from my local machine connecting to SQL Azure database.
Any help appreciated.

I was having this exact problem today; it's my first time deploying to Azure. I've been pulling my hair out, except I don't have any left. I finally figured it out, and it's probably the same issue original poster here is having.
Just like the original poster, I tested in these configurations:
ran WCF Web App from Visual Studio against local DB -- success
deployed WCF Web App from Visual Studio to local IIS, ran against local DB -- success
ran WCF Web App from Visual Studio against Azure SQL DB -- success
deployed WCF App to Azure via Visual Studio, running against Azure SQL DB -- FAILURE!!
After reading another post (Code First vs. Database First) I got a hint. That post says that if "connection string has the metadata, EF thinks it is Model First or Database First" but if it's a "plain connection string, EF thinks it is Code First." I browsed the deployed Azure Web Site's web.config and confirmed that the connection string had the proper references to the Model-First metadata. So what was the problem???
I figured that perhaps the Azure Website wasn't reading the web.config's connection string. Thinking back to how I'd created the Azure Web Site, I remembered that I'd given the Azure SQL DB an alias with the exact same name as my connection string's 'label' in the web.config!! To clarify:
in the Azure admin console I went to the Website settings and reviewed the "connection string" settings "baked in" to my Azure web site as a side-effect of creating-website-with-DB -- connection string 'handle' was "SsnCustInfoModelContainer" -- I'd mistakenly given the connection the same 'handle'/'alias' as my web.config 'handle' for the connection string, thinking this would help. Instead, when EF looks for the connection string, it was finding this 'aliased' handle, which was a "plain" SQL connection string containing no metadata. This 'alias' masked the real connection string specified in the web.config.
So I destroyed my Azure SQL DB and my Azure Web Site. Then I recreated the Azure Web Site, but this time I asked for the connection string 'alias' of "SsnCustInfoModelContainer_Proto" for the connection to the associated Azure SQL Server. After initializing the Azure SQL DB from my local SQL Server Management Studio, I deployed the WCF web app again to the Azure Web Site (I had to download a new deployment profile, of course, to do this), I tried the app again. This time it worked -- the 'alias' "SsnCustInfoModelContainer_Proto" did not conflict with and was not found by EF. EF instead went on to find the true connection string, with all the proper metadata, in the web.config. Problem solved.

Related

SQL Server Express dev setup - access denied whack-a-mole

I have a development environment in which I need to use IIS and SQL Server Express. My connection string looks like this:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyProject.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
This works great when I run the app and browse to the site. Data is returned from the database and I can log into Management Studio and view that data. The problem is when I try to push a new data migration using Update-Database.
I then get this error message:
Login failed for user 'AzureAD\MyAccount'
If I remove User Instance=True from my connection string, the Update-Database command suddenly works! Then I refresh my page and see the following error from all endpoints that require the database:
CREATE DATABASE permission denied in database 'master'.
I have already tried the trick of deleting this folder. It did not solve it.
C:\Users\MyAccount\AppData\Local\Microsoft\Microsoft SQL Server Data
What gives?
Figured this out so Ill leave the answer here for the next dev:
As I mentioned, my dev setup is running IIS and SQL Express.
Update the connection string to point to an Initial Catalog=MyDatabase instead of the AttachDbFilename=|DataDirectory|\MyProject.mdf
Remove User Instance=True. Your connection string now looks like:
Data Source=.\SQLEXPRESS;Initial Catalog=FullStackFitness;Integrated Security=True
Create the database by running Update-Database.
Create a SQL login for the app pool account (IIS APPPOOL\ACCOUNT) dbcreator and sysadmin on the database.
I did not test it but I believe you can keep using an mdf file and still get this to work by running only steps 2 - 4.
Troubleshooting Tips
Help troubleshooting the access denied issue came from a tip on Scott Allens blog:
The first step I would recommend is trying to determine what connection string the framework is using, because the exception doesn’t tell you the connection string, and the connection string can be controlled by a variety of conventions, configurations, and code.
To find out the connection string, I’d add some logging to a default constructor in my DbContext derived class.
public class DepartmentDb : DbContext
{
public DepartmentDb()
{
Debug.Write(Database.Connection.ConnectionString);
}
public DbSet<Person> People { get; set; }
}
Run the application with the debugger and watch the Visual Studio Output window. Or, set a breakpoint and observe the ConnectionString property as you go somewhere in the application that tries to make a database connection.

Azure SQL and my ASP.NET C#

I have made application ASP.NET C# and my connection string is as follows:
<add name="ASPNETDB" connectionString="Server=tcp:MYDATA.database.windows.net,1433;Database=MYDATA;User ID=MYDATA;Password=MYDATA;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
Now it doesn't work at all, I mean I can't connect to my SQL server on Azure at all. When I want to login nothing happens, when I want to register nothing happens too. I get exception when I press to update DB, ie Publish->Settings-> Check box "Update database" Configure database updates . It seems to me that it doesn't work at all. The exception is of following type:
Error 22 Web deployment task failed. (Could not deploy package.
Unable to connect to target server.
Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_EXECUTING_METHOD.) 0 0
What should I do? Please help?
I would recommend logging into the azure management portal and re downloading the publish profile for the application. If you are not working using a publish profile , then at least re download the connection string that is setup for the app and the DB. while in there check that the application (web site or VM) is up and running, and that the database it is connected to is also up and running.
I had to set firewall rule 0.0.0.0 to 255.255.255.255. Even though my firewall rule was set for my address, somehow it didn't register, because communication was relying to my website-DB and ip address of my website wasn't included there too. So I put rule as said before and now it works like a charm. :-)

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

I've got an application running on ASP.NET MVC 3 with Entity Framework Code First. In development I was using a SQL Compact database, however upon moving this to my virtual server, I am attempting to target SQL Express.
There were initially issues to do with a "CREATE DATABASE in master" error, which I got around by extracting the model from the SQL Compact database into an SQL script and executing that on the server to create the DB.
I have created a new connection string to point at the SQL Express instance, which uses the EF format:
<add name="LouiseClarkEntities" connectionString="metadata=res://*/Models.LouiseClark.csdl|res://*/Models.LouiseClark.ssdl|res://*/Models.LouiseClark.msl;provider=System.Data.EntityClient;provider connection string="Data Source=.\SQLEXPRESS; Initial Catalog=LouiseClark; User ID=<username>; Password=<password>"" providerName="System.Data.EntityClient" />
The error I am now getting when navigating to a page that uses the DB, is:
Unable to find the requested .Net Framework Data Provider. It may not be installed.
I have installed Entity Framework 4.1 on the server to try and see if this would solve the issue, but it didn't seem to do much good.
Snippet from the stack trace on error page:
[ArgumentException: Unable to find the requested .Net Framework Data Provider. It may not be installed.]
System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName) +1420567
System.Data.EntityClient.EntityConnection.GetFactory(String providerString) +35
[ArgumentException: The specified store provider cannot be found in the configuration, or is not valid.]
Any help would be appreciated, as this has been bugging me for days now!
Thanks,
Chris
Use the normal connection string with code first.
<add name="LouiseClarkEntities" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=LouiseClark; User ID=<username>; Password=<password>" providerName="System.Data.SqlClient" />
On your second problem, and partly the cause of the first too...
what you did wrong is which I got around by extracting the model from the SQL Compact database into an SQL script and executing that on the server to create the DB.
You should use migration scripts for that - and use in PM console then Update-Database -Script to dump out what you need - then deploy that to the server Database.
Problem is that there are CF has its own table and data that needs to be initialized properly. If that doesn't match you'll end up with something like that.

SQLExpress connection fails in IIS 7 w/ user instance error - "Failed to generate a user instance

Mainly looking to answer my question #1 below, but more knowledge would be appreciated.
I tried to use these resources during my investigation, but was unsuccessful:
http://social.msdn.microsoft.com/Forums/en/sqldatabaseengine/thread/f5eb164d-9774-4864-ae05-cac99740949b (For this error: Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path. Please make sure the user has a local user profile on the computer. The connection will be closed.)
http://social.msdn.microsoft.com/forums/en-US/sqlexpress/thread/6dfdcc22-7a81-4e8f-a947-c1ce6982d4b3/ (For this error: CREATE DATABASE permission denied in database master. An attempt to attach an auto-named database for file ? failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.)
Questions
1.) Why does this error occur while running the Telerik Rad Controls for ASP.NET AJAX "Live Demos" project with IIS 7 (Running Telerik Live Demos works fine using ASP.NET Development Server with this connection string)
Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path. Please make sure the user has a local user profile on the computer. The connection will be closed.
2.) How is creating a SQL Server Express instances different in IIS 7, from ASP.NET Development Server & SSMSE
3.) Are there certain attributes of a SQL connection string not allowed when running a website on different contexts (based on #2).
Environment:
I'm not running the "Live Demos" .NET 3.5 ASP.NET web application via the ASP.NET Development Server (feature that pops up in your system tray and picks a port for you after clicking play in Visual Studio). That works just fine! I'm running the website on IIS 7. SQL Server Express is using the NETWORK SERVICE user in Control Panel > Administrative Tools > Services > SQL Server (SQLExpress).
Using this connection string provided with the installed "Live Demos" web application demo project:
<add name="NorthwindConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Northwind.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
I've tried setting "User Instance=False", but that just throws another error:
CREATE DATABASE permission denied in database master. An attempt to attach an auto-named database for file ? failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
(where "?" is the path of the *.mdf file - C:\Users\\MyDocuments\Visual Studio 2008\Projects\TelerikDemos\Telerik\RadControls for ASP.NET AJAX Q2 2011\Live Demos\App_Data\Northwind.mdf .. Stack Overflow italics is broken with some of those characters, so I had to remove that path)
Someone answered me on a previous question to set this "User Instance=False", but it appears User instances have nothing to do with whether or not you use SQL Express. User Instances are simply a feature of SQL Express that allows a very unprivileged user to host a database instance in it's own user context.
Note, this Northwind database is stored in an *.mdf file in the App_Data folder (under the "Live Demos" root application directory) along with the *.ldf (log file). I did previously try attaching the *.mdf files as actual databases under the "Databases" folder (in the SSMSE Object Explorer tree), but later removed them.
Web application "Live Demos" root folder (and nested folders/files) have the following users assigned with ALL privileges:
- IIS APPPOOL\Telerik ("Telerik" is the name of my application pool in IIS 7 for this site)
- IUSR
- NETWORK SERVICE
Making a note for myself about this SQLExpress master database query:
SELECT * FROM sys.dm_os_child_instances
Also tried different combinations of *.mdf & *.ldf permissions while also changing the user on the SQL Server (SQLExpress) Windows 7 service (Control Panel > Administrative Tools > Services) .. and also restarted the service after making those changes.
To reproduce:
download the Telerik Rad Controls for ASP.NET AJAX. Set the permimssions I mentioned in the "Live Demos" folder under Program Files\Telerik, change the .NET version of the web application to .NET 3.5, switch out their 3.5 web.config file with the normal web.config file in that folder. You have to use Visual Studio 2010, but I am running this in Visual Studio 2008 (with a little grunt work I did because our company is not yet on VS2010). Also switch out the proper Bin35 assemblies into the "Live Demos" folder Bin folder. Compile the solution. Create an IIS 7 website. Add Windows authentication. Enabled anonymous and Windows authentication.. all others are disabled. Set application pool to use Classic and 32 bit.
Then navigating to this URL and clicking the "First Look" image.
http://localhost/combobox/examples/overview/defaultcs.aspx
====================
More evidence will be provided if requested.
You are using a connection string with trusted authentication = true. This means that the connection uses the security context of the calling process.
When you run with the development server you are running in the security context of the logged in user, so every thing works fine.
When you run in IIS you are in the security context of the application pool process, which is NETWORK SERVICE, which does not have a user profile, therefore it crashes.
You can fix it by either:
Change the identity of the application pool to a normal user with access to the database
Use a connection string with user name and password
IIS doesn't load the Windows user profile, but certain applications might take advantage of it anyway to store temporary data. SQL Express is an example of an application that does this. However, a user profile has to be created to store temporary data in either the profile directory or in the registry hive. The user profile for the Network Service account was created by the system and was always available. However, with the switch to unique Application Pool identities, no user profile is created by the system. Only the standard application pools (DefaultAppPool and Classic .NET AppPool) have user profiles on disk. No user profile is created if the Administrator creates a new application pool.
However, if you want, you can configure IIS application pools to load the user profile by setting the LoadUserProfile attribute to "true".
https://learn.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities

SQL Error Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection when I'm trying to open the WebPart

I've created a custom Web Part for SharePoint that interacts with SQL.
Everything worked fine on my DEV server.
After I moved the WebPart to the client's server I started having problems.
I get Error Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection when I'm trying to open the WebPart.
I've searched for solution for a few hours by now and everything I have found doesn't seem to work in my case.
This is how my connection string looks like:
<add name="MyDataEntities" connectionString="metadata=res://*/MyDataModel.csdl|res://*/MyDataModel.ssdl|res://*/MyDataModel.msl;
provider=System.Data.SqlClient;provider connection string="Data Source=ServerName;Initial Catalog=DBName;
Trusted_Connection=yes;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
The SharePoint Web App with the web part and SQL DB are on two different machines.
Here's what I've tried:
1). Made sure SQL uses Mixed mode authentication
2). Made sure the account I'm using has rights to access SQL
3). Tried replacing Integrated Security=True; in the connection string with the User ID = UserID; Password=Password; where UserID and Password were the account IIS is running under.
I ran profiler while clicking on the link and it looks like the app is not using the account’s credentials and is trying to log in anonymously.
Any help is appreciated, I'm desperate because this must be up and running by tomorrow.
Thanks in advance!
Try SPSecurity.RunWithElevatedPrivileges: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx
This method will run code as the ASP.Net application pool identity. Wrap your database calls with it.