Parallels Plesk Panel connecting to database server connection string - sql-server

I am using Entity Framework to access the data from my database. It's an MVC application and works fine locally. When I deploy the application on hosting (Parallels Plesk Panel, MS hosting) I get problems with accessing the SQL server instance. There are options in the cPanel which hold connection strings.
LocalSqlServer:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
xContainer:metadata=res:///Models.x.csdl|res:///Models.x.ssdl|res://*/Models.x.msl;provider=System.Data.SqlClient;provider connection string=
When I upload the site xContainer is generated alone. I found the sql server's instance name and applied it to the data source. In my web.config file I am using the the xContainer. The code after this paragraph is what it seems logic to me to add after the connection string= in the xContainer.
I have tried this with various properties. Data source, initial catalog, and the other info are filled into the conn string (here I am showing only /).
Data Source=x;Initial Catalog=/;Persist Security Info=True;User ID=/;Password=/;MultipleActiveResultSets=True providerName=
The error I receive is that the sql server instance cannot be found. If I add the last piece of code to the container it tells that I don't have a providerName, After adding a providerName the string is deleted to the starting xContainer string:
metadata=res:///Models.x.csdl|res:///Models.x.ssdl|res://*/Models.x.msl;provider=System.Data.SqlClient;provider connection string=

The error I receive is that the **sql server instance cannot be found**.
So, what is the SQL instance name? :)
it maybe not ".\SQLEXPRESS" but ".\SQLEXPRESS2012" or even ".\MSSQLSERVER" or anything else.

You will need to Edit the Web.Config file manually. The ASP.NET Settings page will remove the providerName.
An example of a connection string using EntityClient is below. You can remove the metadata information if you're not using an Entity Model. You will notice the providerName is outside of the actual connectionString and is the reason you will need to edit the file manually.
connectionString="metadata=ModelInformation;provider=System.Data.SqlClient;provider connection string="data source=IP;initial catalog=DATABASE;User ID=USERNAME;Password=PASSWORD;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"

Related

Connection string in appsettings.json for remote database

I have hosting account in plesk panel. I can create and remove a database in hosting panel.
Now I want to create a database from my local computer using add-migration in code first approach. but the following error occurs:
"login failed for the user [myUserId]"
The connection string in appsettings.json is:
"CourseConnection": "Data Source = host-ip,1433; Initial Catalog=mydb;User ID=myuserid;Password=mypassword"
There are two options to create databases on hosting panel:
localhost:3306(default for mysql)
localhost(default for MS sql v13.0...)
I think that provider name is not mentioned in connectionstring but appsettings.json works fine on my local machine without provider name: System.Data.SqlClient.
after hours of try and error , the problem solved as follows:
i created the database in plesk panel and created a new user .
then assign that user to the database . then in package-manager-console applied update-database command to apply migration that was already added.
i used the same connection string in appsettings.json ,it worked successfully.all table created and migration applied .
it may be helpful for someone.
regards

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://*/;

Cannot access SQL Azure DB from Azure website even though same connection string works from local website

I've recently set up my first website on Azure. For now, it's basically just the standard MVC4 template website with the Home and Account controllers. In Azure, I have one website, and one SQL database. I can access the SQL Azure database from SSMS, and have set up a login and user to be used by my website.
In my development environment, pointing at my development database, I can access the /Account/Login page fine. I can register, and I can see the new user in my local db. I can also change the connection string to point my development website at my SQL Azure DB, and again I can access /Account/Login and register new users. I can then see those new users in the SQL Azure DB.
The problems happen when I deploy the website to Azure. I have a transform config associated with my publishsettings file, and I can see in the output window when publishing the site to Azure that this transform is applied during deployment. This amends the local development DB connection string to the SQL Azure connection string. I have also verified that this SQL Azure connection string is in the actual web.config file deployed (using FileZilla FTP to retrieve the actual web.config deployed). I can access the home page of my site on [mysite].AzureWebsites.net, but when I click the login link to go to the /Account/Login page, I get the following error:
[ArgumentException: Format of the initialization string does not conform to specification starting at index 0.]
System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) +5313265
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +124
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +95
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +24
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +167
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +61
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +66
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +122
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +127
System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +346
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps() +17
System.Data.Entity.Database.Exists() +36
[MyWebsite].Filters.SimpleMembershipInitializer..ctor() +105
This seems to suggest that there is an issue with my connection string, but like I mentioned earlier, this exact same connection string worked from my local website.
I've considered that the issue might be firewall-related, but I've checked the settings in the Azure management portal, and the Windows Azure Services firewall rule is applied to allow that access. Also, I've tried removing the firewall rule for my local machine to access the SQL Azure DB, to see would I get a similar exception, but the exception thrown was very obviously firewall-related.
I have also tried to add the SQL Azure connection string through the Azure Management portal (though I didn't see how to specify the provider) - needless to say, I got the same "Format of the initialization..." exception mentioned above.
My connection string in the web.config is in the following format:
<add name="[my connection name]"
connectionString="Server=tcp:abc123.database.windows.net,1433;Database=[my database];User ID=[my login]#abc123;Password=[my password];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
providerName="System.Data.SqlClient" />
Any suggestions would be very welcome.
I've FINALLY got to the bottom of it. What I didn't realise until now was that there were 2 connection strings in the web.config that ultimately gets deployed to the Windows Azure website - my own custom one, but another DefaultConnection connection string as well, which has the format:
<add name="DefaultConnection" connectionString="DefaultConnection_ConnectionString" providerName="System.Data.SqlClient" />
obviously, not a valid connection string (and hence the format exception above). You can see this when you download the actual web.config from your Azure website using FTP.
This default connection string isn't anywhere in the web.configs or various transforms in my solution. Looking at the Output window during publishing, there are a number of transforms that get applied to the web.config. I've gone through the various versions of the files that get generated during the build / publish cycle, and none of them have the DefaultConnection connection string in them, not even in the obj\Release\Package\PackageTmp\ folder. So I'm guessing something in the Web Deploy phase is inserting it as the very last modification of the web.config. There is an MSDeployParameterValue element in the publishsettings file that mentions connection strings and the web.config - I guess it could be that.
In the AccountModels.cs file, a reference is made to this DefaultConnection:
public UsersContext()
: base("DefaultConnection")
{
}
This is how the particular connection string is chosen. Changing this parameter to your custom connection string name ensures that your custom database gets used for the various account stuff, and resolves the format exception seen above.
I know this is an old post, but I wanted to share my findings. In my .pubxml file, it stored my localdb connection string, and would not update on any builds, or publishing. I had to manually update the publish file with my azure DB connection strings in order for it to work. Hope this helps save someone time.
About the Connection strings of SQL Azure
The SQL Azure Database service is only available with TCP port 1433. Ensure that your firewall allows outgoing TCP communication on TCP port 1433.
SQL Azure does not support Windows Authentication. The Trusted Connection will always be set to False.
SQL Azure doesn’t support unencrypted connections. You need to specify in your connection string that you want to encrypt the connection.
Connecting to SQL Azure by using OLE DB is not officially supported.
Standard way
Server=tcp:[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;Encrypt=True;
Use 'username#servername' for the User ID parameter.
For more information check this out Connection strings for SQL Azure
I hope this will help to you.
Try removing "Encrypt=True;" or try adding "TrustServerCertificate=True;" - Read SqlConnection.ConnectionString Property for more details, but basically:
Beginning in .NET Framework 4.5, when TrustServerCertificate is false (the default)
and Encrypt is true, the server name (or IP address) in a SQL Server
SSL certificate must exactly match the server name (or IP address)
specified in the connection string.

Classic ASP - SQL Server 2008 Connection String using Windows Authentication

This should be painfully simple, but I cannot come up with a working connection string for a local copy of SQL Server 2008 using Windows Authentication. I've tried using the Data Link Properties tool to create a connection string and it has no problems connecting, but when I copy paste the generated string into my ADODB.Connection object's ConnectionString property I get all sorts of fun and different errors.
Set conn = Server.CreateObject("ADODB.Connection")
conn.ConnectionString = "SQLNCLI10.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=climb4acure;Data Source=(local);"
Microsoft OLE DB Service Components (0x80040E21)
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
I've tried a variety of similar connection strings but I cannot find one that will work with Windows Authentication. Can someone point me in the right direction?
Thanks!
Here's an easy way to generate connection strings that work.
Right-click an empty spot on the desktop and choose NEW, TEXT DOCUMENT from the context menu
Save it with a .udl extension, and click yes when it asks are you sure.
Double-click the new udl file you just created. It will open a dialogue. Go to the Provider tab, and choose the appropriate provider.
Go to the Connection tab and fill in the server name and database name, and choose NT authentication (or use a specific username and password, which is SQL authentication). Now click Test Connection. If it works, you're ready to click OK and move on to the final step. If it doesn't you need to resolve permission issues, or you've mis-typed something.
Now right-click the file on the desktop and open it in notepad. It will display the connection string that you can copy and paste to wherever you need it.
I assume you have the 2008 Native Client installed? Also, I noticed that you're missing the "provider" tag at the beginning - do you have any more luck with this one:
Provider=SQLNCLI10.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=climb4acure;Data Source=(local);
Have you had a look at connectionstrings.com? They are a pretty good reference (but, in my experience, they don't work too well in the Google Chrome browser).
Works absolutely fine:
"Provider=SQLNCLI;Server=xxxxxxxx;uid=sa;pwd=xxxxxx;database=xxxxxx;"

Resources