Monitoring and SQL Server Connection by leaving the connection open - c#

I'm trying to monitor an SQL Server database connection and I'm either having issues or it's behaving as designed.
I would like to do this:
Open Connection
Write "Open"
Leave it open for 1 minute (using System.Threading.Thread.Sleep)
If the connection drops during this time write "Down" to the console
Close the connection
Write "Closed" to the console
Repeat forever
So with my SQL Express service started I start my code I get
Open
Closed
Open
Closed
(with the appropriate amount of time between)
Then right after I see "Open" again I stop my SQL Express service the next few lines I get are still
Open
Closed
Open
Closed
Now if I restart my program while the SQL Express service is stopped then I get the proper exception.
Here is my code.
static void Main(string[] args)
{
//
string strConnectionString;
string strEnabled;
string strPath;
strConnectionString = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\GlobalNet Direct\\DatabaseMonitor", "ConnectionString", false).ToString();
strEnabled = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\GlobalNet Direct\\DatabaseMonitor", "Enabled", false).ToString();
strPath = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\GlobalNet Direct\\DatabaseMonitor", "LogPath", false).ToString();
do
{
strEnabled = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\GlobalNet Direct\\DatabaseMonitor", "Enabled", false).ToString();
//System.Threading.Thread.Sleep(15000);
SqlConnection myConnection = new SqlConnection(strConnectionString);
try
{
myConnection.Open();
Console.WriteLine(myConnection.State.ToString());
System.Threading.Thread.Sleep(1000);
}
catch (Exception)
{
Console.WriteLine("Down");
}
try
{
if (myConnection.State.ToString() == "Open")
{
myConnection.Close();
System.Threading.Thread.Sleep(1000);
Console.WriteLine(myConnection.State.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}while (strEnabled == "True");
}

Related

Access 2016 DB does not seem to connect correctly

I'm new to c# and im trying to make a store bill generator for fun and learning. Since I don't know much about databases Access seemed decently simple.
I'm just trying to give user confirmation that the connection to the db is successful, I've connected the db to my project but when I run the program nothing happens
I've tried giving the status in a label but it doesn't show either.
availableproductsbox is a listbox
private void availableproductsbox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\source\repos\MultiCashTrack\MultiCashTrack\items.accdb;
Persist Security Info=False;";
connection.Open();
MessageBox.Show("Database connected");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Database connection failed"+ ex);
}
}
I expect it to show a message box showing "Database connected" but it doesn't show

failed to connect to database using c#

I want to ask about connecting db with c#.
I have read http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm and written my code, but the connection doesn't seem to be working.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=localhost;Initial Catalog=dbabc;User ID=admin;Password=qwerty";
sql = "UPDATE ppd,brg,cmp SET WHERE";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
MessageBox.Show(dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
}
dataReader.Close();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Did I write something wrong? The error message shown always says "Can not open connection"!
The Exception thrown should be a SqlException. Check the ErrorCode on the SqlException and look it up here...
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-develop-error-messages
Rather than catch(Exception ex) your code should do this...
try
{
connection.Open();
....
connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show($"Can not open connection ! ErrorCode: {ex.ErrorCode} Error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Can not open connection ! Error: {ex.Message}");
}
I think you should check server name
if you install SQL server (Standard) on your computer, server name named is (local) or .
If you are using VS create a data source and test the connection string. Go to data> Add new data source. There is find your database server and create the correct string.
Your code is working. I can verify it. Please check your connection string and SQL query. Especially your SQL query. It seems to be wrong.
Try to execute the query in Microsoft SQL Server Management Studio. If there is an error in your query, you can easily find it there.
SQL Update Syntax
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Recommended Readings
https://www.tutorialspoint.com/sql/sql-update-query.htm
https://www.w3schools.com/sql/sql_update.asp
To verify the connection string,
Open the Server Explorer pane. ("View" menu, "Server Explorer" or
use the key shortcut CTRL+Alt+S).
Right-click on the Data Connections, Select Add connection and then
press continue after selecting Microsft SQL Server as the Data source.
Select Refresh and click down arrow and then select your SQL server.
If you cannot find it, enter the server name manually.
You may also have to enter the SQL server credentials.
Select or enter your database name & then press Test Connection.
If you see a Test connection succeeded message, then your SQL server is working.
If you want, you can also get connection string by pressing Advanced.. button and then copying the connection string
In addition, try to an add exception message to catch block. That way, you can easily find the error.
MessageBox.Show("Can not open connection ! \n" + ex.Message);

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

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;
}

Protocol error in TDS stream - error

We have two servers. An application server and a SQL server.
When running this simple program from the application server:
static void Main(string[] args)
{
OleDbCommand cmd;
OleDbConnection cnn;
string connectionString = "Provider=SQLNCLI10;Integrated Security=SSPI;User ID=***;Password=***;Persist Security Info=False;Initial Catalog=MCS_BATCH;Data Source=CD6S01;Initial File Name=;";
string sql = "EXEC [msp].[MasterMSP] #BTYPE = N'B_PVM_KNN', #AC_KEY = NULL, #RUN_TS = '2014-05-02 17:29:31.1400555', #CHUNK_ID = 8794";
System.IO.StreamWriter file = new System.IO.StreamWriter("MasterMSP_output.txt");
cnn = new OleDbConnection(connectionString);
try
{
cnn.Open();
cmd = new OleDbCommand(sql, cnn);
try
{
OleDbDataReader reader = cmd.ExecuteReader();
int numberOfFields = reader.VisibleFieldCount;
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
for (int i = 0; i < (numberOfFields - 1); i++)
{
file.Write(reader[i].ToString());
}
file.WriteLine("");
}
file.Close();
}
catch (Exception ex)
{
file.Write("Execption ex at : {0}", System.DateTime.Now);
file.Write(ex.Message.ToString());
Console.WriteLine("Exception ex time is : {0}", System.DateTime.Now);
throw;
}
cmd.Dispose();
cnn.Close();
}
catch (Exception exx)
{
file.Write("Execption exx at : {0}", System.DateTime.Now);
file.Write(exx.Message.ToString());
Console.WriteLine("Exception exx time is : {0}", System.DateTime.Now);
throw;
}
}
We get - after some time - a "Protocol error in TDS stream" error:
We ran a network trace, and we can see that the "TCP Window size" is decreasing after 10 mins and then it's sending a TCP Window size = 0 (close window).
This means that the SQL server can't send more data until it has gotten a update window size, bigger than 0, from the application server.(right?):
The SQL server is trying to send 1 byte keepalive, but the application server is never responding. (The problem is that the application server never raise TCP Windows Size again. At the end the application server is terminating the session.)
We except that it's the application server fault and it could be that the networks buffer is not being empty(flushed) anymore. The only thing the TCP stack can do is to close the TCP Windows Size until the application again empties the buffer - but it never does that.
Any hints, ideas on what the issue can be?
The problem actually came up in 3rd party program. This program is calling a stored procedure on the SQL server. So I just tried to reproduce the logic in a C# program and was able to reproduce the error.
Any help, ideas or comments are highly appreciated.
Thanks
Adding this to the connectionstring fixed the error: MARS Connection=True
Link

Object reference not set to an instance of an object with inserting data into database

I created a connection with a Microsoft sql database and am trying to add basic informastion as part of an exercise but get the following error.
Object reference not set to an instance of an object
This is how I connect to the database
SqlConnection sqlConn;
protected void butConnect_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=lrmg;Integrated Security=True;";
sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
labMessage.Text = "a connection to your database was established";
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
Here is where I get the error
protected void butSubmit_Click(object sender, EventArgs e)
{
try
{
string name = txtName.Text;
string date = txtDate.Text;
**SqlCommand cmd = sqlConn.CreateCommand();**
cmd.CommandText = "INSERT INTO Canditate(Name, Doj) VALUES('" + name + "'," + date + ")";
cmd.ExecuteNonQuery();
labMessage.Text = "The value was inserted into your database";
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
}
I am under the impression that the sql connection was opened so why the exception?
You are getting the error because reference variable sqlConn is null - that is happening probably because
From you code snippet, connection is getting created and opened in
connect button click. So you need to hit connect before submit
Most likely cause is probably different assuming that this ASP.NET code - in such case, every request is served by different instance of page class - so if you open connection on one request (connect click), it (that variable) won't be available in next request (submit click). The remedy is simple - create and open connection when you need it i.e. in submit click. On the other hand, you probably need to understand mode about web programming models to avoid such mistakes.
You use two different events to do your work on the database. Why? Have you ever heard of connection pooling?
Probably between the first event (open connection) and second event (db insert) something happens and change your global variable SqlConn to null and you get the error. (Of course I am assuming that you press that button to open the connection before trying to insert anything)
With connection pooling this kind of programming pattern is no more necessary, instead, when you need to update/insert/delete/select something you open the connection, do your work and close immediately the connection without keeping it open and consuming resources on the server and client side.
try
{
string connectionString = "Data Source=.\\SQLEXPRESS;" +
"Initial Catalog=lrmg;Integrated Security=True;";
using(SqlConnection sqlConn = new SqlConnection(connstring))
{
SqlCommand cmd = sqlConn.CreateCommand();**
cmd.CommandText = "INSERT INTO Canditate(Name, Doj) VALUES(#name, #dt)";
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#dt", Convert.ToDateTime(txtDate.Text));
cmd.ExecuteNonQuery();
labMessage.Text = "The value was inserted into your database";
}
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
Notice also that your code is subject to Sql Injection attacks because you use string concatenation to build your sql text. This is a bad practice that should be avoided at all costs
You should have a dedicated method to open the connection, that you'd invoke every time you're using the connection. With your current setup, butConnect_click MUST be called before butSumbit_Click in the same request. So add the call to butConnect in butSubmit.

Categories