I'm getting error: Connection must be valid and open when I start this program.
It works fine, but sometimes it happens
There is no problem with connection information and query syntax.
Please Help.
public class Connector : IDisposable
{
private MySqlConnection mySqlConnect;
public MySqlConnection MySqlConnect
{
get { return mySqlConnect; }
}
public Connector()
{
mySqlConnect = new MySqlConnection(DatabaseInformation.ConnStr);
Open();
}
private int Open() // Try Connect
{
try
{
if (mySqlConnect.State == ConnectionState.Closed)
mySqlConnect.Open();
return -1;
}
catch (MySqlException ex)
{
return ex.Number;
}
}
private int Close() // Try Disconnect
{
try
{
if (mySqlConnect.State == ConnectionState.Open)
mySqlConnect.Close();
return -1;
}
catch (MySqlException ex)
{
return ex.Number;
}
}
public void Dispose()
{
Close();
mySqlConnect.Dispose();
}
}
Related
I have an SQL database.
Then in one class I have an ExcelFunction:
[ExcelFunction(Description = "fonction de recherche")]
public static double id(string _isin)
{
double res;
res =DBSQL.Instance.getID(_isin);
return res;
}
Then in anoher class I have my connection and the creation of the singleton pattern (in order to be safe in case of multi-threading). The idea might not be clear, just ask me and I will try to explain. The point is to open a connection (using the singleton pattern), then do the request and then delete the singleton to close the connection.
Here is my code :
public class DBSQL : iAccesDB1
{
private SqlConnection MaConn = new SqlConnection("sefhgoefhouzeyf");
private static volatile DBSQL instance;
private static object syncRoot = new Object();
private DBSQL() {}
public static DBSQL Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new DBSQL();
}
}
return instance;
}
}
public void Connection()
{
MaConn.Open();
}
public void CloseConnection()
{
MaConn.Close();
}
public double getID(String _isin)
{
SqlDataReader rd;
double res = -9999;
SqlCommand cd = new SqlCommand("select cpn from tD where isin='" + _isin + "'", MaConn);
try
{
rd = cd.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
res =double.Parse(rd["cpn"].ToString());
}
}
catch (Exception ex)
{
throw new Exception("1000: " + ex.Message);
}
return res;
}
}
The problem is that it does not work - in my excel cell I have the following: VALUE?
When your Excel-DNA function returns #VALUE to Excel, it probably means there was an unhandled exception.
I suggest you change your top-level function to return an 'object' which returns an error string if there is an exception, like this:
[ExcelFunction(Description = "fonction de recherche")]
public static object id(string _isin)
{
try
{
double res;
res = DBSQL.Instance.getID(_isin);
return res;
}
catch (Exception ex)
{
return "!!! ERROR: " + ex.ToString();
}
}
I'm not exactly sure how to address this issue. I have a mutex that is declared as such:
public class MyNamedLock
{
private Mutex mtx;
private string _strLkName;
public MyNamedLock(string strLockName)
{
_strLkName = strLockName;
//...
mtx = new Mutex(false, _strLkName, out bCreatedNew, mSec);
}
public bool enterLockWithTimeout(int nmsWait = 30 * 1000)
{
_nmsWaitLock = nmsWait;
//Wait
return mtx.WaitOne(nmsWait);
}
public void leaveLock()
{
_nmsWaitLock = 0;
//Release it
mtx.ReleaseMutex();
}
}
Then it is used in an ASP.NET page as such:
public class MyClass
{
private MyNamedLock gl;
public MyClass()
{
gl = new MyNamedLock("lock name");
}
public void funct()
{
try
{
//Enter lock
if (gl.enterLockWithTimeout())
{
//Do work
}
else
throw new Exception("Failed to enter lock");
}
finally
{
//Leave lock
gl.leaveLock();
}
}
}
This code doesn't give me any trouble in my dev environment but in the production it sometimes throws this exception:
Object synchronization method was called from an unsynchronized block
of code.
The description is kinda vague, but just doing the trace I found out that the exception is raised at the mtx.ReleaseMutex(); part. What does it mean and how to fix it?
You have some issues on your class, and on the way you use it.
You must release the mutex only if you have previous locked (and this is your error)
You need to Close and Dispose your opened mutex
Also is better to create it just before you going to use it and not when you create you class MyClass.
So I suggest at first look to change your class as:
public class MyNamedLock
{
private Mutex mtx = null;
private string _strLkName;
// to know if finally we get lock
bool cNeedToBeRelease = false;
public MyNamedLock(string strLockName)
{
_strLkName = strLockName;
//...
mtx = new Mutex(false, _strLkName, out bCreatedNew, mSec);
}
public bool enterLockWithTimeout(int nmsWait = 30 * 1000)
{
_nmsWaitLock = nmsWait;
bool cLock = false;
try
{
cLock = mtx.WaitOne(nmsWait, false);
cNeedToBeRelease = cLock;
}
catch (AbandonedMutexException)
{
// http://stackoverflow.com/questions/654166/wanted-cross-process-synch-that-doesnt-suffer-from-abandonedmutexexception
// http://msdn.microsoft.com/en-us/library/system.threading.abandonedmutexexception.aspx
cNeedToBeRelease = true;
}
catch (Exception x)
{
// log the error
Debug.Fail("Check the reason of fail:" + x.ToString());
}
return cLock;
}
public void leaveLock()
{
_nmsWaitLock = 0;
if (mtx != null)
{
if (cNeedToBeRelease)
{
try
{
mtx.ReleaseMutex();
cNeedToBeRelease = false;
}
catch (Exception x)
{
Debug.Fail("Check the reason of fail:" + x.ToString());
}
}
mtx.Close();
mtx.Dispose();
mtx = null;
}
}
}
This the way you must call that class:
public class MyClass
{
public MyClass()
{
}
public void funct()
{
var gl = new MyNamedLock("lock name");
try
{
//Enter lock
if (gl.enterLockWithTimeout())
{
//Do work
}
else
throw new Exception("Failed to enter lock");
}
finally
{
//Leave lock
gl.leaveLock();
}
}
}
In your finally block you're releasing the mutex regardless of whether you actually acquired it in your try block.
In
try
{
//Enter lock
if (gl.enterLockWithTimeout())
{
//Do work
}
else throw new Exception("Failed to enter lock");
}
finally
{
//Leave lock
gl.leaveLock();
}
if gl.enterLockWithTimeout returns false, you will throw an exception but then try to release the lock in the finally block.
Firstly, am new to C# programming.
I have created a dedicated class to get the connection string from the app.config of a Web Services application in Visual Studio 2010 as per the code below.
On building the code I get the following error via the catch block:
"The name 'connection' does not exist in the current context".
Obviously connection is going out of scope.
How do I avoid this error?
Is the Dispose method being used correctly here?
public class FCSConnection : IDisposable
{
public string GetDefaultConnectionString()
{
string DefaultConnectionString = null;
try
{
DefaultConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection connection = new SqlConnection(DefaultConnectionString);
connection.Open();
return DefaultConnectionString;
}
catch (Exception)
{
if (DefaultConnectionString != null)
{
connection.Dispose();
}
}
return DefaultConnectionString;
}
public void Dispose()
{
throw new NotImplementedException();
}
}
The exact compiler message refers to your catch statement:
connection.Dispose();
Here, connection is an unknown name, because it's declared inside the try block.
As for your entire code, I think it's also wrong. If you want your FCSConnection class to encapsulate the SQL connection, you should declare connection as a private member and then dispose it in your Dispose() method.
public class FCSConnection : IDisposable
{
private SqlConnection connection = null;
public string GetDefaultConnectionString()
{
string defaultConnectionString = null;
try
{
defaultConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
connection = new SqlConnection(defaultConnectionString);
connection.Open(); // are you sure want to keep the connection being opened??
}
catch
{
Dispose();
}
return defaultConnectionString;
}
public void Dispose()
{
if (connection != null)
{
connection.Dispose();
connection = null; // to avoid repeat dispose
}
}
}
try
{
using (response = (HttpWebResponse)request.GetResponse())
// Exception is not caught by outer try!
}
catch (Exception ex)
{
// Log
}
EDIT:
// Code for binding IP address:
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = new BindIPEndPoint(Bind);
//
private IPEndPoint Bind(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
IPAddress address;
if (retryCount < 3)
address = IPAddress.Parse("IPAddressHere");
else
{
address = IPAddress.Any;
throw new Exception("IP is not available,"); // This exception is not caught
}
return new IPEndPoint(address, 0);
}
I could imagine this can happen if you are creating a separate thread within the using block. If an exception is thrown there, be sure to handle it there as well. Otherwise, the outer catch block in this case won't be able to handle it.
class TestClass : IDisposable
{
public void GetTest()
{
throw new Exception("Something bad happened"); // handle this
}
public void Dispose()
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
using (TestClass t = new TestClass())
{
Thread ts = new Thread(new ThreadStart(t.GetTest));
ts.Start();
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Do you have more code after the using? The using needs one statement or a block { } after the using statement. In the example below any exception inside the using statement will be caught with the try..catch block.
try
{
using (response = (HttpWebResponse)request.GetResponse())
{
....
}
}
catch (Exception ex)
{
}
This works fine. You'll see an exception getting printed by the Console.WriteLine()
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
try
{
using (Bar bar = foo.CreateBar())
{
}
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
public class Foo
{
public Bar CreateBar()
{
throw new ApplicationException("Something went wrong.");
}
}
public class Bar : IDisposable
{
public void Dispose()
{
}
}
And if you meant that the exception gets thrown inside the using, this works fine to. This will also generate a Console statement:
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
try
{
using (Bar bar = foo.CreateBar())
{
throw new ApplicationException("Something wrong inside the using.");
}
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
public class Foo
{
public Bar CreateBar()
{
return new Bar();
// throw new ApplicationException("Something went wrong.");
}
}
public class Bar : IDisposable
{
public void Dispose()
{
}
}
The using keyword is the same as try-catch-finally, http://msdn.microsoft.com/en-us/library/yh598w02.aspx. Basically, you have a try-catch-finally nested inside of a try-catch which is why you're probably so confused.
You could just do this instead...
class Program
{
static void Main(string[] args)
{
HttpWebResponse response = new HttpWebResponse();
try
{
response.GetResponse();
}
catch (Exception ex)
{
//do something with the exception
}
finally
{
response.Dispose();
}
}
}
I need to develop a single routine that will be fired each 5 minutes to check if a list of SQL Servers (10 to 12) are up and running.
Is there a way to simply "ping" a SQL Server from C# one with minimal code and sql operational requirements?
I have had a difficulty with the EF when the connection the server is stopped or paused, and I raised the same question. So for completeness to the above answers here is the code.
/// <summary>
/// Test that the server is connected
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>true if the connection is opened</returns>
private static bool IsServerConnected(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}
}
Execute SELECT 1 and check if ExecuteScalar returns 1.
See the following project on GitHub: https://github.com/ghuntley/csharp-mssql-connectivity-tester
try
{
Console.WriteLine("Connecting to: {0}", AppConfig.ConnectionString);
using (var connection = new SqlConnection(AppConfig.ConnectionString))
{
var query = "select 1";
Console.WriteLine("Executing: {0}", query);
var command = new SqlCommand(query, connection);
connection.Open();
Console.WriteLine("SQL Connection successful.");
command.ExecuteScalar();
Console.WriteLine("SQL Query execution successful.");
}
}
catch (Exception ex)
{
Console.WriteLine("Failure: {0}", ex.Message);
}
Wouldn't establishing a connection to the database do this for you? If the database isn't up you won't be able to establish a connection.
For what Joel Coehorn suggested, have you already tried the utility named tcping. I know this is something you are not doing programmatically. It is a standalone executable which allows you to ping every specified time interval. It is not in C# though. Also..I am not sure If this would work If the target machine has firewall..hmmm..
[I am kinda new to this site and mistakenly added this as a comment, now added this as an answer. Let me know If this can be done here as I have duplicate comments (as comment and as an answer) here. I can not delete comments here.]
Look for an open listener on port 1433 (the default port). If you get any response after creating a tcp connection there, the server's probably up.
You know, I first wrote this in 2010. Today, I'd just try to actually connect to the server.
public static class SqlConnectionExtension
{
#region Public Methods
public static bool ExIsOpen(
this SqlConnection connection, MessageString errorMsg = null)
{
if (connection == null) { return false; }
if (connection.State == ConnectionState.Open) { return true; }
try
{
connection.Open();
return true;
}
catch (Exception ex) { errorMsg?.Append(ex.ToString()); }
return false;
}
public static bool ExIsReady(
this SqlConnection connction, MessageString errorMsg = null)
{
if (connction.ExIsOpen(errorMsg) == false) { return false; }
try
{
using (var command = new SqlCommand("select 1", connction))
{ return ((int)command.ExecuteScalar()) == 1; }
}
catch (Exception ex) { errorMsg?.Append(ex.ToString()); }
return false;
}
#endregion Public Methods
}
public class MessageString : IDisposable
{
#region Protected Fields
protected StringBuilder _messageBuilder = new StringBuilder();
#endregion Protected Fields
#region Public Constructors
public MessageString()
{
}
public MessageString(int capacity)
{
_messageBuilder.Capacity = capacity;
}
public MessageString(string value)
{
_messageBuilder.Append(value);
}
#endregion Public Constructors
#region Public Properties
public int Length {
get { return _messageBuilder.Length; }
set { _messageBuilder.Length = value; }
}
public int MaxCapacity {
get { return _messageBuilder.MaxCapacity; }
}
#endregion Public Properties
#region Public Methods
public static implicit operator string(MessageString ms)
{
return ms.ToString();
}
public static MessageString operator +(MessageString ms1, MessageString ms2)
{
MessageString ms = new MessageString(ms1.Length + ms2.Length);
ms.Append(ms1.ToString());
ms.Append(ms2.ToString());
return ms;
}
public MessageString Append<T>(T value) where T : IConvertible
{
_messageBuilder.Append(value);
return this;
}
public MessageString Append(string value)
{
return Append<string>(value);
}
public MessageString Append(MessageString ms)
{
return Append(ms.ToString());
}
public MessageString AppendFormat(string format, params object[] args)
{
_messageBuilder.AppendFormat(CultureInfo.InvariantCulture, format, args);
return this;
}
public MessageString AppendLine()
{
_messageBuilder.AppendLine();
return this;
}
public MessageString AppendLine(string value)
{
_messageBuilder.AppendLine(value);
return this;
}
public MessageString AppendLine(MessageString ms)
{
_messageBuilder.AppendLine(ms.ToString());
return this;
}
public MessageString AppendLine<T>(T value) where T : IConvertible
{
Append<T>(value);
AppendLine();
return this;
}
public MessageString Clear()
{
_messageBuilder.Clear();
return this;
}
public void Dispose()
{
_messageBuilder.Clear();
_messageBuilder = null;
}
public int EnsureCapacity(int capacity)
{
return _messageBuilder.EnsureCapacity(capacity);
}
public bool Equals(MessageString ms)
{
return Equals(ms.ToString());
}
public bool Equals(StringBuilder sb)
{
return _messageBuilder.Equals(sb);
}
public bool Equals(string value)
{
return Equals(new StringBuilder(value));
}
public MessageString Insert<T>(int index, T value)
{
_messageBuilder.Insert(index, value);
return this;
}
public MessageString Remove(int startIndex, int length)
{
_messageBuilder.Remove(startIndex, length);
return this;
}
public MessageString Replace(char oldChar, char newChar)
{
_messageBuilder.Replace(oldChar, newChar);
return this;
}
public MessageString Replace(string oldValue, string newValue)
{
_messageBuilder.Replace(oldValue, newValue);
return this;
}
public MessageString Replace(char oldChar, char newChar, int startIndex, int count)
{
_messageBuilder.Replace(oldChar, newChar, startIndex, count);
return this;
}
public MessageString Replace(string oldValue, string newValue, int startIndex, int count)
{
_messageBuilder.Replace(oldValue, newValue, startIndex, count);
return this;
}
public override string ToString()
{
return _messageBuilder.ToString();
}
public string ToString(int startIndex, int length)
{
return _messageBuilder.ToString(startIndex, length);
}
#endregion Public Methods
}
Similar to the answer offered by Andrew, but I use:
Select GetDate() as CurrentDate
This allows me to see if the SQL Server and the client have any time zone difference issues, in the same action.
Here is my version based on the #peterincumbria answer:
using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
return await dbContext.Database.CanConnectAsync(cToken);
I'm using Observable for polling health checking by interval and handling return value of the function.
try-catch is not needed here because:
I normally do this by open a connection but I had some cases where a simple test via Open caused a AccessViolationException
using (SqlConnection db = new SqlConnection(conn))
{
db.Open(); // -- Access Violation caused by invalid Server in Connection String
}
So I did a TCP check before the open like recommanded by Joel Coehoorn. C# Code for this may be:
string targetAddress = "";
try
{
targetAddress = GetServerFromConnectionString();
IPAddress ipAddress = Dns.GetHostEntry(targetAddress).AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1433);
using (TcpClient tcpClient = new TcpClient())
{
tcpClient.Connect(ipEndPoint);
}
}
catch (Exception ex)
{
LogError($"TestViaTcp to server {targetAddress} failed '{ex.GetType().Name}': {ex.Message}");
}