Handling exception that are managed in code - c#

How should I handle those exceptions that I can't catch in the C# code behind... like for example I am facing failed email sending system.Net.Sockets.SocketException but I have no chance to handling the page codebhind.. where should I handle it?
protected void CreateUserWizard1_SendingMail1(object sender, MailMessageEventArgs e)
{
string emailname="";
try
{
TextBox textboxemail = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email");
MembershipUser user = Membership.GetUser(textboxemail.Text);
Guid userid = (Guid)user.ProviderUserKey;
string verificationurl = "http://www.spiralsnet.com/Login.aspx?NewUserId=" + userid.ToString();
e.Message.IsBodyHtml = true;
e.Message.From = new System.Net.Mail.MailAddress("SpiralsWhirls#yahoo.com", "SpiralsNet");
e.Message.Body = e.Message.Body.Replace("<%VU%>", verificationurl);
}
catch (System.Net.Sockets.SocketException ex)
{
Membership.DeleteUser(emailname);
}
}

Related

C# Are errors in DataGridView.Datasource assignments handled internally

I have an application that assigns a list of values to a DataGridView.
This is done inside a Try catch block.
Occasionally there is an issue with the with the procedure that produces this list (also in a try catch block) and this causes an error when the assignment is done.
It appears the exception is never caught by the block doing the assignment and the application freezes.
Is the exception handled inside the assignment call so that it is not propagated out to the catch block?
The exception produced as a pop up states
"The following exception occurred in the DataGridView:
System.IndexOutOfrangeException: Index 1 does not have a value at
System.Windows.Forms.dataGridViewDataConnection.GetError(Int32 rowIndex)
To replace this default dialog please handle the DataError event"
The code is basically
public void SetupRunners(EventDetails _eventDetails)
{
try
{
RunnerAssociates.Clear();
RunnerAssociates = null;
RunnerAssociates = createRunnerAssociateList(selectedEventDetails);
runnerAssociatesDataGridView.DataSource = RunnerAssociates;
runnerAssociatesDataGridView.DataMember = string.Empty;
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
}
private List<Runner_Associate> createRunnerAssociateList(EventDetails _meetAndRace) //NZRB_Global.MeetAndRace _meetAndRace)
{
const string methodName = "createRunnerAssociateList";
List<Runner_Associate> lra = new List<Runner_Associate>();
try
{
if (null != _meetAndRace)
{
_meetAndRace.UpdateAllProfiles();
foreach (RunnerDetail rd in _meetAndRace.runners.runnerList)
{
Runner_Associate ra = new Runner_Associate();
ra.Number = rd.number;
ra.RunnerName = rd.name;
RunnerProfile profile = rd.GetRunnerProfile();
if ((rbJockeyDriver.Checked) || (rbCustom.Checked))
{
ra.AssociateName = rd.person;
}
else if (profile != null)
{
if (rbTrainers.Checked)
{
ra.AssociateName = profile.trainer;
}
else if (rbOwners.Checked)
{
ra.AssociateName = profile.owners;
}
}
lra.Add(ra);
}
}
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
return lra;
}

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll, network releted

private void metroButtonLogin_Click(object sender, EventArgs e)
{
try
{
//Your insert code here
DataSet1TableAdapters.UsersTableAdapter userAda = new DataSet1TableAdapters.UsersTableAdapter();
DataTable dt = userAda.GetDataByUserAndPass(metroTextBoxUser.Text, metroTextBoxPass.Text);
if (dt.Rows.Count > 0)
{
//valid
MessageBox.Show("Login Ok");
UserID = int.Parse(dt.Rows[0]["UserID"].ToString());
loginFlag = true;
}
else
{
// not valid
MessageBox.Show("Access Denied");
loginFlag = false;
}
Close();
}// above is your origine code
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
}
}
You need to look at more details of your exception to better understand what's wrong. You need to look at the Message property of the exception. Usually it will give a more understandable sentence about what the problem could be. Add that last line of code in your metroButtonLogin_Click method in a try/catch block and have a look at the exception.

Parsing JSON object with Windows Phone 7

I'm trying to read from a Uri which i created and to display it on windows phone 7 app.
(I'm doing this tutorial:http://msdn.microsoft.com/en-us/windowsmobile/Video/hh237494).
My problem is that the program doesnt get into the OpenReadCompletedEventHandler and i dont know why. (i putted message box in order to debug and i found out that the program doesnt get into the OpenReadCompletedEventHandler). Here is the relevant code:
void myButton_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://localhost:44705/Service1.svc/GetAllBrands");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenWriteAsync(uri);
MessageBox.Show("opening sucsseded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
MessageBox.Show("OpenRead Handler");
// OpenWriteCompletedEventArgs temp = (OpenWriteCompletedEventArgs)e;
DataContractJsonSerializer serializer = null;
try
{
serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Brand>));
ObservableCollection<Brand> Brands = serializer.ReadObject(e.Result) as ObservableCollection<Brand>;
foreach (Brand b in Brands)
{
int id = b.BrandId;
string name = b.BrandName;
listBrands.Items.Add(id + " " + name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance!
I have never used this but a quick google takes me to this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openreadcompleted.aspx
This should tell you why it's not working - because you are using a read event for a write operation. You should be using OpenWriteCompletedEventHandler with OpenWriteAsync as per this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openwritecompleted.aspx

Output variable from void method so that a javascript function can read it

Hi I am trying to authenticate a user through this method
protected void btnLogin_Click(object sender, EventArgs e)
{
string email = txtEmail.Text;
string password = txtPassword.Text;
try
{
bool loginResult = SingletonManager.Instance.FrontendFactories.UserFrontendFactory.LoginUser(email, FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5"), chkRememberMe.Checked);
if (loginResult == true)
{
FormsAuthentication.RedirectFromLoginPage(txtEmail.Text, true);
Context.Items.Add("email", txtEmail.Text);
}
else
{
txtEmail.CssClass += " " + "txt-error-message";
errorIconmaEmail.Visible = true;
txtPassword.CssClass += " " + "txt-error-message";
errorIconPassword.Visible = true;
}
}
catch (Exception ex)
{
lblerror.Text = ex.Message;
}
}
Now i know it is a void method and void methods do not return values but is there a work around to sumhow create a bool in the else block (instead of the current code) such as bool isValidUser = false, so the javascript function will take care of the error message styling according to the value of this bool. FYI i am accessing the code behind public variables thorugh.
<%= isValidUser %>
RegisterCloentScriptBlock seems to be the function you are looking for.

C#: trying to set "ServerBindings" property of my website programatically, keeps crashing

I am trying to Configure my IIS programmatically following the steps on this
msdn guide
the only difference i made was switching to winforms instead of console..
and variables instead of function parameters.
however the code throws an exception when i try to set the singleproperty value...
here is my code..
string metabasePath = "IIS://localhost/W3SVC/1234", propertyName = "ServerBindings";
object newValue = " :8080:";
try
{
DirectoryEntry path = new DirectoryEntry(metabasePath);
//when i try to retrieve the old value,it returns a null
PropertyValueCollection propValues = path.Properties[propertyName];
MessageBox.Show("7");
//the code throws an exception after messagebox,
//kinda old school debuging
path.Properties[propertyName][0] = newValue;
path.CommitChanges();
lblerror.Text = "Done";
}
catch (Exception ex)
{
if ("HRESULT 0x80005006" == ex.Message)
lblerror.Text = " Property does not exist at ";
else
lblerror.Text = "Failed in SetSingleProperty "+ ex.Message.ToString();
}
The following 'helper' methods (SetServerBinding and RemoveServerBinding) should be of use:
static void Main(string[] args)
{
using(DirectoryEntry site = new DirectoryEntry("IIS://Localhost/W3SVC/1234"))
{
SetServerBinding(":8080:", site);
RemoveServerBinding(":8080:", site);
RemoveServerBinding("172.16.4.99:8087:somesite.com", site);
SetServerBinding("172.16.4.99:8087:somesite.com", site);
}
}
public static void SetServerBinding(string binding, DirectoryEntry site)
{
if(site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
return;
}
site.Properties["ServerBindings"].Add(binding);
site.CommitChanges();
}
public static void RemoveServerBinding(string binding, DirectoryEntry site)
{
if (site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
}
site.CommitChanges();
}

Categories