what is the JSSE equivalent for .NET (C#)? - c#

I'm working on an application using c#-4.0 and EntireX Broker 9.5.1 I'm attempting to convert to tpcip connections to use ssl. I was successful in upgrading my java code to do the same thing thanks to Java/ Software AGs use of jsse for handling the SSL/ceritificate validation. However, when connecting to the same server/port under .net I'm getting the following error:
02150403: Certificate expired or invalid
The error message sounds like it's communicating. So how can I get .Net to successfully validate the certificate?
PS: The certificate is signed by Verisign.
UPDATE:
Both IE and Firefox successfully connect on https://server.domain:port without throwing certificate errors. My application is actually connecting to ssl://server:port?verify_server=y
verify_server=n throws the same certificate error.
The certificate is not expired. The stack trace from the exception stops right at Broker.Logon();.
at SoftwareAG.EntireX.NETWrapper.Runtime.Broker.Logon(String password)
at FAServer.EntireXDotNetClasses.EntireXWrapper.CreateBroker() in C:\Users\tfburton\Documents\Visual Studio 2010\Projects\NEW FADCOM\FAServer\EntireXDotNetClasses\EntireXWrapper.cs:line 1302
UPDATE:
Here's how I'm creating my Broker object.
try
{
Broker mybroker;
try { mybroker = new Broker(BrokerName, BrokerUser); }
catch (Exception e)
{
Utilities.LogEntry("Error Creating broker instance -- BEFORE LOGON. ", e, true);
throw new WrapperException("Error Creating broker instance -- BEFORE LOGON. "
+ Environment.NewLine + e.Message);
}
try //{ mybroker.Logon(BrokerPass); }
{
mybroker.Password = BrokerPass;
mybroker.Logon(); //<-- stracktrace points here
}
catch (AccessViolationException ave)
{
Utilities.LogEntry("Error During Broker Logon.", ave,
EventLogEntryType.Error);
throw new WrapperException(ave); //wrap and duck
}
}
catch ( Exception e )
{
Utilities.LogEntry("Error Creating broker instance. ", e, true);
XException be = e as XException;
if ( null != be ) //<-- resolves to true
{
String msg = "Certificate error connecting to: " + BrokerName;
throw new WrapperException(msg, e);
}
throw new WrapperException( "Error Creating broker instance. "
+ Environment.NewLine + e.Message); //<-- error caught and re-thrown here
}

Turns out I was barking up the wrong tree.
I'm not sure if .NET has an equivalent for JSSE.
My solution turned out to be a lot simpler, concatinate the root certs in a text file and add
trust_store=path\to\file\myrrootcerts.pem
as a parameter to the url aka
BROKER-ID

Related

After some calls getting k8s.Autorest.HttpOperationException: Operation returned an invalid status code 'Unauthorized'

We are trying to monitor an argo workflow using the Kubernetes client for C#. The Kubernetes server is hosted on AWS EKS cluster. The method we are using is IKubernetes.CustomObjects.GetNamespacedCustomObjectAsync(). The issue is that the first 15 minutes or so all calls go through just fine. After that we start getting the above stated exception.
The kubeconfig file was created using the aws eks update-kubeconfig so I'm assuming no errors are present there (also the calls going through initially).
Sample of code used:
public static async System.Threading.Tasks.Task MonitorWorkflowAsync(this IKubernetes kubernetes, string? workflowName)
{
string? state = null;
do
{
try
{
dynamic response = await kubernetes.CustomObjects.GetNamespacedCustomObjectAsync(KubeConstants.Group, KubeConstants.Version, KubeConstants.NamespaceParameter, KubeConstants.Plural, workflowName);
state = response?.GetProperty("status")?.GetProperty("phase").ToString();
}
catch (Exception ex)
{
Log.Error(ex.Message + "/n" + ex.StackTrace);
}
Log.Information("Pipeline: {0}\t Status: {1} ", workflowName,
state);
if (state?.Equals(KubeConstants.Running,
StringComparison.InvariantCultureIgnoreCase) ?? false)
Thread.Sleep(30000);
if (!(state?.Equals(KubeConstants.Failure,
StringComparison.InvariantCultureIgnoreCase) ?? true)) continue;
Log.Warning(
"The workflow {0} has failed to execute properly. Please access the Kubernetes cluster and troubleshoot OR check your yaml file used to create the workflow!",
workflowName);
break;
}
while (state?.Equals(KubeConstants.Running, StringComparison.InvariantCultureIgnoreCase) ?? false);
}
}
Kubernetes Client version : 8.0.6
Kubernetes Version: 1.22
.NET version: 6.0

Getting Error: "underlying connection closed: unexpected error on request receive"

I am using .Net application with web service(.net) and oracle database. But when i send some request to the server and waiting for the result it is giving following error
The underlying connection was closed: An unexpected error occurred
I am unable to get the cause of the error. Can any one plese help me to get actual cause of this error and what i need to do solution. This errror occurce only in Production Server. Same code in Dev and Test server it is working.
This is probably caused by the error inside web service method or function that you are calling. Just create proper error handling and log web service exception. Here is my sample code:
[WebMethod]
public void MyServerMethod()
{
try
{
//open connection and execute your calls to Oracle DB...
}
catch (Exception ex)
{
LogServiceException(ex);
throw ex;
}
}
void LogServiceException(Exception ex)
{
string fullMessage = ex.Message;
while (ex.InnerException != null)
{
ex = ex.InnerException;
fullMessage += " Inner exception: " + ex.Message;
}
//log your exception to log file, DB or eventlog...
//in this case I will use log file, just make sure you appropriate filesystem rights to do this...
System.IO.File.AppendAllText("LogFile.txt", fullMessage);
}

Get sent mail error

Is there any way to get sent error from the smtp to check if the mail is sent successfully?
var smtpClient = new SmtpClient("SmtpServer");
smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
smtpClient.SendAsync(mail, userId);
The errors I am looking for are: mail can't be deliver because the mail address not exists, mail box full etc...
Regards,
Meir.
I am not sure what you are trying to achieve but this will helps you.
I assume you're already aware of the DeriveryNotificationOptions property on System.Net.Mail.MailMessage. The only tricky part to using that property is that its enum type represents a bitfield, so you should set it to the sum of the options you want to apply.
For example, if you want delivery notification on delay, failure, or success, you should set the property to
DeliveryNotificationOptions.Delay + DeliveryNotificationOptions.OnFailure + DeliveryNotificationOptions.OnSuccess
Or
this is one method to capture the failure report or any error when the mail has not been sent (failure report)
// Change your Try-Catch to call the new method named 'CheckExceptionAndResend'
// Error handling for sending message
try
{
smtpClient.Send(message);
// Exception contains information on each failed receipient
}
catch (System.Net.Mail.SmtpFailedRecipientsException recExc)
{
// Call method that will analyze exception and attempt to re-send the email
CheckExceptionAndResend(recExc, smtpClient, message);
}
catch (System.Net.Mail.SmtpException smtpExc)
{
// Log error to event log using StatusCode information in
// smtpExc.StatusCode
MsgBox((smtpExc.StatusCode.ToString + " ==>Procedure SmtpException"));
}
catch (Exception Exc)
{
// Log error to event log using StatusCode information in
// smtpExc.StatusCode
MsgBox((Exc.Message + " ==>Procedure Exception"));
}
private void CheckExceptionAndResend(System.Net.Mail.SmtpFailedRecipientsException exObj, System.Net.Mail.SmtpClient smtpClient, MailMessage emailMessage)
{
try
{
for (int recipient = 0; (recipient <= (exObj.InnerExceptions.Length - 1)); recipient++)
{
System.Net.Mail.SmtpStatusCode statusCode;
// Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
statusCode = exObj.InnerExceptions(recipient).StatusCode;
if (((statusCode == Net.Mail.SmtpStatusCode.MailboxBusy)
|| (statusCode == Net.Mail.SmtpStatusCode.MailboxUnavailable)))
{
// Log this to event log: recExc.InnerExceptions(recipient).FailedRecipient
System.Threading.Thread.Sleep(5000);
smtpClient.Send(emailMessage);
}
else
{
// Log error to event log.
// recExc.InnerExceptions(recipient).StatusCode or use statusCode
}
}
MsgBox((exObj.Message + " ==>Procedure SmtpFailedRecipientsException"));
}
catch (Exception ex)
{
// At this point we have an non recoverable issue:
// NOTE: At this point we do not want to re-throw the exception because this method
// was called from a 'Catch' block and we do not want a hard error to display to the client.
// Options: log error, report issue to client via msgbox, etc. This is up to you.
// To display issue as you have before:
MsgBox((exObj.Message + " ==>Email was not sent"));
}
}
Such kind of errors have a asnychronous nature. When sending mail you talk to the local smtp server of your provider. That server afterwards starts to deliver the mail to the target mail system.
So the SmtpClient class can only show you errors occuring while talking to your local smtp server.
Typically when an error like "unknown user" occures on the target system, it will send an email with the failure message to the originator email address.
This post is helpful to me.
By the way if you're using .net 4.0 this one will be the changes on the above code. Sorry for my first post i don't know why it appears that way.
Here's the code:
private void CheckExceptionAndResend(System.Net.Mail.SmtpFailedRecipientsException exObj, System.Net.Mail.SmtpClient smtpClient, MailMessage emailMessage)
{
try
{
for (int recipient = 0; (recipient <= (exObj.InnerExceptions.Length - 1)); recipient++)
{
System.Net.Mail.SmtpStatusCode statusCode;
// Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
//for .net 4.0
//statusCode = exObj.InnerExceptions(recipient).StatusCode;
statusCode = exObj.StatusCode;
//if (((statusCode == Net.Mail.SmtpStatusCode.MailboxBusy) || (statusCode == Net.Mail.SmtpStatusCode.MailboxUnavailable)))
//for .net 4.0
if (((statusCode == System.Net.Mail.SmtpStatusCode.MailboxBusy)
|| (statusCode == System.Net.Mail.SmtpStatusCode.MailboxUnavailable)))
{
// Log this to event log: recExc.InnerExceptions(recipient).FailedRecipient
System.Threading.Thread.Sleep(5000);
smtpClient.Send(emailMessage);
}
else
{
// Log error to event log.
// recExc.InnerExceptions(recipient).StatusCode or use statusCode
}
}
//MsgBox((exObj.Message + " ==>Procedure SmtpFailedRecipientsException"));
}
catch (Exception ex)
{
// At this point we have an non recoverable issue:
// NOTE: At this point we do not want to re-throw the exception because this method
// was called from a 'Catch' block and we do not want a hard error to display to the client.
// Options: log error, report issue to client via msgbox, etc. This is up to you.
// To display issue as you have before:
// MsgBox((exObj.Message + " ==>Email was not sent"));
}
}

How to catch specific exceptions when sending mail?

I have the following piece of code
try
{
if (!bDebug)
smtp.Send(m);
}
catch (Exception e)
{
wl("Meldingen kunne ikke sendes til en eller flere mottakere.", ConsoleColor.Red);
wl(e.Message, ConsoleColor.DarkRed);
using (var errorfile = System.IO.File.CreateText("error-" + DateTime.Now.Ticks + ".txt"))
{
errorfile.WriteLine(e.StackTrace);
if (e.GetType() == typeof(SmtpFailedRecipientException))
{
var se = (SmtpFailedRecipientException) e;
errorfile.WriteLine(se.FailedRecipient);
}
errorfile.WriteLine(e.ToString());
}
}
Where wl is a shortcut for writing to the console with color, and the text in the first line says "The message could not be sent to one or more recipients.
Previously I only caught the SmtpFailedRecipientException, but when it started failing in some other steps I shoved the generic Exception in there. So the part I'm wondering about is where I'm casting the Exception object into a more specific object to get the FailedRecipient property. Could/should this be done in another more proper way? It seems a bit clunky...
You can have multiple catch branches:
catch (SmtpFailedRecipientException se)
{
using (var errorfile = System.IO.File.CreateText("error-" + DateTime.Now.Ticks + ".txt"))
{
errorfile.WriteLine(se.StackTrace);
// variable se is already the right type, so no need to cast it
errorfile.WriteLine(se.FailedRecipient);
errorfile.WriteLine(se.ToString());
}
}
catch (Exception e)
{
wl("Meldingen kunne ikke sendes til en eller flere mottakere.", ConsoleColor.Red);
wl(e.Message, ConsoleColor.DarkRed);
// for other error types just write the info without the FailedRecipient
using (var errorfile = System.IO.File.CreateText("error-" + DateTime.Now.Ticks + ".txt"))
{
errorfile.WriteLine(e.StackTrace);
errorfile.WriteLine(e.ToString());
}
}
You can try somthing like this(source):
We're going to learn how to catch/handle different types of
exceptions/errors that might occur while sending an email using
ASP.Net. We'll implement error/exception handling using different
exception classes available in System.Net.Mail.
First to learn how to send an email using ASP.Net visit this
link. Notice that in the above article (lead by link) the
'SendEmails' catches only a generic exception and in case ASP.Net
encounters an error while sending email it would be like 'Sending
email failed etc'. We'll extend the error handling functionality for
the above article. So lets get started by openning the solution we
created previously. We already have put a try-catch block that catches
a generic exception that tells very little about what might have gone
wrong. Let's catch different types of exception right away:
Catch the SmtpException: The SmtpException class has a property
'StatusCode' which is actually an enumeration that gets the
error/exception code value returned by the SMTP server when an email
message is transmitted. It also provides more details of
error/exception that can occur during the email sending process. e.g.
catch (SmtpException smtpException)
{ // You can put a switch block to check for different exceptions or errors
// To checks if the destination mailbox is busy
if (smtpException.StatusCode == SmtpStatusCode.MailboxBusy)
throw smtpException;
// To check if the client is authenticated or is allowed to send email using the specified SMTP host
if (smtpException.StatusCode == SmtpStatusCode.ClientNotPermitted)
throw smtpException;
// The following code checks if the email message is too large to be stored in destination mailbox
if (smtpException.StatusCode == SmtpStatusCode.ExceededStorageAllocation)
throw smtpException;
// To check if the email was successfully sent to the SMTP service
if (smtpException.StatusCode == SmtpStatusCode.Ok)
throw smtpException;
// When the SMTP host is not found check for the following value
if (smtpException.StatusCode == SmtpStatusCode.GeneralFailure)
throw smtpException;
}
Catch the SmtpFailedRecipientException: The
SmtpFailedRecipientException class deals with the exception related to
the recipient of the email e.g. SMTP is not able to send the email to
a recipient. The SmtpFailedRecipientException occurs when SmtpClient
is not able to complete a SmtpClient.Send() or SmtpClient.SendAsync()
operation to a particular recipient. To catch this exception use the
following code:
catch (System.Net.Mail.SmtpFailedRecipientException smtpFailedRecipientException)
{
// Get the email that is causing email sending failed exception
String emailCausingException = smtpFailedRecipientException.FailedRecipient;
// Get the status code why and what is actually causing an email sending error
System.Net.Mail.SmtpStatusCode statusCode = smtpFailedRecipientException.StatusCode;
// Take some action either re-send the email again or do some error handling code here
}
Catch the SmtpFailedRecipientsException: The
SmtpFailedRecipientsException is actually a collection of
SmtpFailedRecipientException objects serving the same purpose. It is
used to handle exceptions when SmtpClient is not able to send emails
to one or more recipients.
catch (System.Net.Mail.SmtpFailedRecipientsException smtpFailedRecipientsException)
{
ArrayList emailCausingException = new ArrayList();
foreach (SmtpFailedRecipientException smtpFailedRecipientException
in smtpFailedRecipientsException.InnerExceptions)
{
// Get the email that is causing email sending failed exception
// Add it to a list of emails with exceptions
emailCausingException.Add(smtpFailedRecipientException.FailedRecipient);
// Get the status code why and what is actually causing an email sending error
System.Net.Mail.SmtpStatusCode statusCode = smtpFailedRecipientException.StatusCode;
// Take some action either re-send the email again or do some error handling
// You can also log or print this status code for an individual recipient here
if (statusCode == SmtpStatusCode.MailboxBusy)
{
//Re-Send email after some time
System.Threading.Thread.Sleep(1000);
//smtpClient.Send();
//Email sending code here
}
}
}

MessageQueue.BeginReceive() null ref error - c#

Have a windows service that listens to a msmq. In the OnStart method is have this
protected override void OnStart(string[] args)
{
try
{
_queue = new MessageQueue(_qPath);//this part works as i had logging before and afer this call
//Add MSMQ Event
_queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);//this part works as i had logging before and afer this call
_queue.BeginReceive();//This is where it is failing - get a null reference exception
}
catch(Exception ex)
{
EventLogger.LogEvent(EventSource, EventLogType, "OnStart" + _lineFeed +
ex.InnerException.ToString() + _lineFeed + ex.Message.ToString());
}
}
where
private MessageQueue _queue = null;
This works on my machine but when deployed to a windows 2003 server and running as Network service account, it fails
Exception recvd:
Service cannot be started. System.NullReferenceException: Object reference not set to an instance of an object.
at MYService.Service.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
Solved:
Turned out that the Q that i set up, I had to explicitly add Network Service account to it under security tab
You're seeing that particular exception because you're calling ex.InnerException.ToString(). The InnerException property is not always populated (in fact, it frequently isn't, nor should it be).
Your root problem is likely that the Network Service account doesn't have permissions to access the queue (in this case, read from it).
Here's some code that will help you get the actual error in your event log:
catch(Exception ex)
{
Exception e = ex;
StringBuilder message = new StringBuilder();
while(e != null)
{
if(message.Length > 0) message.AppendLine("\nInnerException:");
message.AppendLine(e.ToString());
e = e.InnerException;
}
EventLogger.LogEvent(EventSource, EventLogType, "OnStart" + _lineFeed +
message.ToString());
}

Categories