The title is a tad confusing, so hopefully I can explain it a tad better here. I want to change the title of the MessageBox that pops up on the screen if there is an error, since the default message is extremely long winded and I'd prefer to give a better explanation for the error that the user could understand.
private void Load_Click(object sender, RoutedEventArgs e)
{
if (comboBox.SelectedItem.ToString() == "Department Staff")
{
try
{
DataTable dt = dataSource.DataTableQuery("SELECT * FROM DepartmentStaff");
dataGrid.ItemsSource = dt.DefaultView;
}
catch (NullReferenceException ex)
{
MessageBox.Show("Unable To Connect To Database, Please Try Again Later.", ex.ToString());
}
}
else
{
try
{
DataTable dt = dataSource.DataTableQuery("SELECT * FROM Department");
dataGrid.ItemsSource = dt.DefaultView;
}
catch (NullReferenceException ex)
{
MessageBox.Show("Unable To Connect To Database, Please Try Again Later.", ex.ToString());
}
}
Take a look more carefully on the Message.Show() arguments:
Message.Show(text, caption); //the first one is text, the second one is caption.
The second argument is the caption (or title) while the first one is the message. Now in your use, you put up your exception message (which typically is very long) as the caption and that's why you get an "extremely long winded" caption (not message).
MessageBox.Show("Unable To Connect To Database, Please Try Again Later.", ex.ToString());
Don't do that! Instead, do it like this:
MessageBox.Show("Unable To Connect To Database, Please Try Again Later. " + ex.ToString(), "Error");
Simply put "Error" as caption argument.
Related
I have a program that reads the amount entered
If the user enters a non numeric input,
try {
number = Convert.ToDouble(input);
}
catch (Exception ex) {
Response.Redirect(Request.RawUrl);
Label1.Text = ex.Message;
}
But the exception message doesn't show when the page is refreshed. IS there a better way to do this?
Thanks.
I am trying to write a method that will check if a database connection is valid or not. Here is the code behind my Test Connection button.
private void TestConn_btn_Click(object sender, EventArgs e)
{
DbConnection DBConnTest;
if (DataSrc_cbx.SelectedIndex == 1)
{
DBConnTest = new SqlConnection("Server="+DatabaseAddress_Value+"; Database="+DatabaseName_Value+";Trusted_Connection=true");
try
{
DBConnTest.Open();
MessageBox.Show("\nTEST SUCCESSFUL\n");
}
catch (Exception exception)
{
MessageBox.Show("TEST FAILED Exception Thrown: " + exception.Message);
}
finally
{
DBConnTest.Close();
}
}
}
The problem is that there is no exception thrown when I enter an invalid Database address ( or leave it empty all together), same applies to the Database name. It only throws an exception when there is no connection string, or in an incorrect format. So my question is, How do I make it check if there is indeed a server and a database on that server with the names input?
You can apply validations on your Web Page if the fields are empty then prompt user to enter something. Now use this statement to check whether this database exist or not??
select name from sys.sysdatabases
where dbid=db_id()
for user you need to ..
SELECT id FROM user WHERE login="JohnSmith"
and see if it gives you any rows. If yes - user exists.
You can use this work-around.
You need to execute a query to connect to the database.
For SQL Server, I usually use IDbCommand.ExecuteScalar to execute:
SELECT ##VERSION
For Oracle:
SELECT banner from v$version where banner like 'Oracle%'
Would you provide the complete code, please?
It would be something like:
try
{
using(SqlConnection conn = ...)
{
conn.Open();
using(SqlCommand command = conn.CreateCommand())
{
command.CommandText = "SELECT ##VERSION";
var result = (string) command.ExecuteScalar();
MessageBox.Show("\nTEST SUCCESSFUL\n" + result);
}
}
}
catch(Exception ex)
{
MessageBox.Show("TEST FAILED Exception Thrown: " + exception.Message);
}
Your code is working for me. The issue here is that you have to wait till the SQL timeout period elapses before the exception is thrown. This will not be a method that returns an immediate answer. If you wrap this try/catch with a WaitCursor, you will at least see when the code is running.
private void TestConn_btn_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
DbConnection DBConnTest;
if (DataSrc_cbx.SelectedIndex == 1)
{
DBConnTest = new SqlConnection("Server="+DatabaseAddress_Value+"; Database="+DatabaseName_Value+";Trusted_Connection=true");
try
{
DBConnTest.Open();
MessageBox.Show("\nTEST SUCCESSFUL\n");
}
catch (Exception exception)
{
MessageBox.Show("TEST FAILED Exception Thrown: " + exception.Message);
}
finally
{
DBConnTest.Close();
}
}
this.Cursor = Cursors.Default;
}
Perhaps try:
using (SqlConnection conn = new SqlConnection(builder.ToString()))
{
try
{
conn.Open();
}
catch (SqlException ex)
{
foreach (SqlError error in ex.Errors)
{
Console.WriteLine(error.Number);
}
}
catch (Exception ex)
{
}
}
It will return the DB error code (run the following query for a list of error codes:
select * from sys.messages where language_id=1033 and severity between 11 and 16
Microsoft also provide some guidance here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlerror.number(v=vs.110).aspx
Your code looks incomplete!
Take this example from Microsoft.conexão c# com sql server 2008
Good luck!
I personally find vague error messages a pain. In my new practice project I am trying to add additional validation to the user input. However, ASP.NET MembershipCreateStatus has Members; e.g. InvalidEmail that takes care of some of these areas when the CreateUser Method is used.
I can do an if statement or Regex on the submitted email before the input reaches the Membership.CreateUser Method. However, I am not sure where to start with this:
I know this question is a little subjective but I hate to find out later that there is a better way, and if you are just starting up, it can be a lifesaver.
Should I create an additional validation Method to check for very specific formatting errors in the email, in addition to the system checking. As you can see the error message does not say why it is invalid.
Also is it possible to create my own enum for example, email contains underscore, which I can attached to the MembershipCreateStatus? If so how?
Here is my sample code, abbreviated:
public string GetErrorMessage(MembershipCreateStatus status)
{
switch (status)
{
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid.";
default:
return "Go to jail!!";
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
Membership.CreateUser(txtUserName.Text, txtPassword.Text, txtEmail.Text);
}
catch (MembershipCreateUserException ex)
{
ltrStatusMsg.Text = GetErrorMessage(ex.StatusCode);
}
catch (HttpException ex)
{
ltrStatusMsg.Text = ex.Message;
}
}
Thanks my friends.
There are lots of ways to skin a cat. Certainly you can do your own validation before calling Membership.CreateUser. Your validation method could throw a MembershipCreateUserException and reuse one of the existing status codes, or throw a different exception. The exception you throw could be a custom exception, or you could reuse an existing exception type such as ValidationException.
try
{
ValidateUser(txtUserName.Text, txtPassword.Text, txtEmail.Text);
Membership.CreateUser(txtUserName.Text, txtPassword.Text, txtEmail.Text);
}
catch (MembershipCreateUserException ex)
{
ltrStatusMsg.Text = GetErrorMessage(ex.StatusCode);
}
catch (ValidationException ex)
{
ltrStatusMsg.Text = ex.Message;
}
catch (Exception ex)
{
// log exception ...
ltrStatusMsg.Text = "An unexpected error occurred while creating the user";
}
...
private void ValidateUser(...)
{
if (... not valid ...) throw new ValidationException("some suitable message");
}
In my CustomMembershipProvider I don't use the CreateUser method, I have a CreateUser method as part of my User business object code with an output parameter (Custom Enum) with the various invalid (or valid) result.
I want to simply notify the user that they have successfully inserted new data to a database.
This is what I have so far:
try { cont.NewMember(txtSS.Text, txtName.Text, txtCity.Text, txtStreet.Text, txtZipcode.Text, txtEmail.Text, txtPhone.Text); }
catch (SqlException ex) { MessageBox.Show("The social security number \"" + txtSS.Text + "\"is already registered"); }
MessageBox.Show("Added succesfully");
I want to show the "Added successfully" only if (obviously) there wasn't an Exception. The update itself is working fine but the message "Added..." is always showing (even when there was an exception).
How can I solve this, using C#?
put the MessageBox... statement at the end of the try block
try
{
cont.NewMember(txtSS.Text, txtName.Text, txtCity.Text, txtStreet.Text, txtZipcode.Text, txtEmail.Text, txtPhone.Text);
MessageBox.Show("Added succesfully");
}
catch (SqlException ex)
{
MessageBox.Show("The social security number \"" + txtSS.Text + "\"is already registered");
}
this is not the correct approach. how would you know that the exception is because the SSN already existed in the database. It could throw an exception for many other cases like connection failure etc...
the best practice is to handle all these in the database.
Refer to handling exceptions in the database.
i have a code like this:
private void Load_Button_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog()==DialogResult.OK){
MessageBox.Show(dialog.FileName,"My Application", MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
string s;
s=".bmp";
if (dialog.FileName.Substring(dialog.FileName.LastIndexOf('.')).Equals(s))
{
picBox_1.Load(dialog.FileName);
BitmapFile = new Bitmap(dialog.FileName.ToString());
}
else {
MessageBox.Show("Not a BMP file!");
}
}
}
so, load image. and have an error in this:
private void Save_Button_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
try
{
if (picBox_1.Image != null)
{
if (dialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(dialog.FileName, "My Application", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
string s;
s = ".bmp";
if (dialog.FileName.Substring(dialog.FileName.LastIndexOf('.')).Equals(s))
{
picBox_1.Image.Save(dialog.FileName.ToString());
//BitmapFile.Dispose();
}
else
{
MessageBox.Show("Not a BMP file!");
}
}
}
else
{
MessageBox.Show("My PicBox is empty!");
}
}
catch (Exception) { MessageBox.Show("Cannot save file, error!"); }
}
this is general GDI error. I suppose, that i can't write to file (not enough rights, maybe). how can i improve this error?
you should catch the exceptions properly, not with a MessageBox which tells you nothing about the exact exception thrown!
at minimum your catch block should look like this:
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
and I say at minimum because you should in fact log the exception somewhere, using a logging framework like NLog or Log4Net and dump stack trace and other details. You are not even able to tell the excact type of Exception if you show a message with a static string and not the details of the actual exception.
You should only catch specific exceptions that you intend to handle or recover from, and log the details. Never catch Exception as you would potentially be masking bigger issues with your server if they occur.
Unexpected exceptions should bubble up so that the cause can quickly be identified when they occur.
See here for Best Practices for Handling Exceptions.
You're eating the exception and losing all the juicy detail. Try changing your catch block to something like this to see what's going on:
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString(), "Error Saving Image", MessageBoxIcons.Error);
}
Also, consider implementing some logging (to the event viewer and/or text file. This will allow you to have a simple message box, but with all the juicy detail put somewhere useful to fetch after the event.
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error Saving Image", MessageBoxIcon.Error);
// _logger is a private field on this class in this case.
_logger.Log(ex, string.Format("Saving image to {0}", dialog.Filename))
}
You could look at Log4net amongst other things for the actual logging, but at the very least write a class to write exception detail to the event viewer.