jgrowl message is displayed unwantedly - c#

try{
myConnection.Open();
SqlCommand myCommd = new SqlCommand(StrMemberId, myConnection);
myCommd.Parameters.AddWithValue("#MemberId", TxtEnterMemberId.Text);
int value=(int)myCommd.ExecuteScalar();
if (value!= 0 )
{
Response.Redirect("GeneralExamination.aspx? MemberId=" + this.TxtEnterMemberId);
}
else
{
string js = "$.jGrowl(' Invalid Member Id Try Again ');";
Page.ClientScript.RegisterStartupScript(typeof(string), "jgrowlwarn", js, true);
TxtEnterMemberId.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally {
myConnection.Close();
}
}
What I am trying to do here is search a Member if does not exist or invalid input jgrowl will show a message(works fine).
i.) Now the problem is when i give the correct memberId a message is generated saying "thread was being aborted." but it does gets redirected to the destined page.What isthe exception about?
ii.) When i go to the next page and click on the back button.A msg box says"To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier." if i click resend the growl is displayed again. How to deal with that?
Please help to overcome the problems..

I) I think that the exception is for making a Response.Redirect inside a try/catch block, to avoid the exception you could add a false parameter to Redirect.
more info: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Related

Linq to SQL - SubmitChanges() - Check if insert was successful

I have following code -
public bool InsertUser(params)
{
User objUser = new User(params);
objDataContext.Users.InsertOnSubmit(objUser);
objDataContext.SubmitChanges();
return objUser.Id >= 0;
}
Calling method -
if (!_database.InsertUser(params))
{
//WriteErrorMessage
}
As I understand from various posts that if we want to know whether an insert was successful or not, we should check if any exception is being thrown.
However above code is relying on whether newly inserted Id is >=0 or not.
Can please guide -
If I should change above code and add a try-catch instead?
Is there any possible scenario where no error is thrown by SubmitChanges() but newly inserted Id <= 0 ?
Thank you!
If I should change above code and add a try-catch instead?
No, don't do that as in that case you will not be able to get the exact reason of failure. If you catch it then the information of failure will be lost and will not propogate to the user.
However if you think that giving exception to the user is not a good idea and you need to catch it then simply place it inside the try catch like this:
public bool SubmitChanges()
{
try{
//your code
db.SubmitChanges();
return true;
}
catch(Exception e)
{
// some code to catch exception
return false;
}
}
Is there any possible scenario where no error is thrown by SubmitChanges() but newly inserted Id <= 0 ?
If you are getting the value >=0, then there is no point to worry about this.
You can also use the GetChangeSet like this:
Gets the modified objects tracked by DataContext.
ChangeSet cs = db.GetChangeSet();
Console.Write("Changes: {0}", cs);
if your code execute the line objDataContext.SubmitChanges(); and comes on return objUser.Id >= 0; your insert will be successfull. you don't need to worry after that. let sql server and your compiler take care of the rest
Yes can use try catch to efficiently catch the error and display appropriate messages.

SqlException not passing a value

I have a handler class file, a default page and a master page.
The default page instantiates an instance of the handler class, and the handler then does all the communication with the database.
The master page contains a label that is supposed to display error outputs, passed to it from the handler via the default page. This is done via the following:
Handler:
catch (SqlException e)
{
errorString = e.ToString();
}
Default.aspx.cs:
errorString = handler.errorString;
((SiteMaster)Master).getErrorLabel.Text = errorString;
Site.Master.cs:
public Label getErrorLabel
{
get { return this.errorLabel; }
}
When I pass a value that doesn't match any record in my database, the errorString continues to hold null. Am I doing something wrong?
edit: I have also tried e.Message and e.Message.ToString() without success
Your catch() specifies an SQLException class. If the exception thrown is not of that type, then the actual exception is not handled. Try changing that to the base Exception class and see what you get. It's probably an error being thrown from somewhere else in the code.

exceptions handling after button click event

Im trying to stop processing after an exception is found and displayed it to the user but i cant get my code to stop once one has been found...
try
{
//Someting
}
catch (Exception ex)
{
lblerror.Text = (ex.Message);
//// STOP CODE WHEN EXCEPTION IS FOUND SO USER CAN FIX THE CAUSE
}
finally
{
Response.Redirect("//hud/account.aspx");
}
i have tried throw and return commands with no luck. Im new to all of this and i have googled it with no luck... any ideas what im missing ? or maybe i have the wrong idea all together. its a button click event that is tied in with a textbox, when an exception is thrown it will display the error in a label for the user to resolve (too many numbers...etc ). When corrected and the button is clicked again, this time without throwing an exception the users should be redirected. Any help would be great.
not use finally.
try
{
//Someting
Response.Redirect("//hud/account.aspx");
}
catch (Exception ex)
{
lblerror.Text = (ex.Message);
//// STOP CODE WHEN EXCEPTION IS FOUND SO USER CAN FIX THE CAUSE
}
You should not be using exceptions to do validation or flow-of-control. You should simply check the conditions in the code and present a message if the values don't satisfy the conditions.
e.g.
int foo;
if( !Int32.TryParse( something.Text, out foo ) )
{
lblError.Text = "You must enter a number.";
}
else
{
Response.Redirect...
}
You should remove the redirect logic from the finally block. Because finally block always gets executed weather an exception has encountered or not.
Probably you should try something as listed below by #user3401335. He has moved the redirect as the last statement in the try block. Your core logic stays on the top and if it is successful and no exception has encountered then it allows you to redirect. Otherwise it stops you right there with the help of exception code...
You should try as follows:
try
{
//Something
Response.Redirect("//hud/account.aspx");
}
catch (Exception ex)
{
lblerror.Text = (ex.Message);
// STOP CODE WHEN EXCEPTION IS FOUND SO USER CAN FIX THE CAUSE
}
finally
{
// PUT IN SOMETHING HERE THAT YOU WANT ALWAYS TO GET EXECUTED
}
Try this code:
bool iserror = false;
try
{
int a = 0;
int b = 1;
int c = b / a;
Response.Redirect("//hud/account.aspx");
}
catch (Exception ex)
{
lblerror.Text = (ex.Message);
iserror = true;
}
finally
{
if (!iserror)
{
//do something if you want
}
}

Label does not display text or update text when a specific method is called

I am working with a Visual WebPart (c#) which consists of an UpdatePanel which wraps the contents of the web form. On this form, within the UpdatePanel, I have an asp.net label which has its text property set based on the outcome of the submit. It's set to visible after execution, and its forecolor is changed as well depending on error or success. This works perfectly (text updates/becomes visible) until I decide to call a specific method when the submit button is pressed. When this method is called, the text property is not updating and the label is not displaying.
I have debugged this process several times and each time I step through the process and see the correct message, see it get applied to the label's text property, and complete but the page is not updated. I can reproduce the working functionality by commenting out the method call. No errors are being thrown. The program appears to execute properly while debugging.
submit button code excerpt:
try
{
CreateElementOnDestinationWebs(this.ddlSupportedElements.SelectedValue.ToString(), elementName, ref messages);
msg = String.Format("<br />We have successfully created your {0}. Please review the following outcomes: <br /><ul>", this.ddlSupportedElements.SelectedItem.Text);
foreach (string m in messages)
{
msg += String.Format("<li>{0}</li>", m);
}
msg += "</ul>";
labelMessages.Text = msg;
labelMessages.Visible = true;
labelMessages.ForeColor = System.Drawing.Color.ForestGreen;
}
catch (Exception ex)
{
msg = String.Format("<br />An unexpected error occurred while creating the item: {0}", ex.ToString());
labelMessages.Text = msg;
labelMessages.Visible = true;
labelMessages.ForeColor = System.Drawing.Color.Maroon;
}
CreateElementOnDestinationWebs source:
try
{
Guid listId = web.Lists.Add(name, "Student work can be submitted here.", SPListTemplateType.DocumentLibrary);
web.Update();
SPList newList = web.Lists[listId];
newList.OnQuickLaunch = this.checkDropBoxShowOnQuickLaunch.Checked;
newList.EnableModeration = true;
newList.Update();
GrantStudentGroupsContributeRights(web, ref newList, ref msgs);
try
{
DetectAddColumnsToDropbox(web, ref newList, ref msgs);
}
catch (Exception)
{
msgs.Add("There was an unexpected error while attempting to add the site columns to the library.");
}
msgs.Add(String.Format("Your item: {0}, has been successfully created on site: <a href='{1}' target='_blank'>{2}</a>", name, web.Url, web.Title));
}
catch (Exception)
{
msgs.Add(String.Format("An error occurred while creating the document library for student work on site: <a href='{0}' target='_blank'>{1}</a>", web.Url, web.Title));
}
If the try block containing "DetectAddColumnsToDropbox" is commented out the label (labelMessages) appears correctly. If not, the label does not appear/update. The method in question does not update any control or item on the form.
Try omitting the inner try/catch or throwing the exception back to the caller method.
Thank you everyone for taking the time to either comment or attempt to answer this issue. After continued searching I found a related issue: https://sharepoint.stackexchange.com/questions/5794/trying-to-use-an-spweb-object-that-has-been-closed-or-disposed-and-is-no-longer
The method: DetectAddColumnsToDropbox declared a variable for the rootweb of the site collection the given web was in. It then disposed the rootweb object. Turns out, SharePoint does not care for that and a JavaScript error was being thrown. I took out the dispose (using block) code and everything functions properly with labelMessages.

c#/asp.net - How to catch "System.Web.HttpException: Request timed out"?

In my asp.net/c# project I am using the iTextsharp dll to read the text from many pdf documents, but sometimes I get this error
System.Web.HttpException: Request timed out.
But the code that does it is:
public static bool does_pdf_have_keyword(string keyword, string pdf_src)
{
try
{
PdfReader pdfReader = new PdfReader(pdf_src);
string currentText;
int count = pdfReader.NumberOfPages;
for (int page = 1; page <= count; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
if (currentText.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1) return true;
}
pdfReader.Close();
return false;
}
catch
{
return false;
}
}
So why does the page go into an unhandled exception when it's in a try catch and the catch is supposed to catch everything?
I think the reason your try is not catching this exception is that the exception you're getting is not thrown from your code per se, but from the server.
Think about it this way:
Your code is running fine, it's just taking a long time.
The server monitors how long the request is taking, kills the request and throws an exception.
So your code doesn't actually throw that exception.
Now, if you want to find out about it or log it, you can use the Application_Error method in your Global.asax file (assuming you have access to it, I'm not sure how that works with SharePoint).
For example, in one of my web projects, I wanted to log all errors, even ones that weren't caught. So what I do is something like this:
protected void Application_Error(object sender, EventArgs e) {
//Log ALL uncaught exceptions
Exception exc = Server.GetLastError();
if (exc is HttpUnhandledException) {
exc = Context.Error.InnerException;
}
//Log error here
}
I'm not sure there's much you can do with it other than log it. I don't know where in the page life cycle this occurs so I'm not sure if you could do something like get the current HTTP request object and redirect the user.
Hope this helps.
You are catching the exception, but, because it's a ThreadAbortException, the framework is automatically re-throwing it. See here for more information.
The issue is that your PDF keyword searching code is (sometimes) taking longer than the specified HTTP execution timeout. I don't know what the default timeout is for Sharepoint, but you should be able to increase it.

Categories