I just created a desktop Winforms application with localhost database.
The connect string I am using is this:
SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Administrator\Desktop\learningsystem\LearningSystem\LearningSystem\LearningSystem.mdf;Integrated Security=True");
If I want to run my application on other computers, how should I make it work?
EDIT:SOLUTION
Thank for all the help! I tried the following steps. I think it is working now. But please correct me if I did something tricky.
1. add a new setting item in project property setting. App.config will automatically update:
<connectionStrings>
<add name="LearningSystem.Properties.Settings.LearningConn" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LearningSystem.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
</connectionStrings>
2. In my program, just add the following statement to connect to the sql server
SqlConnection connect = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\LearningSystem.mdf;Integrated Security = True; Connect Timeout = 30");
Further question
If others will run this application on their computer(not in the same network), they just go into the project setting and change the value by selecting the database file I provide to them,the connectionString will automatically change, right?
Thanks!
It's generally a bad idea to hard code such stuff in your application. Normally, application settings and connection strings are placed in the application's configuration file (in the ConnectionStrings section).
Just like with all strings, you could build your connectionstring from dynamic parts (variables, settings, etc.) and then pass that generated connectionstring to the SqlConnection constructor. Again, to make those separate parts configurable without hard coding them in your application, you might want to add them to your application's configuration file (in the AppSettings section). But IMHO this is an overly complex solution in most scenarios. Putting the entire connectionstring in the ConnectionStrings section is more straightforward (and more flexible).
Anyway, again, to make your application configurable, you might use your application's configuration file (App.config or Web.config), you need to add a reference to System.Configuration in your project's .NET Framework dependencies and use the AppSettings and ConnectionStrings properties of the System.Configuration.ConfigurationManager class.
(Of course, there are more ways to make your application configurable. But using the application configuration file is one of the most straightforward solutions.)
Edit:
When deploying your app to another computer, you need to copy its database over too. If you want to use the application on multiple machines and let them connect to the same database, you might want to leave LocalDB and migrate the data to a SQL Server (Express) instance and make it accessible over the (local) network.
Edit 2 (regarding the recent edits in your post):
I see in step 1 that you are using an application setting (called LearningConn) in your solution now. That's fine. However, it is important that you also use that setting in step 2, like this:
SqlConnection connect = new SqlConnection(Properties.Settings.Default.LearningConn);
If you change the setting in Visual Studio, it will update the connection string. Since the setting will probably have application scope, it will not be possible to update the setting/connection string within your application in runtime (by the user).
I'm not sure if your connection string using |DataDirectory| will always work as expected in all scenarios. I have only been using it in ASP.NET webapplications. If it does work in WinForms applications, you might read this document to learn how to set it up. But personally I am somewhat sceptical about this approach.
I personally would opt for a solution where you use a placeholder in your connection string, which you replace with the full path to the .mdf file before you pass it to your SqlConnection constructor.
When you use "{DBFILE}" as the placeholder, for example, the value of your LearningConn setting would look like this:
Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={DBFILE};Integrated
Security=True;Connect Timeout=30
(Note that this value should be a single line without any line breaks!)
You might create a separate setting in your application called DbFile (of type string) to store the actual value that should be put in place of {DBFILE} in your connection string. When you use scope "user" for that setting, the value might be changed from within the application by the user. When saved, it might not be saved directly in the application's configuration file, however, but in an additional configuration file hidden somewhere in the user's Windows user profile. You might read this document to learn more about application settings.
Your code in step 2 might eventually look something like this:
string connectString = Properties.Settings.Default.LearningConn;
string dbFile = Properties.Settings.Default.LearningSystemDb;
connectString = connectString.Replace("{DBFILE}", dbFile);
SqlConnection connect = new SqlConnection(connectString);
To let your application's users select and store the database .mdf file to use, you might include (a variation of) the following code in your application somewhere:
using (var dlg = new System.Windows.Forms.OpenFileDialog())
{
dlg.Title = "Select database file to use";
dlg.Filter = "Database Files (*.mdf)|*.mdf";
dlg.CheckFileExists = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Properties.Settings.Default.DbFile = dlg.FileName;
Properties.Settings.Default.Save();
}
}
Your question is not clear!
you need work with one Database on 2 or more PC?!
OR
you need work with 2 separate programs?
if you need 2 separate programs :
you must copy .mdf file to other PC at same address or keep mdf address in app.config and read it before connect to SQL.
How to Read From app.config
if you need work with one Db you must connect to dataBase Server such as SQL Server and keep connection string in app.config in connectionStrings tag.
Get connection string from App.config
If you want to work on other PCs, rather than building it dynamically make the connection string more generic:
Server=(localdb)\\mssqllocaldb;Database=LearningSystem;Trusted_Connection=True;MultipleActiveResultSets=true
This should create the mdf file under 'mssqllocaldb' in %appdata% for each user. You might need LocalDb installed (which you tick during SQL Server installation)
Related
I am creating a writable application database in \AppData\Roaming\ProjectName to keep authorization and cache.
So firstly, i have database.db in my project that i will copy to
AppData, when App is started for the first time. But i have no
idea how write a Connection string in App.Config that case. Now it is:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\cache.db" providerName="System.Data.SQLite" />
</connectionStrings>
Secondly, i am not sure, that i should use App.Config connection , but i`m going to change data a lot of times.
Thirdly, did i chose a right path to keep writable database
or there are any of other ways?
This is how I would reference a sqlite database in the appdata folder. I would not use the ConnectionStrings section of app.config. I would use the connection string builder and use Environment to get the path to the user's app data folder.
SqliteConnectionStringBuilder bldr = new SqliteConnectionStringBuilder();
bldr.DataSource = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"your-program-folder-name",
"your-database-name.db");
var sqliteConnection = new SqliteConnection(bldr.ConnectionString);
in #2 of your question I do not understand what you are referring to about changing data. Do you mean in the database or in the config file?
Regarding #3, you mention this database is used for authorization. If you put the database on the client machine you cannot lock it down. A user can figure out how to circumvent your security. So, if security is any kind of concern you need to put the back end on a restricted server and use a system that employs Role Based Access Control (or similar), and that is a large topic in itself.
Recently I am working on an .Net project. We used EF to handle SQL, when we make an installer of the program, we realize that app.config is visible which mean that the connection string is not safe.
I am looking for a way to add connection string (or maybe secret code and username) to the EF so that the connection string is not visible.
Something like change old code from this
Using db As ConnectDb.adoSentoEntities= New ConnectDb.adoSentoEntities
'TODO
End Using
to this
Using db As ConnectDb.adoSentoEntities= New ConnectDb.adoSentoEntities(ConnectionString)
'TODO
End Using
But since we used connect code to SQL all over the place, changing every single line of code is not possible. There is a way I only need to add connection string once?
You’d be better off encrypting the connection string section in the app.config. You wouldn’t need to make any changes.
Storing any sort of configuration in an assembly can be read using a hex editor.
It’s been answered on here before.
Encrypting Connection String in web.config
You’d be better off using a trusted connection if you’re using SQL Server. The user running the app would need to have permissions and no username and password is required.
Save connection string is settings of project properties.
Go in project properties.
Select settings.
Add new setting as connection string and save connection string.
Then you can use it for whole project.
Ok, so I'm doing a website in .Net and for one of my validators, I'm trying to connect to my database. It's a database that I created in my App_Data folder, so it's a local one. The thing is, I have the following on my C# file:
SqlConnection db = new SqlConnection();
db.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\baseDados.mdf;Integrated Security=True";
db.Open();
//MORE CODE
I've got an error on my ConnectionString. Can't I use the same connectionstring that the one in my web.config file? I have been looking to how to connect to my database, but none of the solutions worked for me 'till now. I'm probably overlooking something. Thanks. :)
|DataDirectory| is a pointer in the config that gets replaced by the actual location of the database. You are using an attached database, so it is looking for the actual directory the data file is located in.
My suggestion, as it is more likely to be like production, is attach the database file to the database server. Since it is .mdf, I am guessing SQL Server (99.9% sure it is SQL Server). You will then alter your database connection string to point to the server, database name, etc. The main change will be the center section. The other option is find the actual location of the file and attempt from there. This should work, as that is what the server does for you when it pulls from config.
I don't have time to look, but I bet there is something in config that points where that file is, or it is automatically stored in a specific location by the framework. A quick Google search should yield answers.
I am creating a C# windows form application, the working can be summarized as users fills some form and data is saved in SQL database. Now the problem I am facing is that I have to deliver this as an executable file to someone. But the problem is database is creating issues as the connection string is not match with that computer. I know that if a distribute projects I can put connection string in app.config and every user can change it according to his/her machine. But i want to make it more convenient for the user not to change the connection string as i am only giving the executable file to client. as i have the connection string in my project is
String ConString = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=D:\Users\khan\Desktop\MyApp\MyApp\Database1.mdf;Integrated Security=True";
So how to make it generic so that the client does not need to change the connections string. Kindly elp me out in this issue.I have searched a lot but still not done with it.
Try to use a Enviroment Variable instead of a fixed path in AttachDbFilename.
For example %APPDATA%\Database1.mdf.
I have three computer in a office and I have installed my C#-2005 Project on all three
computers. But Problem is that Boss wants Sql-server-2000 on One PC out of three and other
would share the same.
I don’t know how to share Sql-server-2000 between three PC?. How to do?.
Confusion:-
Thanks for your co-operation but here I have a confusion on majority people said to check
TCP/IP address and consider the Connection string as per main server from client PC.
Suppose I have financial project and there would be thousand of connection string in a
project. As per above I have to change thousand of connection string as per main pc.
Now think it is a one customer's need If I have ten cutomer having same offer than think How much time I have to waste on it?. I have to modify thousand of connection string ten time more?.
If it is true than it will take lots of time on installation to each customer.
I don’t know if it is only way?.
The Connection string I have utilized on my each winform is as below:
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Here suggested about Config File and same I don't know if some body give me idea about how to consider it with my C#2005 project than it will save my lots time.
When you connect to the database in your code, you'll a database connection string of some sort somewhere in there. Figure out the connection string for the Database server and set your code to point to that database server's connection info; I'd bet you currently you have it pointed at localhost
If you're using SQL Server you may need to enable remote connections on the database server.
added: you may need to modify firewall settings as well to allow SQL Server traffic (thanks Jared)
.
Edit: For putting the configuration string into a central location.
Your posted code
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Change to
Assuming your application has a App.Config file then you'd add an entry in there like
<add key="DBConnectionString" value="server=.;initial catalog=maa;uid=mah;pwd=mah"/>
And change your C# code to be like
string connstr = ConfigurationManager.AppSettings["DBConnectionString"];
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Putting the ConfigManager call into a class might be a good idea if you have a lot of settings to retrieve and/or believe the configuration storage methodology might change down the road. Going with the above example is WAY better than having the string literal scattered throughout your code.
Enable theTCP/IP connection in SQL Server. So that you can connect remotely from any pc within the network
check here
If your problem is that you embedded your connection string in the code, then you are going to have to do some refactoring. These would be the general steps, you will have to tailor them a bit to your situation.
Add your connection string to the app.config file.
Create a static/shared method that will read the connection string from the
config file.
Do a find and replace in your solution to replace all
of the hard coded connection strings in your code with the (class
and) name of the method that gets the connection string.
This is probably going to be easier than rewriting all of your data calls to use something like enterprise library or EF.
You will need to do as the others suggested, such as changing the connection string and enabling TCP/IP within SQL Server, but you will also likely need to configure your firewall to allow requests to SQL Server (default port of 1433) through.