I have just completed my first project in WPF using C# and MS SQL 2008 express. I have used Visual Studio 2010. What I have right now is a class `conn.cs' that has a method that returns me the connection string as and when I require. Also I just noticed that I have an App.Config file that also has a connection string defined there (both strings refer to the same database).
My conn.cs
class conn
{
public string get_connection()
{
string conn_string = #"Data Source=.\sqlexpress;Initial Catalog=msp;Integrated Security=True;Pooling=False";
return conn_string;
}
}
App.Config
<connectionStrings>
<add name="msp.Properties.Settings.mspConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=msp;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
I want to know two things now.
How can I fetch the Connection String from the App.Config? I need to do this then, I will fetch the string in my conn.cs from there, and then, I will just change the connection string in the app.config as and when required.
Also tell me, is it possible to set connection string at run time? I want the user to browse to the database (.mdf) file on First Run and then the connection string should get generated and saved in app.config. I can then easily pick it up from there and use.
Please provide suggestions.
You should be able to get access your connection string using this:
string connString = Properties.Settings.Default.mspConnectionString;
(when typing Properties.Settings.Default you should automatically see your choices in the Member List)
You can of course set the connection string at runtime; it is basically just another string. I would not recommend hard-coding the connection string; though.
You might want to give the SqlConnectionStringBuilder class a try; see this MSDN article for example. But actually I never used it so far except for a few experiments here and there although I literally only do database-driven software...
Related
This connection always fails when I transfer my system to another computer. Whatis the correct code for a connection string that can run on another computer?
Public Sub connect()
con = New SqlConnection("data source=.\SQLEXPRESS; Integrated Security=true; User Id=sa;Password=sa;")
con.Open()
End Sub
I'm expecting for the code that can be run on other PC when I transfer my system
That connection string will work on any machine that has a local instance of SQL Server Express with the default name. There's no way to build a connection string that will magically work with any SQL Server instance with any name on any machine. If each user may need a different instance name then you have to provide for that.
One option is to store your connection string in the config file and let each user edit that by hand. That's risky if your user's aren't technically inclined though. You can also store the connection string attribute values somewhere, e.g. My.Settings and then provide a UI for the user to specify them at run time and persist them for later use. The specifics of that are up to you but you can find an example here:
http://www.vbforums.com/showthread.php?532768
The point of that thread was the encryption part but you can ignore that and just use the rest.
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
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"
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.
I have an application (WinForms) which using SQL Server as its database.
Now I am using app.config file to access ConnectionString.
Have a look at my app.config file
<configuration>
<connectionStrings>
<add name="dbConnectionString"
connectionString="Data Source=abc-79f1f531c9f;Initial Catalog=ItemStockInParth;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
You can see that Data Source=abc-79f1f531c9f.
Here ==> abc-79f1f531c9f is server name which is running on my (Developer's) PC.
Now when application is being installed at client's site, the server name should be changed to the server name which is running on the client machine or server name which will client machine use.
Then what should be the best criteria for handling this situation?
Means I have to create one new form which asking user to enter their Server Name and as per that I creating our ConnectionString?
Or dynamically getting the servername?
Or just hard-code the Server Name of client machine (or server name which will client machine use) inside our App.config file?
please help.....
You will probably want to provide a place where the user can enter the name of the server, or if you are clever, provide a list of available servers on the network (for example by using the code referenced by #user350374). Then you can generate an appropriate connection string as you need it using the SqlConnectionStringBuilder class:
var builder = new SqlConnectionStringBuilder();
builder.DataSource = ##SERVER NAME FROM USER##
builder.InitialCatalog = "ItemStockInParth";
builder.IntegratedSecurity = true;
builder.Pooling = false;
string connectionString = builder.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
// use the connection here for your code
con.Close();
}
This would take the place of requesting the connection string from your configuration class, i.e., where you would normally say ConfigurationManager.ConnectionStrings['dbConnectionString'].ConnectionString.
Since you can programmatically read the list of connectionstrings defined in the app.config, I suggest you create a list of connection strings and ask the user which one to use:
foreach(ConnectionStringSettings setting in ConfigurationManager.ConnectionStrings)
{
...
}
It's better than to ask for the server name, as you can give a nice name to a connectionstring entry.
Is this what you are looking for
http://krishnapyrmca.wordpress.com/2010/11/23/get-sql-server-name-using-c/
<add key="Connectionstring" value="Data Source=.;
AttachDbFilename=|DataDirectory|\AppData.mdf;
Initial Catalog=Appdata;Integrated Security=True"/>
<add key="Connectionstring" value="Data Source=.;
AttachDbFilename=|DataDirectory|\AppData.mdf;
Initial Catalog=Appdata;Integrated Security=True"/>
Simply add this code in the app.config file and attach your database to the setup file.
It automatically takes the database from the setup file of your project.