No exception for incorrectly configured WCF server hostname - c#

I have a server client implementation using WCF where the clients sends a Connect message to the server when it starts.
This is the code I'm using in my client application (WCF service is self hosted in this case):
public void InitializeCommunicationChannel()
{
this._proxy = new DistributionServiceClient(this._context, "NetTcpBinding_IDistributionService");
Log.Write(Level.Debug, "Initialized proxy..");
//set credentials
this._proxy.ClientCredentials.Windows.ClientCredential.Domain = PasswordManager.ServerAdminDomain;
this._proxy.ClientCredentials.Windows.ClientCredential.UserName = PasswordManager.ServerAdminUsername;
this._proxy.ClientCredentials.Windows.ClientCredential.Password = PasswordManager.ServerAdminPassword;
this._proxy.InnerChannel.Faulted += new EventHandler(this.InnerChannel_Faulted);
this._proxy.InnerChannel.Closing += new EventHandler(this.InnerChannel_Closing);
//send a connect message to the server
try
{
Log.Write(Level.Debug, "Sending connect message..");
this.StationId = this._proxy.ClientConnected(ClientConfiguration.HostName, this.Version, ClientConfiguration.CurrentIpAddress);
Log.Write(Level.Debug, "Connect message sent..");
Log.Write(Level.Info, "Connected to server.");
this.ConnectionState = "Connected";
}
catch (ConfigurationErrorsException cEx)
{
Log.Write(Level.Error, cEx.Message);
Log.Write(Level.Debug, cEx.ToString());
}
catch (FaultException fEx)
{
//probably server didn't recognize configured ip or hostname
Log.Write(Level.Error, fEx.Message);
Log.Write(Level.Debug, fEx.ToString());
}
catch (CommunicationException cEx)
{
Log.Write(Level.Debug, cEx.Message);
Log.Write(Level.Debug, cEx.ToString());
}
catch (System.Security.Authentication.InvalidCredentialException iEx)
{
Log.Write(Level.Error, iEx.Message);
Log.Write(Level.Debug, iEx.ToString());
}
catch (Exception ex)
{
Log.Write(Level.Error, ex.Message);
Log.Write(Level.Debug, ex.ToString());
}
void InnerChannel_Closing(object sender, EventArgs e)
{
Log.Write(Level.Debug, "Communication channel is closing down..");
this.ConnectionState = "Attempting connection..";
}
void InnerChannel_Faulted(object sender, EventArgs e)
{
this.ConnectionState = "Not connected";
Log.Write(Level.Debug, "Communication channel faulted..");
//something went wrong
this._proxy.Abort();
this._proxy.InnerChannel.Faulted -= this.InnerChannel_Faulted;
this._proxy.InnerChannel.Closing -= this.InnerChannel_Closing;
//give the server a chance to get back online; retry after 10s
Thread.Sleep(10000);
//re-initialize the communication channel
this.InitializeCommunicationChannel();
}
The problem that I'm having is that when the server address is not correctly configured in the client's config file, the channel faults when I try to send the Connect message, but no exception is being caught.
Is this because the connection is occurring on a different thread therefore it never ends up in my catch code? How do I catch endpoint configuration exceptions in code? The InnerChannel_Faulted's EventArgs member doesn't contain any useful information.
Thanks a lot.

Related

SVN credentials

I have an issue where I keep getting an error
No provider registered for 'svn.ssl.server' credentials
I am using the same code that works on another SVN server, but a new server I setup can't seem to connect even though I can connect no problem through a web browser.
//SVN Client repo sync
public void DownloadSVNStartup(string url, string path)
{
using (SvnClient client = new SvnClient())
{
try
{
client.CleanUp(path); //will go to catch block since there's no working copy yet I
//want to checkout for the first time then next time this part
//will work.
SvnUI.Bind(client, this);
SvnCheckOutArgs sco = new SvnCheckOutArgs();
sco.AllowObstructions = false;
}
catch (Exception ex)
{
MessageBox.Show("Line 88");
MessageBox.Show(ex.ToString());
myLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
client.Configuration.SetOption("servers", "global", "http-auth-types", "basic;digest");
client.Authentication.Clear();
client.Authentication.ForceCredentials("user", "password");
try
{
client.Authentication.SslServerTrustHandlers += delegate (object sender,
SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = false; // Save acceptance to authentication store
};
Object[] args = { url, path };
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += backgroundWorker1_DoWork;
worker.RunWorkerAsync(args);
this.Hide();
}
catch (Exception ex)
{
MessageBox.Show("Line126");
MessageBox.Show(ex.ToString());
myLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //connect to the Svn
//server
{
try
{
Object[] arg = e.Argument as Object[];
string url = (string)arg[0];
string path = (string)arg[1];
using (SvnClient client = new SvnClient())
{
client.Authentication.Clear(); // Prevents saving/loading config to/from disk
client.Authentication.ForceCredentials("user", "password");
client.CheckOut(new Uri(url), path); //fails here with the error No provider registered for 'svn.ssl.server' credentials
client.CleanUp(path);
client.Update(path);
client.CleanUp(path);
}
}
catch (Exception ex)
{
MessageBox.Show("Line166", ex.Message.ToString());
MessageBox.Show(ex.ToString());
}
}
I have searched for hours for solutions and can't find anything.
Both servers are setup with same port, same HTTPS settings and created certificates, same VisualSVN server editions.
I have tried only the one solution that I could find as this is not a common issue at all.
This is supposed to fix that error but it doesn't.
client.Authentication.SslServerTrustHandlers += delegate (object sender, SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = false; // Save acceptance to authentication store
};
I fixed it with adding an event handler for the certificate
private void SslClientCertificateHandlers(object sender, SvnSslClientCertificateEventArgs e)
{
e.Save = true;
e.CertificateFile = #"where you want to save certs";
}

How to catch exception in case no internet connection while sending data to Azure IoTHub

I have a requirement where I am continuously sending data to IoT hub and If Internet connectivity is went down I need to store it on Local database like SQL.
To Send data to IoT hub we have asyn method that is "deviceClient.SendEventAsync"
where device client is the object of DeviceClient class.
Now since this is asyn method it is not throwing any exception when no internet connection is there hence I am not able to catch this and store into local sql db.
Inside method my code is like
try
{
await deviceClient.SendEventAsync(message) ;
}
catch(AggregateException)
{
//If exception found then store same msg to local database.
}
catch(Exception ex)
{
//If exception found then store same msg to local database.
}
But I am never getting any exception in case of any fault or no internet connectivity and the execution of code is keep going.
Please help me to tackle this issue.
Also let me know in case there are any other ways to capture exception while calling any asyn method.
Please find the entire code structure that I am using for this operation.
namespace D2CDeviceDataSender
{
class Program
{
private static DeviceClient deviceClient;
private static string iotHubUri = string.Empty;
private static string deviceKey = string.Empty;
private static string deviceName = string.Empty;
static void Main(string[] args)
{
try
{
iotHubUri = ConfigurationManager.AppSettings["IoTHubURI"].ToString();
deviceName = ConfigurationManager.AppSettings["DeviceName"].ToString();
deviceKey = ConfigurationManager.AppSettings["DeviceKey"].ToString();
deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceName, deviceKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt);
Task.Factory.StartNew(() => SendDeviceToCloudMessagesAsync1());
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Press any key to exit.....");
Console.ReadLine();
}
}
public static async Task SendDeviceToCloudMessagesAsync1()
{
while (true)
{
try
{
double avgWindSpeed = 10; // m/s
Random rand = new Random();
double currentWindSpeed = avgWindSpeed + rand.Next();
var telemetryDataPoint = new
{
DeviceCode = "myFirstDevice",
Date = DateTime.UtcNow,
};
string messageString = JsonConvert.SerializeObject(telemetryDataPoint);
var message = new Message(Encoding.ASCII.GetBytes(messageString));
Task taskresult = deviceClient.SendEventAsync(message);
await taskresult;
Console.WriteLine("Data sent to IoT hub :" + DateTime.Now + " " + messageString);
}
catch (IotHubCommunicationException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.InnerException);
Console.WriteLine("Internet connectivity down insert data to local database !");
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.InnerException);
Console.WriteLine("Internet connectivity down insert data to local database !");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.InnerException);
Console.WriteLine("Internet connectivity down insert data to local database !");
}
Thread.Sleep(5000);
}
}
}
}
Below are my two observation that is:
This code will throwing exception only one time when internet
connectivity get down.
From next iteration the "await taskresult;" method in stop
responding and from on ward iteration so I am not able to capture any
exception.
Please revert back with your feedback.
I have the following code in a loop that continuously sends messages to IoT Hub:
try
{
await deviceClient.SendEventAsync(message);
Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
}
catch (AggregateException e)
{
Console.WriteLine("{0} > Error Sending message: {1}", DateTime.Now, messageString);
Console.WriteLine("AggregateException: {0} ", e.Message);
}
If I set this running, and then disconnect the computer from the network, I see this in the output:
19/04/2017 09:11:47 > Sending message: {"deviceId":"myFirstDevice","windSpeed":10.042793008518775}
19/04/2017 09:11:52 > Sending message: {"deviceId":"myFirstDevice","windSpeed":8.5088816902175921}
19/04/2017 09:11:58 > Sending message: {"deviceId":"myFirstDevice","windSpeed":10.399840490147398}
19/04/2017 09:12:22 > Error Sending message: {"deviceId":"myFirstDevice","windSpeed":10.388208727533094}
AggregateException: One or more errors occurred.
This shows that you can catch AggregateExceptions from the SendEventAsync method. What platform are you running your code on?

When disconnecting socket, waiting time occurs

I'm studying network and Windows forms with C# these days.
I'm trying to build an async-socket network system, everything's working well.
codes for Connect and Connect Callback are below.
private void ClientConnect()
{
CheckForIllegalCrossThreadCalls = false;
try
{
socket.BeginConnect(endPoint, new AsyncCallback(ConnectCallback), socket);
connectDone.WaitOne();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
Send(socket, textBox3.Text, 0);
connectDone.Set();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
But in disconnecting socket, there's a problem.
I make a button to disconnect socket, and codes for button-clicked event are below.
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
socket.Shutdown(SocketShutdown.Both);
Application.DoEvents();
socket.Disconnect(true); //-> problem occurs.
}
catch
{
MessageBox.Show("Disconnect Error!");
}
if (socket.Connected)
MessageBox.Show("Disconnect Error!");
else
textBox1.AppendText("Disconnected! (" + DateTime.Now.ToString("h:mm:ss tt") + ")\n");
}
When I disconnect the socket, 2 minutes of waiting time occurs.
after 2 minute(I checked this with time-stamp), It shows 'Disconnected' message.
And I can re-connect with this socket.
I think it is not just waiting like sleep, something's processed in background.
(Because mouse cursor's changed and program's blocked)
I'm so wondering why this delay(?) happens.
Please let me know.

Accepting Connections asynchronous with a Proxy Server

When I want to open a new Thread for every Incoming Request. Is this good way to do it? Will there be a new Thread with every accepted Request? The BeginReceive Method called in the end of this piece of code Works asynchronous aswell.
public void Listen(IPEndPoint EndPoint)
{
try
{
ListeningSocket.Bind(EndPoint);
ListeningSocket.Listen(BACKLOG);
BeginAccept();
}
catch (Exception e)
{
Console.WriteLine(e.Message + "\nfrom Source: " + e.Source + "\nand Stack Trace: " + e.StackTrace);
}
}
public void BeginAccept()
{
try
{
ListeningSocket.BeginAccept(new AsyncCallback(Accept_Callback), new ServerSocket());
}
catch (SocketException e)
{
Console.WriteLine("Listening Socket Error:" + e.ErrorCode);
}
catch (ObjectDisposedException e)
{
Console.WriteLine("The Listening Socket has been closed");
}
}
private void Accept_Callback(IAsyncResult asyncResult)
{
BeginAccept();
try
{
if (asyncResult.AsyncState != null)
{
ServerSocket serverSocket = asyncResult.AsyncState as ServerSocket;
if ((serverSocket.CommunicationSocket = ListeningSocket.EndAccept(asyncResult)) != null)
{
BeginReceive(serverSocket);
}
}
}
catch (SocketException e)
{
Console.WriteLine("Listening Socket Error:" + e.ErrorCode);
}
catch (ObjectDisposedException e)
{
Console.WriteLine("The Listening Socket has been closed");
}
}
This approach uses threads from a ThreadPool which is a good thing. While waiting for a new client to be accepted or for data to arrive no threads are used, so your code will not span 1000 threads when you have 1000 clients connected.
Just when data arrives on one socket, one free thread will be taken from the tread pool and will process your callback. When your method finishes, the thread will be returned to the pool to be available for the next data arrival or client connection.

Sending Emails Asychrounously Problems

I had configure smpt mail for my site and it's work when I tried to send one single email but I have following error when I want to send it to more people, In addition I use SendAsyn method.
When I Send all Emails using LOOP
Syntax error, command unrecognized. The server response was:
at System.Net.Mail.SmtpConnection.ConnectAndHandshakeAsyncResult.End(IAsyncResult result)
at System.Net.Mail.SmtpClient.ConnectCallback(IAsyncResult result)
When I Add All Emails to BCC
Service not available, closing transmission channel.
The server response was: Too many bad commands, closing transmission channel
at System.Net.Mail.SendMailAsyncResult.End(IAsyncResult result)
at System.Net.Mail.SmtpTransport.EndSendMail(IAsyncResult result)
at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result
what is the solution for that ?
I have a similar situation whereby l am sending multiple emails and not waiting for one to finish before sending another.
What l did was initiate a new SMTPClient for every mail to be sent and send asynchronously. Like this:
private void SendMailAsync(string ids, MailMessage mail)
{
SmtpClient client = null;
try
{
client = new SmtpClient(ConfigurationManager.AppSettings["MailServer"], Convert.ToInt32(ConfigurationManager.AppSettings["MailPort"]));
string userState = "MailQueueID_" + ids;
client.SendCompleted += (sender, e) =>
{
// Get the unique identifier for this asynchronous operation
String token = (string)e.UserState;
DateTime now = DateTime.Now;
try
{
if (e.Cancelled)
{
LogError(new Exception(token + " - Callback cancelled"));
return;
}
if (e.Error != null)
{
LogError(e.Error);
}
else
{
logWriter.WriteToLog(this.jobSite + " - " + token + " (Email sent)");
try
{
int updated = UpdateMailQueue(token, now);
if (updated > 0)
{
// Update your log
}
}
catch (SqlException sqlEx)
{
LogError(sqlEx);
}
}
}
catch (ArgumentNullException argument)
{
LogError(argument);
}
finally
{
client.SendCompleted -= client_SendCompleted;
client.Dispose();
mail.Dispose();
// Delete the attachment if any, attached to this email
DeleteZipFile(token);
counter--;
}
};
client.SendAsync(mail, userState);
counter++;
}
catch (ArgumentOutOfRangeException argOutOfRange)
{
LogError(argOutOfRange);
}
catch (ConfigurationErrorsException configErrors)
{
LogError(configErrors);
}
catch (ArgumentNullException argNull)
{
LogError(argNull);
}
catch (ObjectDisposedException objDisposed)
{
LogError(objDisposed);
}
catch (InvalidOperationException invalidOperation)
{
LogError(invalidOperation);
}
catch (SmtpFailedRecipientsException failedRecipients)
{
LogError(failedRecipients);
}
catch (SmtpFailedRecipientException failedRecipient)
{
LogError(failedRecipient);
}
catch (SmtpException smtp)
{
LogError(smtp);
}
}
The error was caught in the SendCompletedEvent Handler.
Of course the error appeared for only one email while the other 7 went thru to different mail boxes both before and after it in the same run. What caused the error, l still don't know.
When l ran my program again, it picked up the mail that was not sent and sent it off successfully.
Hope this helps others cos l realise that the question was posted more than 15 months ago.

Categories