Umbraco back office save validation - c#

In Umbraco V7 how to show custom error validation message on back office save or publish to user
I have tried following but it shows 'Publishing was cancelled by a 3rd party plugin' not actual error message
void ContentService_Saving(IContentService sender, SaveEventArgs<IContent> e)
{
e.Cancel = true;
ShowErrorBubble("Error saving item", "Error:duplicate records exists");
}
private static void ShowErrorBubble(string title, string exception)
{
try
{
umbraco.BasePages.UmbracoEnsuredPage.Current.ClientTools.ShowSpeechBubble(umbraco.BasePages.UmbracoEnsuredPage.speechBubbleIcon.error, title, exception);
}
catch (Exception ex)
{
//do nothing at the moment, forums suggest we cannot send an error message
}
}

That's an old snippet you're using. It never worked properly that way anyhow. Try this code instead:
void ContentService_Saving(IContentService sender, SaveEventArgs e)
{
ShowErrorBubble(e, "Error saving item", "Error:duplicate records exists");
}
private static void ShowErrorBubble(SaveEventArgs e, string title, string text)
{
try
{
e.Messages.Add(new Umbraco.Core.Events.EventMessage(title, text, Umbraco.Core.Events.EventMessageType.Warning));
e.Cancel = true;
}
catch (Exception ex)
{
//do nothing at the moment, forums suggest we cannot send an error message
}
}

Related

How to notify an exception in C#?

I have an exception occurred when the Database connection failed in a Class. The problem is how do I notify my Main Window that this exception is caught and show a message box to notify my user?
Thanks
Use the Try ... Catch clause like this:
try
{
// The code that could generate an exception
}
catch(Exception ex)
{
MessageBox.Show("Error: " ex.Message);
}
Or if you're using SQL-Server connection, use it like this:
try
{
// The code that could generate an exception
}
catch(SqlException ex)
{
MessageBox.Show("SQL Error: " ex.Message);
}
Thanks. I may have not make my question clearly. I mean this exception
is occurred in one class, but the message box should be show in an
other windows class. So how do I communicate and show this error?
From your clarification in one of the comments:
So if you have class TestClass.cs with method Test in it.
public void Test()
{
//if you want to throw an exception defined by your business logic
if(someCondition == false)
throw CustomException();
//if you have exception in the code
int a = 5;
int b =0;
//here you will be thrown an exception can't divide by 0.
int c = a/b;
}
Your winform Button Click or whatever
public void Button_Click1(object sender, EventArgs e)
{
try
{
TestClass cl = new TestClass();
cl.Test();
}
catch(CustomException custEx)
{
//this for your Bussines logic exception
//write your message
}
catch(DivideByZeroException div)
{
//this for divide by zero exception
//write message
}
//you can catch all other exception like this but I don't advice you to do that
catch(Exception ex)
{
//for this to working properly, this catch should be under all of others(last priority)
}
}

Append To Text File Each Error

I am using this syntax to write errors to a text file for logging in my Global.axax - it overwrites each time and only logs the most recent error. While this is helpful, it is not as helpful as I need it to be. How can I log each error that is raised?
This is my current code that only logs the most recent:
void Application_Error(object sender, EventArgs e)
{
Exception CurrentException = Server.GetLastError();
Server.ClearError();
if (CurrentException != null)
{
try
{
using (StreamWriter sw = new StreamWriter(Server.MapPath("HereAreErrors.txt")))
{
sw.WriteLine(CurrentException.ToString());
sw.Close();
}
}
catch (Exception ex) { }
}
}
As others have stated you're better off using an existing log tool to handle your logging. They have a myriad of features and, best of all, are maintained by someone else!
With that said, and in the interest of answering the question as asked, here's how to resolve your problem. It has the added benefit of creating the file if it doesn't exist.
void Application_Error(object sender, EventArgs e)
{
Exception CurrentException = Server.GetLastError();
Server.ClearError();
if (CurrentException != null)
{
try
{
File.AppendAllText(Server.MapPath("HereAreErrors.txt"), CurrentException.ToString());
}
catch (Exception ex) { }
}
}

Generating custom exception in c#

I have tried this code to raise a manual exception
protected void test ()
try
{
throw new Exception("HI"); //line22
}
catch (Exception ex) { lblerror.Text = ex.ToString(); }
but received exception below
System.ArgumentException: HI at
Project_Test_M_Test.btnsubmit_Click(Object sender, EventArgs e) in
D:\Project\Test\M_Test.aspx.cs:line 22
I want to see error message that I have send not this.
Please use ex.Message instead of ex.ToString().
btw, its not a good idea to throw the base class Exception. please use a more specific one.
This is what you need to do, use Message property to access the error message.
protected void test ()
{
try
{
throw new Exception("HI"); // Exception message passed from constructor
}
catch (Exception ex)
{
lblerror.Text = ex.Message;
}
}

Setting Custom Header in Outlook MailItem

I am working on outlook add-in where I need to set a custom header. I am using VS2010 for my development.
I am trying with the following code but it doesn't seems to be working.
private void AddUserProperty(Outlook.MailItem mail, string folderEmailId)
{
Outlook.PropertyAccessor mailPropertyAccessor = null;
try
{
if (string.IsNullOrEmpty(folderEmailId))
return;
mailPropertyAccessor = mail.PropertyAccessor;
mail.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/string/{00020386-0000-0000-C000-000000000046}/X-WorksiteFolderEmailId", folderEmailId);
mail.Save();
try
{
MessageBox.Show("Existing :" + mail.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/string/{00020386-0000-0000-C000-000000000046}/X-WorksiteFolderEmailId"));
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (System.Exception ex)
{
Logger.Error(ex);
MessageBox.Show(ex.Message);
}
finally
{
if (mailPropertyAccessor != null)
Marshal.ReleaseComObject(mailPropertyAccessor);
}
}
After saving the mail item, I am trying to fetch the same item for verification, but it's throwing an exception saying the property not found.
I don't see a problem with your code, although getting a reference directly to the PropertyAccessor is unnecessary. Try:
string prop = "http://schemas.microsoft.com/mapi/string/{00020386-0000-0000-C000-000000000046}/X-WorksiteFolderEmailId";
mail.PropertyAccessor.SetProperty(prop, folderEmailId);
mail.Save();

C# saving an image from PictureBox

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.

Categories

Resources