I have an ASP.net web app that spawns a process (in a thread). This thread calls a '.dll' to connect to another 'subsystem'.
Problem is, when there are errors connecting to the 'subsystem', it affects my main application (main UI) and I get a 'connection refused message'. I have already put in 'try-catch' error handling routines in my thread. FYI, I would like to treat the thread as a 'Fire and forget' thread.
The thread is spawned when btnSubmit is clicked.
Please refer to trimmed-down extract of code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
txt_hide.Value = sStatus;
if (sStatus == "")
{
//create thread for posting
id = Guid.NewGuid();
Thread th = new Thread(() => postXMLClass.PostXML(sSeqNo));
th.Start();
sStatus = "Transaction generated..please check posting status..";
lblMessage.Text = "Transaction Generated...";
}
else
{
FormView1.DataBind(); //refresh the form
clib.Show2("Error generating transaction : " + sStatus, sender);
lblMessage.Text = "Error generating transaction : " + sStatus;
}
}
catch (SqlException ex)
{
lblMessage.Text = "Error generating transaction ...: " + ex.Message;
}
catch (Exception ex)
{
//sqc.Transaction.Rollback();
lblMessage.Text = "Error encountered...: " + ex.Message;
throw;
}
finally
{
if (dbc != null) dbc.Dispose();
if (clib != null) clib.Dispose();
}
}
public static void PostXML(string inlinkcode)
{
string sToken = "", sXMLOut = "";
Xml.Router.XMLRouter cX = new Xml.Router.XMLRouter();
try
{
cX.set_Options("com.xml.router.nameServer", appSetArray[0]);
cX.set_Options("com.xml.router.nameServerPort", appSetArray[2]);
cX.set_Options("com.xml.router.logicalServerName", appSetArray[1]);
{
sLinkcode = inlinkcode;
if (sLinkcode != null && sLinkcode != "")
{
strxml = "<?xml version=\"1.0\" encoding='UTF-8' ?>";
strxml += "<TableLinkRequest version=\"1.0\"><DocumentLinkStart><Request><StartParams>";
strxml += "<CmpCode>X</CmpCode><DocCode></DocCode></TableLinkRequest>";
sXMLOut = cX.Send(sToken, strxml);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception {0}", ex.Message);
}
finally
{
if (cX != null) cX.Logoff(sToken);
}
}
I'm going to create form contact in asp.net mvc 4. I have yet form in html and code in controller. And his looks like:
[HttpPost]
public ActionResult Kontakt(KontaktModel k)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(k.Mail.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("myemail#gmail.com");
msg.Subject = k.Temat.ToString();
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
sb.Append("Nick / Imię i nazwisko: " + k.Name);
sb.Append(Environment.NewLine);
sb.Append("Typ problemu: " + k.TypProblemu);
sb.Append(Environment.NewLine);
sb.Append("Treść:");
sb.Append(Environment.NewLine);
sb.Append(k.Tresc);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View("SUCCESS");
}
catch(Exception)
{
return View("Error");
}
}
return View();
}
}
But when I clicked to button app return Error.cshtml. I have a question, how I can know how exception catched? I don't know why it does not work. Any ideas?
The answer should be to get the Exception Message and put inside a ViewBag.Message and show it in the Error.cshtml view.
Error:
#ViewBag.Message
But is good to know little more about Exception and Exception Handling. If you only declare a try catch and a exception happen it will go inside the catch is the same if you do try catch(Exception) if you want to know more detail about the exception is happening you can declare a variable, example :
try{
///code
}catch(Exception e){}
and then you can watch inside the variable for more detail.
The good practice is to know what type of exception you can receive and handle, here is a link that have a good explanation Exception and Exception Handling
Example:
try
{
//code
}
catch(Exception c)
{
ViewBag.Message = c.Message
return View("ERROR");
}
I have run the following code without issue dozens of times, but now it is returning
"Object reference not set to an instance of an object" on the DataBind:
DataSet ds = oHelper.GetDependents(gSelectedContact);
if (ds.Tables[0].Rows.Count > 0)
{
try
{
gvDependents.DataSource = ds;
gvDependents.DataBind();
gvDependents.Columns[1].Visible = false;
btnEnroll.Enabled = true;
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}
Rows.Count = 3. There are 8 columns and all are populated as expected. The ex.innerhtml is null. As far as I know nothing's changed from this morning when this ran aok. Any ideas? Thank you.
There are other similar questions to this, but I don't feel like it answers mine. From a Java servlet I need to be able to ssh to any server on my company's network and dynamically handle this unknown key exception and then issue a command to get and display the current status of the server.
I saw one suggestion to use JSch session.setFingerprint, but it must have changed or something because far as I can tell, it doesn't exist. I'm using Netbeans.
Here's my code:
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String url = "validurl";
String user = "validuser";
String password = "validpassword";
printer.println ("HelloWorld!");
JSch ssh = new JSch();
ChannelShell ch = null;
Session session = null;
try {
session = ssh.getSession(user, "serverIP", 22);
session.setPassword(password);
session.connect();
ch = (ChannelShell)session.openChannel("shell");
ch.connect();
}
catch (JSchException e) {
System.out.println ("Exception: " + e);
}
catch (Exception e) {
System.out.println ("Exception: " + e);
}
Thanks!
Devin
I identified a bug in my code and I'm baffled as to how it could have occurred in the first place.
My question is, I found a skip in the database ID fields (it is an incremented identity field), indicating some records weren't inserted - which means my SQL sprocs (probably) threw an error. Thinking backwards from there, that means that my business object should have caught that error and thrown it, exiting immediately and returning back to the page's codebehind (instead it continued right on to the second stored procedure). I don't understand why or how this is possible. What's going on in respect to the code execution skipping my try catches?
Page code behind:
protected void submitbutton_click(object sender, EventArgs e){
try{
mybusinessobject.savetodatabase()
} catch( Exception ex) {
Response.Redirect("Error.aspx");
}
}
business object code:
public static void savetodatabase(){
int ID1=-1;
int ID2=-1;
//store the billing contact
SqlCommand cmd1 = new SqlCommand("SaveInfo1", con);
cmd1.CommandType = CommandType.StoredProcedure;
//...
cmd1.Parameters.Add("#Ret", SqlDbType.Int);
cmd1.Parameters["#Ret"].Direction = ParameterDirection.ReturnValue;
try
{
con.Open();
cmd1 .ExecuteNonQuery();
ID1 = Convert.ToInt32(cmd1.Parameters["#Ret"].Value);
}
catch (Exception ex) { throw ex; }
finally { con.Close(); }
if (ID1 > 0)
{
SqlCommand cmd = new SqlCommand("SaveInfo2", con);
cmd.CommandType = CommandType.StoredProcedure;
//...
try
{
con.Open();
cmd.ExecuteNonQuery();
ID2= Convert.ToInt32(cmd.Parameters["#Ret"].Value);
}
catch (Exception ex) { throw ex; }
finally { con.Close(); }
}
}
SQL Code:
PROCEDURE [dbo].[SaveInfo1]
(
-- ... parameters ...
)
AS
INSERT INTO Table1 ( ... ) Values ( ... )
RETURN SCOPE_IDENTITY
PROCEDURE [dbo].[SaveInfo2]
(
-- ... parameters ...
)
AS
DECLARE #SpecialID INT
INSERT INTO Table2 ( ... ) Values ( ... )
SET #SpecialID = SCOPE_IDENTITY()
INSERT INTO Table3 ( [ID], ... ) Values ( #SpecialID, ... )
RETURN SCOPE_IDENTITY()
Your exception handling is horrible. Never do this:
catch (Exception ex) { throw ex; }
All that accomplishes is to screw up the stack trace in the exception. It makes it look like the exception originated at the point of the throw.
Never do this:
try{
mybusinessobject.savetodatabase()
} catch( Exception ex) {
Response.Redirect("Error.aspx");
}
You don't know what exception happened. You have no idea whether or not it's safe to redirect, and on top of it all, you lose all information about what the exception was!
You should also get into the habit of implementing using blocks:
public static void savetodatabase()
{
using (SqlConnection con = new SqlConnection("Connectionstring"))
{
int ID1;
//store the billing contact
using (SqlCommand cmd1 = new SqlCommand("SaveInfo1", con))
{
cmd1.CommandType = CommandType.StoredProcedure;
//...
cmd1.Parameters.Add("#Ret", SqlDbType.Int);
cmd1.Parameters["#Ret"].Direction = ParameterDirection.ReturnValue;
con.Open();
cmd1.ExecuteNonQuery();
ID1 = Convert.ToInt32(cmd1.Parameters["#Ret"].Value);
}
if (ID1 <= 0)
{
return;
}
int ID2 = -1;
using (SqlCommand cmd = new SqlCommand("SaveInfo2", con))
{
cmd.CommandType = CommandType.StoredProcedure;
//...
con.Open();
cmd.ExecuteNonQuery();
ID2 = Convert.ToInt32(cmd.Parameters["#Ret"].Value);
}
}
}
A using block will ensure that the resource will have its Dispose method called, whether or not an exception is thrown.
Isn't the more likely scenario that someone just deleted some records from the table?
If records are deleted, their unique identifiers will not be recycled, even when new records are later inserted. You can use RESEED in SQL to reset the identity seed to 0 if you desire, but I suggest against that unless you wipe the table. Otherwise you could end up with primary key violations.
Also, make sure your column's identity seed is set to increment 1 at a time.
Your code doesn't matter, just go to Web.config and play with appropriate node:
<customErrors mode="On|Off" />
P.S.
Use the using clause to auto-close a connection, instead of manual in the finally clause
you can test the catch. just change the procedure:
PROCEDURE [dbo].[SaveInfo1]
(
-- ... parameters ...
)
AS
INSERT INTO Table1 ( ... ) Values ( ..., some_out_of_range_value_here, ....)
RETURN SCOPE_IDENTITY()
to have some hard coded out of range value (so the insert fails), and then run your application...