CreateUserWizard step changing issue after account creation - c#

I want to change the createuserwizard.step= start if the mail sending fails and not to go to successful creation step.
catch (SmtpException ex)
{
Membership.DeleteUser(textboxemail.Text.Trim());
Literal errorMessage=(Literal) CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("ErrorMessage");
errorMessage.Text = "Account creation failed due to email notification."+ ex.Message + " errorcode" +ex.StatusCode + "; inner exception; " + ex.InnerException;
CreateUserWizard1.CreateUserStep.StepType = WizardStepType.Start;
}
but the exception says the steptype can't be changed. So how to do this. I mean to stop from going to success step.

You are getting that exception because you need to use the Wizard.MoveTo method.
Like this:
CreateUserWizard1.MoveTo(WizardStep1);
Where "WizardStep1" is the ID of the asp:WizardStep that you want to go back to (the "start" step).

Related

How to handle an array of SQL Error codes

I have a try\catch block that handles opening a connection and inserting data into a database.
catch (SqlException ex)
{
string sqlError = null;
for (int i = 0; i < ex.Errors.Count; i++)
{
sqlError += "Error Message " + ex.Errors[i].Message + "\n" + "Stored Procedure " + ex.Errors[i].Procedure + " \n " + "Line Number " + ex.Errors[i].LineNumber;
}
LogTools.WriteLog("Sql Server error " + sqlError);
Variables.InstallStatusDetail = "Database connection failed";
if (!sqlError.Contains("connection to SQL Server"))
{
if (Variables.WriteToDatabase)
{ HostedDataBase.InsertRunStatusIntoInstallStatus('E', sqlError, null); }
}
}
I want to log sqlexceptions to the database that wont interfere with connecting and logging to the database. The problem occurs when the database cannot be found, or a login does not have the proper permissions, etc. The exception is raised, and it tries to log to the database, so when it does that, it calls the function that writes to the database and tries to access once again, but once again the same exception is raised, resulting in a loop of failed attempts to write to the database (either because the DSN cannot be found, or the user does not have proper permissions).
How can I handle sql errors that would prevent me from being able to access and write to the database, and at the same time still be able to write sql errors that would not cause this loop?
I'm slightly confused by your question but I will attempt to answer it. You have to be careful with how you handle exceptions. If you are going to attempt to reconnect to the database even though an exception was raised the first time, you may want to have some conditions checking what sort of exception was raised. This way, you know to only attempt to re-connect if it was an exception which will not be repeated over and over.
IE.
catch (SqlException ex)
{
Error = ex.ToString()
WriteToLog(Error);
CheckError();
}
Void CheckError()
{
//conditions based on error output.
}
void WriteToLog(string Error)
{
// write your error output to log
}
You should put your logging in it's own try..catch block, like this:
catch (SqlException ex)
{
string sqlError = null;
for (int i = 0; i < ex.Errors.Count; i++)
{
sqlError += "Error Message " + ex.Errors[i].Message + "\n" + "Stored Procedure " + ex.Errors[i].Procedure + " \n " + "Line Number " + ex.Errors[i].LineNumber;
}
LogTools.WriteLog("Sql Server error " + sqlError);
Variables.InstallStatusDetail = "Database connection failed";
if (!sqlError.Contains("connection to SQL Server"))
{
if (Variables.WriteToDatabase)
{
try {
//I am assuming this is where you are trying to write the error back into the database
HostedDataBase.InsertRunStatusIntoInstallStatus('E', sqlError, null);
} catch {
//ignore errors here
}
}
}
}
Unfortunately if you are writing to the same database that you don't have access to, I'm afraid you cannot do that.
I'd suggest you to use something like Log4net which can have multiple appenders (eventlog, database, file, etc). Also, log4net operates something like a fire and forget. Even if log4net has any issues logging the errors, it won't throw exceptions.

Editing Exception to send to raygun api

At the moment raygun catches the errors I send using this line
public void SendException(Exception e)
{
new RaygunClient(AppConfiguration.RaygunApiKey).Send(e);
}
I'm looking to edit the exception so that in the message it'll give me more detail about the user and the machine along with the stacktrace. I'm wondering how do I edit the existing message or create a new message that'll also carry the stacktrace.
What I've tried is below but won't bring the stack trace over. May I ask how do I copy stack trace over.
public void SendException(Exception e)
{
var exception = new Exception("Error by " + _user.FullName + " on " + Environment.UserName + " on Machine " + Environment.MachineName, e);
new RaygunClient(AppConfiguration.RaygunApiKey).Send(exception);
}
I am aware that machine name is already provided within the exception.

Getting error message in try catch (C#, Window Service)

Is it possible to get error message in try catch on C# (or window service that was written with C#) like this:
string input = Console.ReadLine();
while (input!="q")
{
try
{
double result = 10 / int.Parse(input);
Console.WriteLine("Divinced by " + input + " And result is " + result);
}
catch (Exception)
{
Console.WriteLine("Error, Please try again");
}
finally
{
input = Console.ReadLine();
}
}
It was built to ".exe" program.
If I input character ("A","B","C") or zero, then the program will show message "Error, Please try again" so I need to know error message.
I don't want to edit code. I need a tools to detect all error in program.
Thank you for your helping.
You want the exception's Message property to be printed. Replace your catch block with this:
catch (Exception e)
{
Console.WriteLine("An exception occurred : " + e.Message);
}

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

Categories