I am getting this error:
Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.
Instance failure.
here is my code :
void ConnectToDb()
{
connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = #"(localdb)\MSSQLLocalDB";
connStringBuilder.InitialCatalog = "WRESTLING.MDF";
connStringBuilder.Encrypt = true;
connStringBuilder.ConnectTimeout = 30;
connStringBuilder.AsynchronousProcessing = true;
connStringBuilder.MultipleActiveResultSets = true;
connStringBuilder.IntegratedSecurity = true;
string temp = #"Server=EC2AMAZ-FN5N011\\MSSQLSERVER;Database=C:\APP_DATA\WRESTLING.MDF;Trusted_Connection=True;";
string temp1 = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=C:\APP_DATA\WRESTLING.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(temp);
comm = conn.CreateCommand();
}
When you want to connect to a local database file (.mdf) you can use the following connection string syntax with AttachDbFilename:
#"Data Source=(local);AttachDbFilename=C:\APP_DATA\WRESTLING.MDF;Integrated Security=True;Connect Timeout=30;"
Related
Hi I'm new when it comes to connecting to a server/database and was wondering why this returns an error.
I have a FastHost server with a database.
I've just put in an example IP but i have been using the one given on my control panel on the site.
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012" +
"Initial Catalog = DiscoverThePlanet" +
"User ID = TestUser" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
This returns the
Can not open Connection!" message.
I get the following show in my code:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I know my server is fine because i have connected to it on SQL Server Management studio and added tables and data.
You're missing a couple of ;
conn.ConnectionString =
"Data Source = 123.456.789.012" +
";Initial Catalog = DiscoverThePlanet" +
";User ID = TestUser" +
";Password = Test";
An even better solution is to use ConnectionStringBuilder.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "123.456.789.012";
builder["Initial Catalog"] = "DiscoverThePlanet";
builder["User ID"] = "TestUser";
builder["Password"] = "Test";
Console.WriteLine(builder.ConnectionString);
Or (as #Fischermaen mentioned) you can use the properties, instead of indexes. It's even more readable!
builder.DataSource = "123.456.789.012";
builder.InitialCatalog = "DiscoverThePlanet";
builder.UserID = "TestUser";
builder.Password = "Test";
Also, in this scenario you aren't using any user input, but beware of connection string injection when manually creating your connection string. ConnectionStringBuilder can help you avoid those.
A connection string injection attack can occur when dynamic string
concatenation is used to build connection strings that are based on
user input. If the string is not validated and malicious text or
characters not escaped, an attacker can potentially access sensitive
data or other resources on the server. For example, an attacker could
mount an attack by supplying a semicolon and appending an additional
value. The connection string is parsed by using a "last one wins"
algorithm, and the hostile input is substituted for a legitimate
value.
The connection string builder classes are designed to eliminate
guesswork and protect against syntax errors and security
vulnerabilities. They provide methods and properties corresponding to
the known key/value pairs permitted by each data provider. Each class
maintains a fixed collection of synonyms and can translate from a
synonym to the corresponding well-known key name. Checks are performed
for valid key/value pairs and an invalid pair throws an exception. In
addition, injected values are handled in a safe manner.
A last (and, in my opinion, best) alternative is to move your connectionstring from code into a config. This will make it much easier for you to use the same code in different environments.
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString];
And your config.
<connectionStrings>
<add name="MyConnectionString" connectionString="[ConnectionString goes here]" providerName="System.Data.SqlClient" />
</connectionStrings>
Add a semicolon after each part of your connection string code:
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
https://www.connectionstrings.com/sql-server/ should tell you more about the correct format.
Your connectionstring is not well formated, you forgot some ; :
"Data Source = 123.456.789.012;Initial Catalog = DiscoverThePlanet;User ID = TestUser;Password = Test"
An example :
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
https://www.connectionstrings.com/sql-server/
There are some ';' missing. Try this:
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
Use StringBuilder if you wants to write ConnectionString like mention,
String object it will occupy memory each time.
StringBuilder will occupy memory only once, so it will give you better performance.
SqlConnection conn = new SqlConnection();
StringBuilder sb=new StringBuilder();
sb.Append("Data Source = 123.456.789.012;");
sb.Append("Initial Catalog = DiscoverThePlanet;");
sb.Append("User ID = TestUser;");
sb.Append("Password = Test;");
conn.ConnectionString =sb.ToString();
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
Semi Column is missing in the Connection String. So correct it
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
I want to ask about connection timeout since I have a problem with it.
The error is
"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occured because all pooled connections were in use and max pool size was reached."
Can code like this cause a connection to timeout?
What is best practice to call connection??
using (var cnn = OpenExternalContractor()) //call connection string
{
var query = #"insert into interfaceRequest (requestNo,requestAssemblyName,requestApplicationName,requestFunctionName,
requestParameters,requestUserName,requestUserMail,requestDate)
values (#requestNo,#requestAssemblyName,#requestApplicationName,#requestFunctionName,
#requestParameters,#requestUserName,#requestUserMail,getDate())";
cnn.Execute(query, new
{
requestNo = requestNo,
requestAssemblyName = requestAssemblyName,
requestApplicationName = jobName.Split('-')[0],
requestFunctionName = jobName.Split('-')[1],
requestParameters = requestParameters,
requestUserName = requestUserName.Replace("\"", "\\"),
requestUserMail = userMail
});
//Call another function here that call connection string
PersonnelRepository.UpdateLastNumber(requestNamePrefix, Convert.ToInt32(lastNumber));
}
public static void UpdateLastNumber(string type, int value)
{
using (var cnn = OpenExternalContractor()) //Call connection string
{
var query = "update AutoNumber set LastNumber = " + value + " where Type = '" + type + "'";
cnn.Query<int>(query);
}
}
Here are the code for connection string:
protected static IDbConnection OpenExternalContractor()
{
IDbConnection dbConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ExternalContractor"].ConnectionString);
dbConnection.Open();
return dbConnection;
}
Thanks,
When getting the string of your connection by using WebConfigurationManager.ConnectionStrings["ExternalContractor"].ConnectionString, you can change in your WebConfig file the connection timeout by altering this connection string like this for example :
Data Source=(local);
Initial Catalog=AdventureWorks;
Integrated Security=SSPI;
Connection Timeout=30
From social.msdn.microsoft.com
I'm trying to connect to remote Oracle server. My connection string -
OdbcConnection con = new OdbcConnection();
con.ConnectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
I encountered error saying - "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified" (System.Data.Odbc.OdbcException) Exception Message = "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified", Exception Type = "System.Data.Odbc.OdbcException", Exception WinRT Data = ""
I specified my connection string according to my TNSNAMES.ora
Entry for my DB in TNSNAMES.ora goes like this:
DB.WORLD=
(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST= xxxx)
(PORT=xxxxx)
)
(CONNECT_DATA=
(SERVER=dedicated)
(SERVICE_NAME=abc.domain.com)
)
)
Can someone explain on the error. Please help/suggest if my connection string went wrong and how to connect to Oracle server from my windows application
first install odp.net.managed using nuget packet manager:
Install-Package odp.net.managed
odp.net.managed work without preinstalled Oracle Client
next:
const string connectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
if you have tnsnames.ora in application folder:
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
or if tnsnames.ora in other folder:
Environment.SetEnvironmentVariable("TNS_ADMIN", #"path_to_tnsadmin.ora");
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
you need to use OracleConnection
OracleConnection conn = new OracleConnection(connectionString);
download and install Oracle Data Provider for .NET
Go to Connections Strings for Oracle
Maybe will find some help
Use following Code:
using System;
using Oracle.DataAccess.Client;
class ConnectionSample
{
static void Main()
{
OracleConnection con = new OracleConnection();
//using connection string attributes to connect to Oracle Database
con.ConnectionString = "User Id=scott;Password=tiger;Data Source=oracle";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
Console.WriteLine("Disconnected");
}
}
Source ONE , TWO and THREE
Try something like this class :
public class OracleOperations
{
OracleConnection oraConn = new OracleConnection();
private bool connStatus;
public OracleOperations()
{
connStatus = false;
connect();
}
~OracleOperations()
{
disconnect();
}
public bool getConnStatus()
{
return connStatus;
}
public void connect()
{
string connString = "User Id=xxxx; Password=yyyyy; Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.10.10)(PORT=1583))(CONNECT_DATA=(SERVER=dedicated)(SID=oracledb)))";
if (oraConn.State != ConnectionState.Open)
{
try
{
oraConn.ConnectionString = connString;
oraConn.Open();
Console.WriteLine("Successful Connection");
connStatus = true;
}
catch (Exception eOra)
{
Console.WriteLine(eOra.Message+ "Exception Caught");
connStatus = false;
throw eOra;
}
}
}
public void disconnect()
{
if (oraConn.State == ConnectionState.Open)
{
try
{
oraConn.Close();
connStatus = false;
Console.WriteLine("Connection Closed");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "Exception Caught");
}
}
}
}
I would try Tnsping utility to make sure you can connect via tnsnames.ora
Try putting tnsnames.ora and sqlnet.ora in the same folder of the application and see if that addresses the issue.
With Managed ODP.Net there is one catch it does not support LDAP look up (e.g. LDAP.ora)
I'Ve Created an app.config File and configured the DB entry like this
<configuration>
<configSections>
<section name ="Environment" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<Environment>
<add key ="CIT" value ="Password=pwd123;User ID=abc123;Data Source=db1;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="SIT" value ="Password=pwd234;User ID=abc234;Data Source=db2;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="UAT" value ="Password=pwd345;User ID=abc345;Data Source=db3;Persist Security Info=True;Provider=MSDAORA"/>
</Environment>
</configuration>
Reffered that configuration into my form using ConfigurationManager(Need to refer the assembly - system.configuration). Add namespace - using System.Collections.Specialized to avail NameValueCollection. Code goes like this
environments = ConfigurationManager.GetSection("Environment") as NameValueCollection;
string strConnString = environments[envs];
conn = new OleDbConnection(strConnString);
conn.Open();
OleDbDataAdapter objDa = new OleDbDataAdapter("select * from tblABC", conn);
DataSet ds1 = new DataSet();
objDa.Fill(ds1); dataGridView1.DataSource = ds1.Tables[0];
Using datset, i've populated datagrid using an OleDbDataAdapter. It worked for my Windowsapplication.
I am not able to create a backup of database saved in location like C:\database\mydb.mdf
error : Unable to create a backup
Backup sqlBackup = new Backup();
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "Archive";
sqlBackup.Database = databaseName;
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
//ServerConnection connection = new ServerConnection(serverName, userName, password);
ServerConnection connection = new ServerConnection(serverName);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
string dataBaseName = #"C:\database\mydb.mdf";
string serverName = #"Data Source=.\SQLEXPRESS;Integrated Security=True;User Instance=True";
string destinationPath = "C:\\mydb.bak";
Maybe I am passing wrong variables?
Please can anyone verify it and post me the right solution
thnx in advance.
PS: database is not password protected and can use mixed authentication
First of all - I guess some of your parameters are wrong:
ServerConnection connection = new ServerConnection(serverName);
Here, you need to pass just the server's name - so in your case, do not send in your whole connection string - just .\SQLExpress
As for your database name - I don't know if you can use SMO to backup an "attached" MDF file in SQL Server - normally, this would be the database name (the name of the database only - no file name, no extension) when the database is on the server.
string dataBaseName = #"C:\database\mydb.mdf";
So my suggestion here would be:
attach this MDF file to your SQL Server instance (which you have installed anyway)
give it a meaningful name, e.g. mydb
then use just the database name as your value here:
string dataBaseName = "mydb";
With these points in place, your code does work just fine in my case, at least...
TextBox1=Server Name
TextBox2=Db Name
TextBox3=User Name
TextBox4=Password
I declared as a variable "Server Name,dbname,user name,password".My question is; I want to test my sql connection on another machine by them using.
How can I do that with c#?
//// SqlConnection conn = new SqlConnection
////("Data Source="+ server +";Initial Catalog=DATA;Persist Security Info=True;User ID=sa");
You could use the SqlConnectionStringBuilder for this scenario:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = TextBox1.Text.Trim();
builder.InitialCatalog = TextBox2.Text.Trim();
builder.UserID = TextBox3.Text.Trim();
builder.Password = TextBox4.Text.Trim();
string result = builder.ConnectionString;
This builds up the connection string and returns it as a result in the end.
Also: you might want to use more descriptive names for your textboxes! tbxDataSource, tbxInitialCatalog etc. would be much better than TextBox1, TextBox2 etc.
little modified pranay's answer
bool TestConnection()
{
SqlConnection conn = new SqlConnection(string.Format(#"user id={0}; password={1};Data Source={2};
Trusted_Connection=yes;
Initial Catalog={3};
connection timeout=30", userName,password,serverName,database));
try
{
conn.Open();
return true;
}
catch (Exception e)
{
return false;
}
}