C# Connecting to a SQL server with a named instance? - c#

A client of mine has told me the program I made for them won't connect to a SQL server named instance, I have a standard SQL server with no named instance so I'm wondering how I can test this. A named instance connection string look like the one below, could the backslash be were my code fails?
Driver={SQL Native Client};Server=myServerName\theInstanceName;Database=myDataBase;
My code is as follows:
sqlServer=s.Substring(keyword.Length,s.Length-keyword.Length);
FormODBC formODBC=new FormODBC(this);
formODBC.SetSqlServer(sqlServer,dbUsername,dbPassword,database,table);
formODBC.ReadData();
How should I handle the backslash as I suspect this may be the problem?
Thanks

We have SQL servers with named instances.
Examples: myservername\sql2005.
Backslash is fine, in the conection string server name will be "myservername\sql2005", works 100% fine. You can have a "regular instance" on the same server, will be "myservername"
PS just unit test your function making connection string returns "myservername\sql2005".

Also, remember that backslash is an escape character in C# strings. If your instance name is contained in a string variable, make sure you do either:
string server = "myServer\\myInstance";
or
string server = #"myServer\myInstance";

The answer is to ensure your connection string is configurable, and set it to something like:
data source=localhost\msexpress;database=dbname;trusted_connection=true;

There is also the occassional SQL Express edition case where the name is MyServerName\SQLEXPRESS. This can trip up some people because they wouldn't think to specify the server that way.

You can extract your connection string to a config file (note this isn't necessarily secure - that will depend on how their SQL security server is set up and the account your application is running under) - then your client can just add the appropriate connection string for their server to your application's config when deployed.
Notes:
You can create a connection string by renaming a .txt file to a .udl file and running through until you can connect to your/their server.
Your unamed instance can actually be accessed by name - the machine name on which the SQL server is installed

Scott,
At the risk of stating the obvious, have you tried setting up a named instance in your own development environment? I don't actually know the answer to your question but I've never personally run into a solution where testing the scenario that is failing directly didn't help. At a minimum you ought to be able to get better debugging information as to precisely what is failing. Good luck getting this resolved.
Regards,
Chris

Related

Database Connection in C#

Is there a way/code where I can use that won't require me to change my connection string everytime I move my project to another computer?
been using 2 computers with different server names, but with the same database.
PC1:
static string ConnStr = "Server=DESKTOP-Q0BI1S3;Database=ISPROJ2;Trusted_Connection=True;";
PC2:
static string ConnStr = "Server=DESKTOP//SEGUERRA;Database=ISPROJ2;Trusted_Connection=True;";
tried using: Server=(localdb)
Update: used localhost and (local) with PC1 worked fine, but these won't work with PC2
see img
I am not sure if this will work for you, but where I work everyone has their own local instance of sql server and each developer are using the db on localhost. We solve this problem by referencing the database as a dot (localhost).
"Server=.;Database=ISPROJ2;Trusted_Connection=True;"
This solution only works if all developers have their db installed as the default instance.
See here.
This may be the solution you are looking for. Use the hostname and append it to the connection string.
I also believe you may be able to use server=localhost;
You could make one computer work as a server and connect to it everytime with same connection string.
This might help you:
https://technet.microsoft.com/en-us/library/ms175483(v=sql.105).aspx
There are probably lots of libraries to solve this, but the simplest way you can do interim is to within the software identify which computer the software is run on:
static string GetConnectionString()
{
switch(System.Environment.MachineName)
{
case "PC1": //TODO:Change this to the actual machine name!
return "Server=DESKTOP-Q0BI1S3;Database=ISPROJ2;Trusted_Connection=True;";
case "PC1": //TODO:Change this to the actual machine name!
return "Server=DESKTOP//SEGUERRA;Database=ISPROJ2;Trusted_Connection=True;";
}
}
You can also make it more dynamic by reading it from the web.config/app.config:
static string GetConnectionString()
{
return ConfigurationManager.AppSettings["ConnectionString_" + System.Environment.MachineName];
}
This makes it more dynamic, and you can simply add a new connection string onto the web.config/app.config once it needs to run on a new environment.
<appsettings>
<add key="connectionstring_pc1" value="[pc1connectionstringhere!]"/>
<add key="connectionstring_pc2" value="[pc2connectionstringhere!]"/>
</appsettings>
You will find all SQL Server connection string options here.
https://www.connectionstrings.com/sql-server/
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;

SQL Server connection string specified without a computer name? How can that be?

I'm working from a code base I downloaded from a repository, and it is likely that I'm missing a system or local setting.
In Web.Config, I have this connection string:
<add name="Context"
connectionString="Data Source=InstanceName;
Initial Catalog=MyProduct;
Integrated Security=True;
Connect Timeout=15;
Encrypt=False;
TrustServerCertificate=False"
providerName="System.Data.SqlClient" />
(indentation mine)
Normally I would have expected the Data Source to be \\ComputerName\InstanceName or at least .\InstanceName if the SQL Server is on the same host. But here, nothing. The initially uploaded project had a local database, on the developer's machine. I can get the connection to work if I add .\, but I don't understand how only specifying the instance name can work. So, how can it?
The instance name is needed only if you want to connect to a named instance.
If your install of Sql Server hasn't created a named instance then the default for the instance is MSSQLSERVER and you DON'T need to specify that part on the connection string.
However, the computer name part is required but it could be expressed in various form
a point to mean the local computer
an IP address (local or not)
a server name recognized by the DNS system of your lan
the special string (LOCAL)
More info on the Data Source key could be found on MSDN docs for ConnectionString
Could it be that the InstanceName is the name of an ODBC Data Source that already has the target server configured, and the other employees have a corresponding ODBC data source set up?
The other option is that the connectionstring is modified before being passed to a data connector, so "MyMachineName" + connectionstring is happening somewhere (perhaps to separate production and development environments?
Also, double check the App_Data folder to make sure some sort of file-based database isn't being accessed.
In addition to what #Steve has already mentioned local or current machine can also be referred by a special string localhost. Please refer to below post:
What is the sql connection string I need to use to access localhost\SQLEXPRESS with Windows Authentication or SQL Authentication?

Access denied for user 'root'#'localhost' (using password: YES) in Visual Studio

Kindly bear with me. I am a Microsoft SQL Server person with loads of Visual Studio experience, but I need to get something done using a MySQL database.
I am trying to create a little tool here that will allow our developers to quickly update database records, and I am using Visual Studio to create a small Windows Form to do this.
In a Microsoft SQL Server connection string, I could write something like this:
Server=myServerAddress;Database=myDataBase;User Id=username;Password=password;
In a MySQL connection string, there appear to be multiple other options, but the first one looks basically the same:
Server=myServerAddress;Database=myDataBase;Uid=username;Pwd=password;
When I attempt to open the MySQL connection from my PC, I get the exception listed in the title (actually, it shows the Uid value and the IP Address of my PC instead of localhost, but I am hoping more people will recognize the error easier this way):
public static void MySQLi_Connect() {
m_err = null;
var str = Properties.Settings.Default.ConnStr;
try {
m_conn = new MySqlConnection(Properties.Settings.Default.ConnStr);
m_conn.Open();
} catch (MySqlException err) {
ErrorLog("MySQLi_Connect", err);
}
}
I did a search, and it seems that the Uid on MySQL needs to be granted access from the specific IP Address that the connection is being made from.
Further, I found this on the mysql.com doc pages:
If you do not know the IP address or host name of the machine from which you are connecting, you should put a row with '%' as the Host column value in the user table. After trying to connect from the client machine, use a SELECT USER() query to see how you really did connect. Then change the '%' in the user table row to the actual host name that shows up in the log. Otherwise, your system is left insecure because it permits connections from any host for the given user name.
A few things:
It looks like I can connect to MySQL by using a % setting in the Uid jp2code, but MySQL says I need to change that back right away to remove system vulnerability.
Microsoft SQL Server did not seem to require this - or, if it did, I simply never was slapped in the face with this vulnerability issue like MySQL is doing.
Now, I ask:
If this is going to be a tool used by different developers on different PCs, is it common practice to turn the blind eye to this horrendous system vulnerability?
Is this not really as big of a concern as MySQL is making it appear?
What is the best way to continue with a Windows Forms application that needs to connect from various locations? Obviously, I do not want to continuously be adding more entries for a particular application every time another developer wants to use the tool or someone tries to run it from a different PC.
You can configure the security of your MySQL server as strong as you like, usually you dont connect users but applications. So if you have your root user without password in production environment is your fault. Usually developers have access to development environment, so this is not a big deal.
Of course try to have as many users as roles you need, for your example I think one user is enough. In production use a secure config file for save a secure password and set you mysqlserver restricted.
I was having the same issue and I found out that the password wasn't correct.
GO to your sql command line and type the code below:
mydb in the line below is the name of the database you are working on.
passwd in the line has to match the password you have in c# code so in your case "password"
grant all privileges on mydb.* to myuser#localhost identified by 'passwd';
Like OP says you can wildcard the hostname portion. I used this on our dev-server (not recommended for production servers):
update mysql.user set host = '%' where host='localhost';
Then I had to restart the server to make MySQL use it (propably I could just have restarted the MySQL service).

Cheat application to connect to different SQL Server database

At work I wrote an application that processes data from a SQL Server database and outputs it in file format.
Now I need to use it at home and since app has hard-coded connection string I've got a problem. I got a copy of database at my company, the original database is inaccesable from the outside of the company.
Connection string format looks like this
Data Source=serverName-01;Initial Catalog=dbName_01;Integrated Security=True;Pooling=False
I've tried to cheat app by editing windows hosts file:
serverName-01 127.0.0.1
But it did not work. Is there a way to make it work without going to work and editing source code ?
Lesson learned hard way - never hard-code connection srings :<
To do this you can use an alias defined in SQL Server Configuration manager. Create an alias for your local instance that has the exact same name as the one in the connection string.
Have a look at the following article for how to do this (it's pretty simple):
Create or Delete a Server Alias for Use by a Client (SQL Server Configuration Manager)

C# DBMLs and SQL Server

My dev machine has SQL Server 2005 on it and that is how I make my DBML file and define the tables in there and then make a WCF Service. When i go to host the WCF service, the server has SQL Server 2000, it finds the connection string fine but not the table im pointing it to. Is there a way to tell through the web.config file which SQL Server i am using at run time?
Thanks
sure, that's what the connection string is for, are you sure you have the right permissions on the server?
The name of the server and database should be in the connection string (in the config file); what does it currently look like? And what is the exact error message.
The exact connection string depends on your setup (for example, is the server a "named instance"?).
The other thing I can think of... are the objects in the right schema? i.e. are they "daniel.sometable" on your machine, but "dbo.sometable" on the server? This matters, since the dbml includes the schema. Fortunately, you can edit the dbml (it is just xml) and use "replace all" (i.e. ctrl+h) to fix this...

Categories