Sharing SQL Server Between Multiple System - c#

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.

Related

What Is the Syntax for Including the Service Name in a Connection String?

I have a C# ASP.Net MVC web application. I am trying to successfully connect to an Oracle database.
I am getting a "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor" error.
I do not have access to the server the database is on. But I do have access to Oracle SQL Developer, which I have installed on my machine.
In my C# code I am setting the connection string like this:
ConnectionString = "DataSource=XXX.XX.XXX.XXX/abcd,1521;User ID=userid;Password=password;";
abcd should be the service name. and 1521 is the port number.
I understand that my connection string might not be the cause of the error, but I want to rule it out. Also, I know the more proper way of doing things is probably to set the connection string in web.config and retrieve it as needed, but I am doing it this way just for ease of testing until I know I am able to connect to the database successfully.
What is weird to me, is that I was able to connect to the database using Oracle SQL Developer using the same IP address, port number, service name, username, and password I am using in my connection string.
Primarily, I would like help knowing if my connection string looks valid. If you have additional thoughts about what the issue could be, that would also be appreciated.
using this command in Oracle SQL Developer:
select sys_context('userenv','service_name') from dual;
I am able to determine that the service name I am using in my connection string is one that exists, although I guess this does not guarantee that the service is up.
I am not a DBA by any means. In fact, I am still new to .Net and web development in general, but I have been assigned to troubleshoot this issue. Any help is appreciated.
I don't recall seeing the following format
DataSource=XXX.XX.XXX.XXX/abcd,1521
as valid (which doesn't mean its not, I've just not seen it).
The more common ones I've seen are:
DataSource=XXX
where XXX is a reference to your tnsnames.ora file
DataSource=//nnn.nnn.nnn.nnn/service_name
DataSource=//nnn.nnn.nnn.nnn:port/service_name
So maybe try those variants and see how you go. There's also more definitive list of alternatives at https://www.c-sharpcorner.com/UploadFile/nipuntomar/connection-strings-for-oracle/
I ended up figuring this out. My connection string format I don't t think was correct. I changed it to be:
ConnectionString = "DataSource=XXX.XX.XXX.XXX/abcd;User ID=userid;Password=password;";
Basically, I just took off the port number. In my case, the default port was what I needed anyway. Not sure what I would have done had I needed to specify the port number.
As new to Oracle I struggled a few days finding solution to this
this article helped me alot
As of Oracle 21 c
This is my Connection string for C#
Password=dev;Persist Security Info=True;User ID=Dev;Data Source=localhost:1521/XEPDB1
Keep in mind Dev is Username which is also the Schema name for Oracle

How to add connection string to once for whole solution to use?

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.

How to create dynamic database connection string C#

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)

How to create exe file with database in c# to run on client machine

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.

Getting SQL Connection fragmentation, different way to connect to DB's

We have multiple DB servers. On one of the servers we have a master config table that holds instructions as to what DB server and DataBase name an Agency is supposed to use.
Currently each Database always has 2 connections on them, even if they're not being used (which we are fixing). However, we're trying to find a way to make it so our connections are not all over the place, and relieve some of the stress on our DB Servers.
After a lot of research we found some articles saying to do all connections to a central location, and then Change which database we're using through the SQLConnection object. Which seems a bit roundabout, but could work.
So I'm wondering what others do in this situation?
The current path for this is:
-User Logs in
-System access ConfigTable to find out which database user is going to connect to.
-System loads the Agency connection settings into memory (SEssion) for that user.
-Every request now directly hits that users database.
Is there a more efficient way of doing this?
Open connections late, and close them early.
For example:
string result;
using (var con = new SqlConnection(...))
{
con.Open();
var com = con.CreateCommand();
com.CommandText = "select 'hello world'";
result = com.ExecuteScalar();
}
The Windows OS will make sure to efficiently pool and reuse connections. And since you're only using connections when you need them, there are no idle connections lying around.
EDIT: Windows only caches connection strings that are literally the same, so if you use Initial Catalog=<dbname> in the connection string, that could hurt performance by requiring 500+ "connection pools" for one server.
So if you have 4 servers with a lot of databases, make sure you only use 4 connection strings. After connecting, switch database with:
com.CommandText = "use <dbname>";
com.ExecuteNonQuery();
Or query with a three-part name like:
select * from <dbname>.dbo.YourTable

Categories

Resources