C# Cassandra Datastax driver - Handling failed connection - c#

Is there any way to catch the connection exception thrown by the datastax cassandra driver for C#? It usually works fine, but the catch block does not execute when the remote host is down (that is, when a NoHostAvailableException is thrown). The debugger only halts and indicates the exception at Connect().
try
{
cluster = Cluster.Builder().AddContactPoint("<ip address>").Build();
session = (Session)cluster.Connect();
}
catch (NoHostAvailableException ex)
{
//Never executes
}
catch (Exception ex)
{
//Never executes
}

Found the fix, Visual Studio has a checkbox where you can choose whether or not you want to break on a certain exception (regardless of a try/catch), unchecking that solved everything.

Related

How do I tell apart a read error from a write error in a socket?

I am creating a server for a game that deals with lots of TCP connections, and I need to deal with a sudden loss of connection (pc crash, game process killed, internet connection lost, ectect). The problem I currently have is that I can't tell apart a read error from a write error since both throw an IOException. even the underlying exception is the same (SocketException), the only difference being that one occurs on Socket.Send() and the other on Socket.Receive() respectively. I could of course compare the exception message, but that would become a problem as soon as the system language changes (and lets be honest, that would be a pretty messy approach anyway).
I tried comparing the Hresult but since the underlying exception is the same, so is the Hresult. I also tried getHashCode() but this one changes from player to player.
Any other ways I could tell apart those 2 situations?
To clarify, we're talking about the exception that comes up when using TcpClient.read() or TcpClient.write() on a TcpClient whose connection has been unexpectedly closed.
You could try wrapping the send and receive functions in a try-catch block, and use the Data property to tell exceptions from read and write apart:
enum ReadOrWrite { Read, Write }
void Foo()
{
try
{
socket.Receive();
}
catch (IOException ex)
{
ex.Data.Add("readOrWrite", ReadOrWrite.Read);
throw;
}
}
And this is where you later catch it:
try
{
Foo();
}
catch (IOException ex) when (ex.Data.Contains("readOrWrite"))
{
var readOrWrite = ex.Data["readOrWrite"];
}

prevent application crashes when sending data over a closed websocket connection

The ASP.NET Core application uses websocket connection on the client side and Microsoft.AspNetCore.WebSockets.Server 0.1.0 (latest stable version on nuget as I know) on the server side. The simple sending code is
await _ws.SendAsync(new ArraySegment<byte>(arrbr), WebSocketMessageType.Text, true, ctk);
the problem is this line throws error when it is a closed connection. I would like that method to return a Boolean if process was successful. I already check if the connection is open like this:
_ws.State == WebSocketState.Open
But this does not work if user has
unplugged the network cable or disconnected his device(almost all situations except closing the browsers).
As an extra, I do not know how to simulate network connection loss for one of two clients and I suppose WebSocketState is readonly, please warn me if I am wrong and I do not think shorter pings will solve this problem.
I have two ideas:
I may use the sender code in a try catch block. (I am not comfortable with using try catch in production code)
I may set interval on the client side, and ask the server like "what is new for me". I feel bad with this because it is away from being a websocket(closer to http).
Is there any way to fix this without using try catch? I know that this is not a qualified question but a qualified problem for me. I can share full code if needed.
Update 1
after using server-side logging:
While messaging is working well in production environment, I disconnect the client by unplugging the network cable and send data to the client. I use try catch and no catch. then i get this error.
This means I cant detect lost connection by using try catch. and i think i can solve this by handling this throw.
How can I handle this error?
update2
I have noticed that "Exceptions from an Async Void Method Can’t Be Caught with Catch" and "it's possible to use await in catch" since c# 6 link however I can not catch the throw. I may try running synchronously await _ws.SendAsync(new ArraySegment<byte>(arrbr), WebSocketMessageType.Text, true, ctk).runsynchronously(); if I cant fix in this way
update3
running synchronously does not help. using try catch does not differ. as a result question, asp.net core websocket how to ping
update4
my log file when using Microsoft.aspnetcore.websockets.server 0.1.0
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HL1940BSEV8O": An unhandled exception was thrown by the application.
System.IO.IOException: Unexpected end of stream
at Microsoft.AspNetCore.WebSockets.Protocol.CommonWebSocket.<EnsureDataAvailableOrReadAsync>d__38.MoveNext()
my log file when using Microsoft.aspnetcore.websockets 1.0.0
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HL19H5R4CS21": An unhandled exception was thrown by the application.
System.Net.WebSockets.WebSocketException (0x80004005): The remote party closed the WebSocket connection without completing the close handshake. ---> System.IO.IOException: Error -4077 ECONNRESET connection reset by peer ---> Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvException: Error -4077 ECONNRESET connection reset by peer
I might be missing something, but why can't wrap the sending operation in a method that returns bool in the following manner:
private async Task<bool> DoSend()
{
bool success = true;
try
{
await _ws.SendAsync(new ArraySegment<byte>(arrbr), WebSocketMessageType.Text, true, ctk);
}
catch (Exception ex)
{
// Do some logging with ex
success = false;
}
return success;
}
I also suggest reading about Async All The Way, it should clear some of the confusion with async void, async Task and async Task<T>
Until C# 6.0 to capture an exceptions from async methods you should use the ExceptionDispatchInfo type. Then the code will look like this:
private async Task<bool> DoSend()
{
bool success = true;
ExceptionDispatchInfo capturedException = null;
try
{
await _ws.SendAsync(new ArraySegment<byte>(arrbr), WebSocketMessageType.Text, true, ctk);
}
catch (Exception ex)
{
capturedException = ExceptionDispatchInfo.Capture(ex);
}
if (capturedException != null)
{
await ExceptionHandler();
if (needsThrow)
{
capturedException.Throw();
}
}
success = capturedException == null;
return success;
}

C# Try-catch does not catch the exception

I have a confusing problem and I could not any way to workaround it. I have a couple of lines of codes, and at some point, the Send function throws a System.Net.Sockets.SocketException. However, even though try has the catch block, it does not catches the exception and continue with normal flow. When I try to run the case where it needs to throw same exception, catch captures it pretty well.
Things I have tried:
Trying to change VS debugging settings 'Enable Only For My Code', but
it is already disabled.
I tried to both Debug and Release modes.
I tried using general Exception catcher, but none of them worked.
Here is the code, at some point, the connection from the server closes and the c Socket disconnects. It returns the System.Net.Sockets.SocketException, but below catch does not capture it.
try
{
// Some code here . . .
c.Send(clientData);
Print("Started uploading the file " + uploadFilename + ".");
upBox.Text = "";
Print("Finished uploading the file " + uploadFilename + ".");
}
catch (System.Net.Sockets.SocketException)
{
Print("You are disconnected from server!");
}
The reason you're not getting an exception ...
... is that no exception has occurred!
TCP/IP itself won't necessarily "notice" a disconnect ... unless you explicitly try to write to a closed socket.
Definitely check out Beej's Guide to Network Programming:
http://www.beej.us/guide/bgnet/.
See also:
http://stefan.buettcher.org/cs/conn_closed.html,
How to detect a TCP socket disconnection (with C Berkeley socket)

Too Many Connection Error in mysql

i Have one C# desktop application that connects mysql database sever.
The applicaiton runs well but after some time or some days it gives an exception like:
9/16/2013 12:56:55 PM: 9/16/2013 12:56:55 PM: Exception Occurred. Too many
connections.StackTrace: at MySql.Data.MySqlClient.MySqlStream.OpenPacket()
at MySql.Data.MySqlClient.NativeDriver.Authenticate411()
at MySql.Data.MySqlClient.NativeDriver.Authenticate()
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at ReckonHelper.MySqlDatabaseConnection.ConnectDB().
I don't know why it is being happen??
Any Solution For this?
Close the connection once you have complated the execution of SQL statements.
Use try..catch..finally
try
{
.......
con.Open();
//execute sql statement
}
catch (Exception ex)
{
throw ex;
//throw or dispaly your exception
}
finally
{
con.close;
}
Add the pooling attributes in your connection string
"Server=servername;Port=3306;Database=dbname; Uid=username;Pwd=password;pooling=true;Allow Zero Datetime=True;Min Pool Size=5; Max Pool Size=100;"

Accepted way to prevent "The remote host closed the connection" exception

I'm constantly getting the following exception which is caused by a user initiating a download and it consequently failing (or being cancelled):
Error Message : The remote host closed
the connection. The error code is
0x80072746. Stack Trace : at
System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[]
status, Byte[] header, Int32
keepConnected, Int32 totalBodySize,
Int32 numBodyFragments, IntPtr[]
bodyFragments, Int32[]
bodyFragmentLengths, Int32
doneWithSession, Int32 finalStatus,
Boolean& async) at
System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean
isFinal) at
System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean
finalFlush) at
I've searched all over the internet, and found an interesting article, however there doesn't seem to be a definitive answer as the best way to prevent this filling up the logs.
The user sees no error and there's no actual problem in the app as it occurs only (to my understanding) in situations out of its control (user cancelling download or loss of connection) but there has to be a way to prevent such an exception being reported.
I hate to say it but I'm tempted to check for this exception and empty catch block its ass away - but this makes me feel like a dirty programmer.
So - what is the accepted method of preventing this exception filling up my mailbox?
The error occurs when you try to send a response to the client but they have disconnected. You can verify this by setting a breakpoint on the Response.Redirect or wherever you are sending data to the client, wait for Visual Studio to hit the breakpoint, then cancel the request in IE (using the x in the location bar). This should cause the error to occur.
To capture the error you can use the following:
try
{
Response.Redirect("~/SomePage.aspx");
Response.End();
}
catch (System.Threading.ThreadAbortException)
{
// Do nothing. This will happen normally after the redirect.
}
catch (System.Web.HttpException ex)
{
if (ex.ErrorCode == unchecked((int)0x80070057)) //Error Code = -2147024809
{
// Do nothing. This will happen if browser closes connection.
}
else
{
throw ex;
}
}
Or in C# 6 you can use Exception filters to prevent having to re throw the error:
try
{
Response.Redirect("~/SomePage.aspx");
Response.End();
}
catch (System.Threading.ThreadAbortException)
{
// Do nothing. This will happen normally after the redirect.
}
catch (System.Web.HttpException ex) when (ex.ErrorCode == unchecked((int)0x80070057))
{
// Do nothing. This will happen if browser closes connection.
}
Which is a better debugging experience since it will stop on the statement throwing the exception with the current state and all local variables preserved instead of on the throw inside the catch block.
You cannot prevent a remote Host to close anything.
And in some protocols this is the normal (or at least accepted) way to say goodbye.
So you will have to handle this specific exception.
From a practical perspective, there is nothing wrong with cancelling a download by virtue of a dead computer or a killed web session, therefore catching remote host closed exceptions is perfectly acceptable.

Categories

Resources