Check online connection with SQL server, switch to offline C# Windows Application - c#

I have a C# Windows app that I am creating with connection to a MS SQL server. I need the ability to switch to a local instance of SQL Server express if connectivity is down. This app is in a remote area where online is hit and miss. When connectivity goes down, I need the connection strings to reflect to the local server. I have logic to resync items from the local db to the live one once connection is restored. However, I am having issues trying to test connectivity automatically. The connection string in my app.config has both live and offline connections with the following code:
SqlConnection con = new SqlConnection(Properties.Settings.Default.MyLiveConnectionString);
If connection goes down, I want the local connection to use:
SqlConnection con = new SqlConnection(Properties.Settings.Default.MyLocalConnectionString);
Does anyone have a suggestion on how to make this happen seamlessly and quick?
I can test connections using try/catch, but it takes several seconds to time out before continuing.

public void Connect()
{
string connectionStr = string.Empty;
try
{
if(CheckConnection(Properties.Settings.Default.MyLiveConnectionString))
connectionStr = Properties.Settings.Default.MyLiveConnectionString;
}
catch (Exception ex)
{
//Log this, etc...
}
if (string.IsNullOrWhiteSpace(connectionStr))
connectionStr = Properties.Settings.Default.MyLocalConnectionString;
using (SqlConnection conn = new SqlConnection(connectionStr))
{
}
}
private static bool CheckConnection(string connectionString)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT 1", conn);
conn.Open();
if ((int)cmd.ExecuteScalar() == 1)
return true;
}
return false;
}

Related

Cannot connect to SQL Server with Windows authentication from C#

I want to connect to SQL Server 2016 using Windows authentication.
I am using C# with this connection string
Server=192.168.1.12,14331;Database=master;Integrated Security=true;Timeout=30
or
Server=serversql\newinstance;Database=master;Integrated Security=true;Timeout=30
The error is a timeout connection.
When using connection with SQL Server authentication like this:
Server=192.168.1.12,14331;Database=master;User Id=***;Password=****;Timeout=30
everything is ok.
Source code C#
var constr = "<connection string>";
using (var connection = new SqlConnection(constr))
{
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT 1";
command.CommandTimeout = 0;
connection.Open();
command.ExecuteNonQuery();
}
But when I am using SQL Server Management Studio to check connection to the SQL Server instance with Windows authentication, it is ok. Using alias or Ip address does not help the error.
I don't understand why I get this error ...
Help me please! Thanks you everyone!
UPDATE:
If I use connection 1 with IP and port, there is an error:
Login failed. The login is from an untrusted domain and cannot be used
with Windows
UPDATE:
Instance SQL installed on other PC the same network LAN with My PC.
I'm checked Log Viewer on PC install instance SQL but no record log.
I'm not sure it works for you, but you can try it:
SqlConnection cnn;
public connect(){
string strConnect = #"Data Source=192.168.1.12,14331;Network Library=DBMSSOCN;Initial Catalog=master;User ID=****;Password=*****";
cnn = new SqlConnection(strConnect);
try
{
cnn.Open();
}
catch(Exception)
{
// connect failed
}
}
public void ExeQuery(string query){
// query="select * from tblA"
SqlCommand sqlCmd = new SqlCommand(query,cnn);
sqlCmd.ExecuteNonQuery();
sql.Dispose();
}

UWP connection string

I want to create a connection for my UWP and database. I want the uwp to send a value to the database.
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1; uid = root;" + "pwd=root;database=test";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
}
Is this the correct way to write the connection ? and where do I write this part of the coding at ?
enter image description here
Main page or any of my other page ? (scenario 1-3)
Your content looks right, I would try to use 'localhost' rather than ip.
var myConnection = new MySqlConnection();
myConnection.ConnectionString = "database=test;server=localhost;uid=root;pwd=root";
myConnection.Open();
More info see: https://dev.mysql.com/doc/dev/connector-net/6.10/html/P_MySql_Data_MySqlClient_MySqlConnection_ConnectionString.htm
I would also check here to see if you are providing enough info, which you are. https://www.connectionstrings.com/mysql/
In terms of connecting to the database, it depends. What type of application is this? Typically, database connections are made during the start of the application. If you are using Entity Framework, you'll want your Database Context to manage the connection (which is an entirely different topic).

how to monitor SQL client connection number in C#

In C# client side, we can open SQL connections based on connection string. Connection pool is used to improve the client performance.
We want to monitor how many connections are active and how many are free for use, which is very important to client side health check. Unfortunately, I didn't find any way to get this kind of information. Can any one tell me? Or I have to implement it by myself?
You need to have a wrapper class with count variable to monitor count of connection, on connection.Open() increment by 1 and on connetion.Close() decrement by 1.
public static DataTable GetActiveConnections()
{
DataTable objResult = new DataTable();
try
{
using (SqlConnection conection = new SqlConnection("ConnectionSetting"))
{
conection.Open();
using (SqlCommand cmd = new SqlCommand("sp_who", conection))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter adpter = new SqlDataAdapter())
{
adpter.SelectCommand = cmd;
adpter.Fill(objResult);
}
}
}
}
catch (Exception)
{
throw;
}
return objResult;
}
I haven't check it in c# application but i tested it in SQL Server Management Studio

C# console application Invalid Operation Exception

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
namespace BissUpdater
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=H....;
Initial Catalog=LANDesk; Persist Security Info=True;
User ID=Mainstc; Password=xxxxxxxx";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
}
}
}
The SQL Connection threw a invalid operation exception.
"Invalid Operation. The connection is closed".
This is my complete Code. In a other program, it works perfect.
That is the second time, that doesnt work. Im working with VS2005...maybe my program is damaged?
Stacktrace:
at System.Data.SqlClient.SqlConnection.GetOpenConnection()
at
System.Data.SqlClient.SqlConnection.get_ServerVersion()
The correct way doing that should be something like:
static void Main(string[] args) {
string connectionString = "Data Source=H....;
Initial Catalog=LANDesk;User ID=Mainstc; Password=xxxxxxxx";
// removed Persist Security Info=True;
using(SqlConnection con = new SqlConnection(connectionString))
{
if (con.State==ConnectionState.Closed)
{
con.Open();
}
}
}
Using Using Statement it will automatically dispose your SQL connection.
Check this also: Best Practices for Using ADO.NET on MSDN
Other things to do: Use SQL Management Studio and try to use your sql authentication login credential from your connection string and if you have successfully connected to your database using that account the above code should work for you.
Best Regards
The code should read
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
...
}
Try add this code. You probably has open connection and while rerun program you try to again open connection or you have problem with server or your connection string
con.Close();
See there for more info http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx
you can check connection state before opening ittry this :
SqlConnection con = new SqlConnection(connectionString);
if (con.State==ConnectionState.Closed)
{
con.Open();
}
// here your code goes for sql operations
con.Close();
Try to use using statements. Direct manually opening and closing data bases in case of large databases is bad idea.
using(SqlConnection con = new SqlConnection(connectionString))
Try to do like this for open and close connections>>
public DB(string conStr):base()
{
con = new OracleConnection(conStr);
con.Open();
}
public void Close()
{
con.Close();
//con.Dispose();
}
Hope Helpful.
I was having same problem, my solution in VB is:
Dim db As New Database
' ... Some Work with EF without procedures (90 seconds)
db.SaveChanges()
For Each p In list
If db.Database.Connection.State <> ConnectionState.Open Then
' This is only executed 1 time
db.Database.Connection.Open()
End If
' ... Some Work with EF but calling a mapped procedure (1 or 2 seconds each call)
db.MyProcedure(p.FieldId)
Next
db.Dispose()
But the total time was 200 seconds, so I had to change this in my WebConfig of my WebService:
<system.web>
<httpRuntime executionTimeout="600" /> <!--10 min-->
...

Troubles reconnecting to MySQL database from C#

I can successfully log on to the database with this:
MySqlConnection conn = new MySqlConnection();
MySqlConnectionStringBuilder connString = new MySqlConnectionStringBuilder();
connString.Server = textEditServer.Text;
connString.UserID = "root";
connString.Password = textEditServerPassword.Text;
connString.Database = "geysercontrol";
conn.ConnectionString = connString.ConnectionString;
try
{
conn.Open();
Properties.Settings.Default.Properties["ConnectionString"].DefaultValue = conn.ConnectionString;
conn.Close();
}
catch (MySqlException)
{
XtraMessageBox.Show("No connection could be established");
}
But when I try to use the ConnectionString property to reconnect with different class, I get an MySQLException saying
Access denied for user 'root'#'localhost' (using password: NO)
What can be the possible causes to this? The page on possible causes on the MySQL website doesn't include my situation.
The code I use to reconnect is:
connection = new MySqlConnection();
connection.ConnectionString = (String)Properties.Settings.Default.Properties["ConnectionString"].DefaultValue;
connection.Open();
And the connectionString definitely is the same in both cases. It is:
server=localhost;User Id=root;database=geysercontrol;password=password
Add persist security info = true to the connection string I think.
If it were me though I wouldn't put connection string with a password in it in there. If you ever call Save, it will be exposed in the config file.

Categories