ASP.NET MVC: moving from SQL Server Express to Azure - c#

I'm sure this has been asked before, but I'm not seeing anything in the similar questions. :(
I've got an ASP.NET MVC application I have developed locally that has been using a SQL Server Express database. In Azure, I recreated the database and taken the connection string it provided and updated the connection string in web.config of my app to use the new database.
When I publish the app to Azure, there doesn't appear to be any issues. However, when I hit a page in the app that accesses the db, it throws an error complaining it can't find the SQL Server Express database. Below is the main snippet from the error:
SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
So it seems like it's ignoring my connection string and still looking for a locally stored SQL Server Express database instead of using the Azure database I specify in the connection string. Any ideas why this might be? My guess is that I have missed something pretty basic (my usual guess when something that seems like it should be simple doesn't work. :) )
Connection strings per below request:
Local:
<add name="FCDbContext" connectionString="data source=(localdb)\MSSQLLocalDB;initial catalog=FormCenterResponder;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Azure Contection String:
<add name="FCDbContext" connectionString="Server=tcp:***azuredbserver here***,1433;Initial Catalog=***azuredb here***;Persist Security Info=False;User ID=***username here***;Password=***password here***;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
And configureservices per another request (it's pretty much defaults):
public void ConfigureServices(IServiceCollection service)
{
services.AddControllersWithViews();
}

Ok, mark this one up to being a asp.net/c# noob. I'll go ahead and post (the embarrassing) answer, though, in case others find themselves in my position.
A co-worker had a look at the code and found an excellent tutorial here. He was able to figure out what I had done wrong.
Basically, I had never registered the database context in Startup.ConfigureServices. I think this is why someone (who has since deleted their question) asked me to post that section of my code. Then that context can be read in by the controller files granting them the info they need to get access to the db.
App is now working as it should.

Related

Error Database schema could not be retrieved for this connection

Edit: if you are downvoting can you at least tell me what Im missing so I can improve my question?
I have a website which uses a SQL Server database. It works fine when building both debug and release.
But if I add a new SqlDataSource to my project and try to configure it in design view, I get this error:
Database scheme could not be retrieved for this connection. Please make sure the connection settings are correct and that the database is online.
Failed to retrieve data for this request.
Failed to connect to server---------.
Login failed for user 'xxxxxx'.
Even if I configure the connection string with the connection-guide, test the connection and save, it fails afterwards when trying to configure the datasource.
Connection string:
Data Source=SERVER\SQLEXPRESS,61180;Initial Catalog=DBNAME;User Id=USERNAME;Password=PASSWORD;
So to clarify: The connection string works fine when running the website in both debug and release, and if I connect using SQL Server Management Studio, but the only place it doesn't work is when I try to configure the datasource in design view.
After a lot of trial and error I found out that I had to put Persist Security Info=True; into the connectionstring to get it to work.
First time in my 10+ years of programming that I encountered this problem.

Azure Cloud Service unable to connect to SQL Database on write operations only

I have developed a web application in lightswitch. There is an HTML lightswitch client that connects to a server (C#) and this server gets the data from an SQL Database.
The application is working correctly in my local machine, the problem comes when I publish the solution to a Cloud Service in Azure. Then, the server connects to the database correctly and can read all the information from it, but when I try to update the database from within my application (insert or update rows) the application freezes and it promts the following error:
Unable to connect to SQL Server database.
Inner exception message:
Unable to connect to SQL Server database.
Inner exception message:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I have checked the connection parameters and all of them are correct, this is the connection string in my web.config:
<add name="My_Data" connectionString="data source=tcp:{MyServer}.database.windows.net,1433;initial catalog={myDatabase};user id={Myuser}#{MyServer};password={MyPassword};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
I have seen other questions with the same issue, but all of them were because the database or the server was not available. I have no problem connecting to the server because I can query my database with no problems.
The error comes when I try to write in my database, either because I click on the save button of a lightswitch screen or because I do it by code in the server:
serverContext.DataWorkspace.My_Data.SaveChanges();
If I comment the previous line, the error is not prompted.
I have also checked the user permissions in the database and this usser is a db_owner, so there should be no problem with that.
Anyone has ever faced a problem like this?
I found the solution!
After a deep research, I discovered that Azure server is adding a connection string to my application (I don't know how nor why). This connection string is inherited from somewhere and it is pointing to a local instance of SQL Express. Obviously, this instance does not exist, so after a timeout the application throws the error shown above.
I don't really know why this is happening nor why only happens when I try to write in my database. The solution I found is to add the following in the connection strings part of my web.config:
<clear />
With this, we delete the inherited connection string. And now, we have to set the connection string of the LocalSqlServer (which will be our connection string, the one that points to our remote SQL Server in Azure):
<add name="LocalSqlServer" connectionString="Data Source={SERVER}.database.windows.net;Initial Catalog={DATABASE};Integrated Security=False;User ID={USER}#{SERVER};Password={PASSWORD};Encrypt=True" />
Now, everything works fine. I hope this can help anyone who faces the same problem than me and I would really like to know why this happened, so if anyone knows it, please tell me :)

Connection string is not valid or Error Locating Server/Instance

I reinstaled my PC and now I have problems with my SQL connection string or with SQL Server 2012 Enterprise
Error I get:
"... (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)" or
"... (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
In SQL Server Management Studio server instance looks like this:
TOM-PC (SQL Server 11.0.3128 - Tom-PC\Tom)
And My SQL connection string in ASP.NET XML config. file:
<add name="ApplicationServices" connectionString="Data Source=.\TOM-PC;Database=D:\Programming\InvoiceManager\invocemanagerSQL.mdf;" providerName="System.Data.SqlClient" />
Tried everything, in firewall added port 1434 or 1433 tested both, not working, "SQL Server Browser" Service is running, TCP/IP Enabled, Allow remote connections to this server, even tried 4 different connection strings, nothing worked.
Before it worked like a charm, not fully but worked. Why not fully? Because I couldn't work on my local machine with both studios "VS2010" and "SQL Management studio" at the same time, if I needed change something in database manually, I needed to stop or restart SQL Server process and service, then I get in database, and read tables. Now, nothing is working!
What I do or did wrong? Where seems to be the problem? Why always are problems with SQL servers and it's connectionstrings?
What you are seeing in Management Studio is as follows:
Instance Name (SQL Server version - Domain\LoggedInUser)
You are logged in using integrated authentication (i.e. your windows logon account) but not specifying it in the connection string. This will try to use the currently logged on user for the ASP.Net application, which will almost certainly not be running as your windows account. It will either be one of the local or network service accounts or a built-in ASP.Net user.
You're also using the wrong variable name to attach the database file, if this is actually what you want rather than connecting to an actual database on the server.
What I suggest you do is enable SQL Server authentication on your instance, create a new user and give it permissions to the database as required.
You would then log in using the following format:
Server=myServerAddress; Database=myDataBase; User Id=myUsername; Password=myPassword;
Where myServerAddress would be localhost or TOM-PC; Database would be the name of the database as it appears in Management Studio; User Id would be the username for the user you just created and Password would be the password you set for them during creation.
If you do actually want to attach a database file then your connection string changes to use this format:
Server=myServerAddress; AttachDbFilename=C:\Path\To\Database\File.mdf; Database=myDataBase; Trusted_Connection=Yes;
Typically, you can get most connection string variants that you will need from: http://www.connectionstrings.com/sql-server/

Two database connection strings in app.config with EF code first approach causing error

I have code first entity model designed and working fine as follows:
<add name="DemoEntities" connectionString="metadata=res://*/DemoDataModel.csdl|res://*/DemoDataModel.ssdl|res://*/DemoDataModel.msl;provider=System.Data.SqlClient;
provider connection string="data source=myservername;initial catalog=DemoDB;user id=demouser;password=abcd123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="SecondDemoEntities" connectionString="metadata=res://*/SecondDemoDataModel.csdl|res://*/SecondDemoDataModel.ssdl|res://*/SecondDemoDataModel.msl;provider=System.Data.SqlClient;
provider connection string="data source=myservername;initial catalog=SecondDemoDB;user id=demouser;password=abcd123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
But first connection string is working fine and i am able to read the data. But second connection string is throwing following error:
''A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Run time error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.''
Please help, I have done this:
Used separate entity files and declared them in the constructors:
public Application1Entities()
: base("DemoEntities")
{
}
public Application2Entities()
: base("SecondDemoEntities")
{
}
Looks like you're trying to create the second on the wrong server. At a glance, it looks like both of these reside on the same server but are using different server names.
data source=myservername;
data source=secondDemoDB
Both of those data source lines need to be the same if they are hosted on the same server. The Initial Catalog determines which database on the server that EF will draw from.
I figured out the issue. I have to declare the same connection string in UI application also. That whole thing was in my DAL library. When i declared the same connection string in my UI application everything worked well..

error: 26 - Error Locating Server/Instance Specified. (Can't connect to my local Db From my host server)

I already asked this question before, but without any good response,
my problem is that I have a local database (aspnetdb.mdf) in my app_data folder, here is the connection string in the web.config :
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
so my site works fine in my local iis server, but when i put the site in my host server, I get this error message :
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified).
In the other server I have sql server 2008 (the remote connection is accepted and i have the same instance name SQLEXPRESS). I really tried everything that I can but without any good results. I will really appreciate your help, thx.
This format indicates a local connection:
.\SQLEXPRESS
From another server, you'll need to specify a server name or IP address, e.g.:
192.168.1.205\SQLEXPRESS
YOURMACHINE\SQLEXPRESS
You'll also need to validate that the instance is SQL Server Express. From your other nearly identical question it looks like a default instance.
You should also stop using this silly user instance / attachDbFilename technique. Attach your database to the instance properly, then reference the logical database name using Initial Catalog=aspnetdb; in your connection string. This user instance feature was deprecated for multiple reasons, and this is certainly one of them.
Of course there may be other network issues that will prevent this, e.g. if the server is in a different domain, there are firewall settings interfering, etc. But your other server is never going to be able to access your machine using a dot for the server name.
EDIT providing baby steps because obviously my advice is not being followed. Assuming you have actually attached the aspnetdb database on the new server, try this please:
connectionString="data source=192.168.85.124\SQLEXPRESS;
Integrated Security=SSPI;
Initial Catalog=aspnetdb;"
If you aren't using SQL Express named instance after all, try:
connectionString="data source=192.168.85.124;
Integrated Security=SSPI;
Initial Catalog=aspnetdb;"
For SQL authentication use the same username/password you use in Management Studio:
connectionString="data source=192.168.85.124;
User ID=username; Password=password;
Initial Catalog=aspnetdb;"
This is troubleshooting 101 stuff. If you still can't get this to work, you may have to hire a consultant for 10 minutes to fix it for you since it's impossible to figure out what you've done and why you can't get it to work.

Categories

Resources