I have my own exception based on some condition and want to raise an alert when control comes in this catch block
catch (ApplicationException ex)
{
//want to call window.alert function here
}
Do you mean, a message box?
MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx
It's a bit hard to give a definitive answer without a bit more information, but one usual way is to register a startup script:
try
{
...
}
catch(ApplicationException ex){
Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
}
if you are using ajax in your page that require script manager Page.ClientScript
will not work,
Try this and it would do the work:
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"alertMessage", #"alert('your Message ')", true);
You can use the following extension method from any web page or nested user control:
static class Extensions
{
public static void ShowAlert(this Control control, string message)
{
if (!control.Page.ClientScript.IsClientScriptBlockRegistered("PopupScript"))
{
var script = String.Format("<script type='text/javascript' language='javascript'>alert('{0}')</script>", message);
control.Page.ClientScript.RegisterClientScriptBlock(control.Page.GetType(), "PopupScript", script);
}
}
}
like this:
class YourPage : Page
{
private void YourMethod()
{
try
{
// do stuff
}
catch(Exception ex)
{
this.ShowAlert(ex.Message);
}
}
}
You can also do this :
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showError",
"alert('" + ex.Message + "');", true);
}
this will show the exeption message in the alert box
MessageBox like others said, or RegisterClientScriptBlock if you want something more arbitrary, but your use case is extremely dubious. Merely displaying exceptions is not something you want to do in production code - you don't want to expose that detail publicly and you do want to record it with proper logging privately.
I'm not sure if I understand but I'm guessing that you're trying to show a MessageBox from ASP.Net?
If so, this code project article might be helpful: Simple MessageBox functionality in ASP.NET
Simple use this to show the alert message box in code behind.
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Record Saved Sucessfully');", true);
You can try this:
Hope it works for you..
`private void validateUserEntry()
{
// Checks the value of the text.
if(serverName.Text.Length == 0)
{
// Initializes the variables to pass to the MessageBox.Show method.
string message = "You did not enter a server name. Cancel this operation?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}`
You should try this.
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Sakla Test');", true);
Related
I have two near identical forms on the site and only one of them works. On firing button click they're supposed to collect text from checkbox fields and email that information on. One of the forms try is completely ignored and the error message in catch is displayed
Using the working form on the new page still won't work makes me think there may be issues with the page, but deleting the aspx and aspx.cs pages and rewriting them when it may not be that serious is not something I want to do if it's not necessary. I've tried removing 'if (IsPostBack)' and 'if (LiabilityCheckBox.Checked == true)' on the form with issues among other things, but nothing seems to help.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
if (LiabilityCheckBox.Checked == true)
{
// validate the Captcha to check we're not dealing with a bot
bool isHuman = ExampleCaptcha.Validate(CaptchaCodeTextBox.Text);
CaptchaCodeTextBox.Text = null; // clear previous user input
if (!isHuman)
{
lblCaptchaError.Visible = true;
lblCaptchaError.Text = "Incorrect Code. Please try again!";
}
else
{
try
{
//some code
lblRegMessage.Text =
("Registration Successful. Thank you for entering."
+ "Please click button below to finalise Payment and Registration.");
// Clear the textbox values
//Show Continue Button.
ContinueButton.Visible = true;
}
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
}
}
else
{
lblMessage.Text = ("You must check the Liability check box to continue");
}
}
}
I am expecting the result of filling out the form to be the mail is sent and a message appears telling the user "Registration Successful. Thank you for entering."
What I am getting is this:
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
As I checked, your code missing some closing brackets. Please check the brackets are properly closed and in the series.
I created a simple e_form with insertion button, I wanna add pop up message if the insertion process succeed, I add it alone and it works but when combining it with my code I got an error.
my code is
protected void ImageButton1_Click(object sender, EventArgs e)
{
// connection stuff...
cmd.Parameters.AddWithValue("#full_name", TextBox1.Text);
cmd.Parameters.AddWithValue("#dob", TextBox5.Text);
cmd.Parameters.AddWithValue("#id_no", TextBox2.Text);
int result;
result=cmd.ExecuteNonQuery();
if result >0
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"script", "<script>data has been added successfully</script>");
con.close();
}
}
I think you need to check few things before executing the SQL query.
i)are your html DOM elements are populated as soon as the page because RegisterStartupScript method places javascript at the bottom of the page just before closing of the element.
ii)is our ExecuteNonQuery returning result.
RegisterStartupScript (type type,string key,string script,bool addtags) is mostly used for scripts that must run on page load but your code must run on image button click,so use below method
int result = 1;
if (result==1)
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"script", "alert('data has been added successfully');", true);
}
This should work..Cheers
The if requires brackets
if(result > 0)
I would also suggest adding a label or alert. The ,true adds the tags
Page.ClientScript.RegisterStartupScript(this.GetType(),
"script", "alert('data has been added successfully');", true);
I have a textbox and a dropdownlist. The textbox is defaulted to 1 but if the user enters a different value into the textbox they must select a value from the dropdownlist. If they do not select a value from the dropdownlist then the exception message appears, and the changes they made to the textbox will not be saved. The problem is the value in the textbox is still there when I reopen the page. If I manually refresh the page, then it defaults back to 1. So I am trying to refresh the page after the exception message appears, but if I put code to refresh the page after the exception then the message doesn't appear anymore.
How can I refresh the page after the user closes the exception message?
JobPieceSerialNo SerNo = new JobPieceSerialNo(job.ID);
if (SerNo.Reason == null)
{
throw new Exception("Must select reason");
}
catch (Exception ex)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "Message",
"<script>$(document).ready(function () { $(\"<div>" + "Please note : " + ex.Message + "</div>\").dialog({modal: true,title: \"NOTE\",buttons: [ { text: \"Ok\", click: function() { $( this ).dialog( \"close\" ); } } ]}); ShowHidePointToPoint('OVERNIGHT');});</script>");
Response.Redirect("Job.aspx?JobID=" + Request.QueryString["JobID"], false);
}
You almost certainly don't want to be throwing an Exception here, it looks like you're using an exception to handle normal UI validation and if so that's quite unusual.
There are some pretty standard ways of validating user input and presenting validation results back to the user, this article describes simple c# validation which seems to fit your problem better than throwing and catching an Exception.
You can use windows.location after closing dialog
your catch would be like this:
catch (Exception ex)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "Message",
"<script>$(document).ready(function () { $(\"<div>" + "Please note : " + ex.Message + "</div>\").dialog({modal: true,title: \"NOTE\",buttons: [ { text: \"Ok\", click: function() { $( this ).dialog( \"close\" ); window.location.href = 'Default.aspx'; } } ]}); ShowHidePointToPoint('OVERNIGHT');});</script>");
}
or you can also change the window location to the current page in close function of your dialog.
JQuery UI dialog have a close event:
$( ".selector" ).dialog({
close: function( event, ui ) {window.location.href ="Job.aspx";}
});
I have an application that performs a time consuming task when the user selects an item for a listbox.
When a user selects a show the application will retrieve all the shows information form the tvdb and the display it in the Ui.
The problem occurs when a user quickly changes selection while the show is still loading.
I would like to make it so that a user could change their mind and then make another selection while the first was loading and have that information displayed in the Ui.
I have created a simple demonstration application to show the problem : Demo App .
This is what i tried to do
List box selection event handler
private void lb1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string sid = lb1.SelectedItem.ToString();
try
{
LoadSeries(Int32.Parse(sid));
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid series id");
}
}
LoadSeries
private void LoadSeries(int _seriesId)
{
Task<TvdbSeries> series = Task.Factory.StartNew(() =>
{
TvdbSeries seriesloaded = null;
try
{
seriesloaded = m_tvdbHandler.GetSeries(_seriesId, TvdbLanguage.DefaultLanguage, true, true, true, true);
}
catch (TvdbInvalidApiKeyException ex)
{
MessageBox.Show(ex.Message);
}
catch (TvdbNotAvailableException ex)
{
MessageBox.Show(ex.Message);
}
return seriesloaded;
}
);
series.ContinueWith((antecedent) =>
{
UpdateSeries(series.Result);
},
TaskScheduler.FromCurrentSynchronizationContext()
);
}
If a user changes selection quickly the application errors on the line seriesloaded = m_tvdbHandler.GetSeries(_seriesId, TvdbLanguage.DefaultLanguage, true, true, true, true); and shows this message in the debugger "WebClient does not support concurrent I/O operations."
I did find out that it is because I am making a new request before the last one is finished but I have no way of chaining the code in m_tvdbHandler.GetSeries because its functionality comes from library i am using and some one else wrote .
This is the library tvdblib , I am sure the problem is with how I am doing things and not the library .
when a user makes a selection you can disable the UI till the information is loaded completely and display a message at the bottom loading please wait. Once everything is loaded, enable the Ui and hide the message.
You are posting this question as a C#5.0 question, so you should be using async/await as much as you can.
private Task<TvdbSeries> LoadSeriesAsync(int _seriesId)
{
return Task.Run(() =>
{
TvdbSeries seriesloaded = null;
try
{
seriesloaded = m_tvdbHandler.GetSeries(_seriesId, TvdbLanguage.DefaultLanguage, true, true, true, true);
}
catch (TvdbInvalidApiKeyException ex)
{
MessageBox.Show(ex.Message);
}
catch (TvdbNotAvailableException ex)
{
MessageBox.Show(ex.Message);
}
return seriesloaded;
}
);
}
It would be much better if there was a LoadSeriesAsync.
One way to do it would be to disable lb1 while retrieving the series.
private async void lb1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string sid = lb1.SelectedItem.ToString();
try
{
lb1.IsEnabled = false;
var series = await LoadSeriesAsync(Int32.Parse(sid));
UpdateSeries(series);
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid series id");
lb1.IsEnabled = true;
}
}
Does anyone know how can I create a pop-up message box in server side, so that it will display the error message in the pop-up message box when save process is failed?
Example:
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
using (TransactionScope scope = new TransactionScope())
{
//save process
scope.Complete();
Response.Redirect(url);
}
}
catch (TransactionAbortedException ex)
{
//pop-up message box to show error message
}
catch (ApplicationException ex)
{
//pop-up message box to show error message
}
}
How can I able to create a pop-up message box within the catch to pop-up the error message box to the user when the save process is failed?
Try using either the Page.RegisterStartupScript or ClientScript.RegisterStartupScript methods.
ClientScript.RegisterStartupScript(
this.GetType(), "myalert", "alert('" + errorText + "');", true);
or
Response.Write(
#"<SCRIPT LANGUAGE=""JavaScript"">alert('" + errorText + "')</SCRIPT>");
Here's one way:
/// ---- ShowAlert --------------------------------
///
/// <summary>
/// popup a message box at the client
/// </summary>
/// <param name="page">A Page Object</param>
/// <param name="message">The Message to show</param>
public static void ShowAlert(Page page, String message)
{
String Output;
Output = String.Format("alert('{0}');",message);
page.ClientScript.RegisterStartupScript(page.GetType(), "Key", Output, true);
}
While the alert() scripts mentioned are OK, they come across pretty amateurish. I would recommend two options.
Have a label on your page which is normally hidden with font color red, and bold. Then just make it visible and set the text on error.
If you want a dialog behavior, use what everyone is showing you, but instead of popping up an alert, pick something nice from jQuery UI with a nice error icon and even a help link or something in the dialog. Here's an example: http://jqueryui.com/demos/dialog/#modal-message
Of course, if you want your app to seem more reliable, don't show them any error. :)