|
Just use *.docx instead *.doc for the name of your document and that is it.
|
|
|
|
|
Is there a way to cut down on the individual exception handling code placed in classes and methods so it can be centralized but not result in termination.
I can see that you can use program.cs and put a try/catch around Application.Run. The exception can be caught. This provides a basis for logging and informing the user, but the application still terminates after the catch logic.
You can put an Application.Run in the catch and get it to start over one more time, but the next exception cannot be caught. So its not much use.
The solution I am trying to determine would look something like:
Form1.cs:
using System;
using System.Windows.Forms;namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void testMethod()
{
throw new ArgumentException("Invalid parameter");
}
private void nextMethod()
{
}
}
}
Program.cs:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
catch
{
}
}
}
}
The return to previous level and continue does not seem possible. I am then left with sprinkling exception handling code throughout the application and replicating catch blocks to some degree.
It seems to me that there must be a way to create a centralized exception handler and reduce the number of try/catch blocks overall.
I have read quite a few articles but none seem to address this issue. I realize I can try to reduce the exception handling with logic and rethrow exceptiosn, etc. But this still leaves the issue open for me.
Am I missing something?
Any ideas welcome.
Thanks.
REMEMBER: THIS WAS ORIGINALLY POSTED IN Q/A BY SOMEONE ELSE, AND WAS MOVED HERE BECAUSE A THREADED DISCUSSION WAS MORE APPROPRIATE.
.45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
|
|
|
|
|
If all the OP wants is to get the app restarted again, then this should suffice:
static class Program {
[STAThread]
static void Main() {
try {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
} catch(Exception exc) {
somehowLogException(exc);
Application.Restart();
}
}
}
Application.Restart() starts the same app over again, in a new process. The drawbacks should be obvious: the current status will be lost, anything the user has entered/done and wasn't persisted somehow is gone, and some categories of problems will just occur over and over, e.g. a FileNotFound situation typically does not get solved by trying again.
IMO the question doesn't make much sense, there is no general solution to run-time problems, a problem should be handled locally if it can be solved at that level, or propagated up the calling chain.
BTW: very good of you to promote the question from Q&A to a programming forum!
|
|
|
|
|
I missed the Restart Method. Thanks.
In trying this, it starts another instance, and has a dialogue box that pops up if the user creates the same exception repeatedly. The box has retry or quit buttons.
This is helpful.
Thanks.
"Coding for fun and profit ... mostly fun"
|
|
|
|
|
To your "does not make much sense" comment
My goal was to try to find a way to cut down on repetitive coding of try/catch/finally blocks by centralizing the exception handling. There is a lot of repetitive coding to deal with exceptions. A lot of exceptions are somewhat routine.
Do you use try/catch/finally in all of your methods and just try to minimize them with logic? or what would you suggest?
Maybe I am not approaching exceptions efficiently?
Thanks.
"Coding for fun and profit ... mostly fun"
|
|
|
|
|
The general rule is: One must solve a problem at the level where one can solve the problem. Here is a fictitious example (a simple web browser), first without any error checking, without try/catch. Assume a URL is entered in the appropriate TextBox and some button gets clicked (or the ENTER key gets hit), causing the Navigate method to be called.
class Program {
public static Main() {
Application.Run(new Browser());
}
}
class Browser : Form {
public Navigate(string URL) {
string HTML=GetWebPage(URL);
WebPage page=DecodeHtml(HTML);
ShowPage(page);
}
}
Now assume the HTML is invalid (say a missing </table> tag), so the DecodeHtml method throws an exception, navigate fails, the Exception reaches Main, the app crashes. Good? I don't think so. Now put try/catch in Main. Any better? No, Main cannot solve the problem, all it could do is nicely tell the user "Something went wrong, and I quit (or I restart)", so whatever the user had done till then is lost. Not good.
Now assume Navigate has a separate try/catch around each of its lines; DecodeHtml fails, so page is null, causing ShowPage to either fail or show an empty page. Good? I don't think so, the user expects to see a page, and when some HTML error occurs, he still wants to see as much as possible of that page.
Now have some try/catch inside DecodeHtml(). It could hold a lot of the decoding stuff, and try and guess what was intended, i.e. return a page as well as it can plus signal something isn't quite OK, maybe showing an error message in a status bar. This would be acceptable behavior from the user's point of view. Hence, that is what must be done.
Does this mean, the lowest level must solve all problems? No. It means the lowest level must solve the problems it can deal with well, and it must propagate the ones it cannot adequately handle, to the higher level (the caller).
Another example, not quite about exceptions, more about user errors: a compiler will easily detect your mistakes in the source files you feed it. Do you want the compiler to crash at the first error? You don't. Do you want the compiler to continue compiling and report more errors? You do (up to a point, getting more than 100 error messages isn't really helpful). So the compiler should not give up, it should try and continue to satisfy the user's expectations. And yes, that may take a lot of code.
In the end it is a balance between the user's comfort and the programmer's effort. And IMO the user is much more important than the programmer, as he is the paying customer; and there could be a lot of them.
|
|
|
|
|
Thanks for the guidance.
"Coding for fun and profit ... mostly fun"
|
|
|
|
|
John Simmons / outlaw programmer wrote: It seems to me that there must be a way to create a centralized exception handler and reduce the number of try/catch blocks overall.
There is - in .NET there's an UnhandledException in the AppDomain class which allows you to catch almost all unmanaged exceptions (the exception to this rule, no pun intended, being terminal exceptions such as StackOverflowException ).
|
|
|
|
|
using System;
using System.Security.Permissions;
public class Test {
[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
public static void Example()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
try {
throw new Exception("1");
} catch (Exception e) {
Console.WriteLine("Catch clause caught : " + e.Message);
}
throw new Exception("2");
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
}
public static void Main() {
Example();
}
}
This works.
If the user recreates the exception (they do pound on the keys and mouse) it does not seem to catch the second throw. Not sure there is a way to deal with that. This helps as part of the solution.
Thanks.
"Coding for fun and profit ... mostly fun"
|
|
|
|
|
Well, in Windows.Forms you can use Application.ThreadException event:
static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
}
I have never used it, but I guess it might be useful sometimes.
|
|
|
|
|
I tried this but could not get it to catch the unhandled exception.
MS suggests adding:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
But that did not enable the catch either.
I must be missing something?
"Coding for fun and profit ... mostly fun"
|
|
|
|
|
I think this event cannot be raised if you run the application in debug mode. Have you tried without debugging?
|
|
|
|
|
Hmm ... I have not. The other methods do run however. I can try it.
I did notice that there was an example that used the following.
static void Application_ThreadException(object sender, ThreadExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
MessageBox.Show(args.ToString());
}
This is different than what I originally used. The problem is that the ExceptionObject for the ThreatExceptionEventArgs is not supported in .NET 4.0. So I guess this code is obsolete.
They seem to have gone to the AppDomain Class and its similar tools. I don't know why. This approach is supported in .NET 4.0.
So I guess I need to use that class instead.
Thanks for working through this with me.
I am learning as I go. More experienced C# developers like you are greatly appreciated.
"Coding for fun and profit ... mostly fun"
|
|
|
|
|
Errr, I don't know where you got that sample, but MS documentation for 4.0 version doesn't say so for ThreadExceptionEventArgs[^].
UnhandledException event in AppDomain is slightly different becouse here the application will always end when your handler finishes, but with ThreadException event you still have an option to recover from the problem and let the application keep on running.
|
|
|
|
|
I found the following reference in my local copy of the .NET doc
ThreadExceptionEventArgs Class
Provides data for the ThreadException event.
Namespace: System.Threading
Assembly: System (in System.dll)
...
PlatformsWindows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information.NET Framework
Supported in: <big>3.5, 3.0, 2.0, 1.1, 1.0</big>
I also see another doc reference in the online 4.0 doc
http://msdn.microsoft.com/en-us/library/system.threading.threadexceptioneventargs.aspx[^]
This reference has a different code example to try.
Thanks for pointing this out. The doc on theis topic is a bit thick and confusing to sort out and follow.
So far I have decided that using a try/catch in Program.cs with the Application.Restart() is the best for me at present.
I can log, warn the user, and let them try different approaches and/or parts of the program.
I have found that an actual crash scares them off. As long as there is controlled execution, graceful exits,
and no eroneous results they are happier.
"Coding for fun and profit ... mostly fun"
|
|
|
|
|
I always think of Exception Handling as a two step process;
1. There are going to be exceptional circumstances under which errors occur, which, due to good analysis, testing or experience can be handled at a reasonably low level. I usually consider database access as good example of this as the availability of the database should be considered outside of the scope of control of any DAL, (Data Access Layer), BLL, (Business Logic Layer), or UI.
2. In a project of any size there is usually going to be unpredictable responses to certain actions, some of which will generate exceptions and the reality is you simply cannot, (and should not), attempt to protect every method, event handler etc. within an Exception Handler. However, should an unpredicted, or unpredictable exception occur an application should handle it gracefully and take appropriate action based on the exception type, which as a programmer it is your job to consider.
My approach is typically to protect more sensitive and/or predictable area's of code with explicit exception handlers, but then to also attempt to protect an application at run time so that anything exceptional/unpredictable occurring is logged appropriately and potentially reported to the end user. The granular try...catch approach is obviously self explanatory, but the high level approach I normally undertake with an ExceptionManagement class which when instantiated subscribes to the '' and '' events and which itself can be configured at instantiation to tog or report handles exceptions in a predefined manner;
public class ExceptionManager : IDisposable
{
public ExceptionLogger()
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
}
}
static class Program
{
internal const string C_ExecutingApplicationName = "My Application Name";
private static Form mainForm;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
ExceptionManager exceptionManager = ExceptionManager();
ExceptionManager exceptionManager = new ExceptionManager();
mainForm = new Forms.Main();
Application.Run(mainForm);
}
}
Rhys
"With no power comes no responsibility"
|
|
|
|
|
Hi all
can any one help me to create a datetimepicker which selects multiple dates from the calendar control(windows form application).
thanks
ajith
|
|
|
|
|
The datetime picker supports on 1 selected item not a collection of selected items. There are some calendar controls out there that may support this but the standard DTP does not.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
The MonthCalendar will let users select a range of dates. Not sure if that will help.
Creating your own dropdown control! Once you start dealing with the dropdown overhanging the form and whether there is enough room at the bottom of the desktop, loss of focus etc. You'll wish you hadn't. It's a coders nightmare.
|
|
|
|
|
Creating a whole control is a bit beyond what anyone can do in a forum response. If you look through Code Project, you should be able to find a few articles that can help.
|
|
|
|
|
|
My requirement is print a message in inside of rectangle in windows form application and I achieved this one using PrintDocument and PrintDialog control.I have written the code as shown below:
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Rectangle rect = new Rectangle(50, 40, 500, 150);
e.Graphics.DrawRectangle(Pens.Black, rect);
RectangleF recf = new RectangleF(55, 45, 400, 20);
e.Graphics.DrawString("Printing from Windows form",new Font("Arial",10,FontStyle.Bold ), Brushes.Black, recf);
}
My problem is If I print this message using the above code.I got the some junck line along with message but the rectange is not drawn in the print document.
The following are the output from the printer(which lines bold )
/languagelevel where {pop languagelevel} {1} ifelse dup 2 ge {currentglobal ex
0 0 10 6 [] 0 1 GpPBeg
0.0039 0.0039 0.0039 SC
NP Printing from Windows form
300 240 m 3300 240 1 330 1140 1 300 1140 1 CP
S
GSE
If I print the same message without rectangel I am able to print correct message without junk lines (above bold lines).
I am using this printer model HP LaserJet M3027 MFP PCL 6 for print
Could you please help me how to fix this issue?
I am a software Developer and have worked on Microsoft .Net technologies for about 3 Years.I always interested to read the technical articles and learn about new technologies.
|
|
|
|
|
ragupathi.p wrote: /languagelevel where {pop languagelevel} {1} ifelse dup 2 ge {currentglobal ex
0 0 10 6 [] 0 1 GpPBeg
0.0039 0.0039 0.0039 SC
NP Printing from Windows form
300 240 m 3300 240 1 330 1140 1 300 1140 1 CP
S
GSE
That stuff is raw PostScript code, the language used between your PC and your particular printer. Normally the printer interprets this textual information and only prints what is intended to be printed; the remainder being formatting, positioning, etc. (actually PostScript is a pretty complete programming language).
If you're saying the text shows as intended when only e.Graphics.DrawString() is present, and everything gets messed up when you do
e.Graphics.DrawRectangle(Pens.Black, rect);
e.Graphics.DrawString("Printing from Windows form",new Font("Arial",10,FontStyle.Bold ), Brushes.Black, recf);
then something is rotten, and it ain't your C# code. However I can't tell you what it is. Check your printer driver, does it match your printer? is it up-to-date? check your cable. Reset your printer and reboot your PC. If the mess is identical every time, it must be a bug. Experiment a bit with more lines of text, with different coordinates, fonts, whatever. Assuming nothing gives any improvement, start googling.
FWIW: if you need more proof your C# code is good, try printing to another printer. Maybe install a "PDF writer" which basically is a driver that emulates a printer and creates a PDF document, which you then can see on your screen. It will look all right!
|
|
|
|
|
Thanks for your help.
As you suggested,I am able to print this message with rectangle using PDF Printer writter.
I am a software Developer and have worked on Microsoft .Net technologies for about 3 Years.I always interested to read the technical articles and learn about new technologies.
|
|
|
|
|
Is it legal for a .NET 2.0 executable (.exe) to have a reference to a .NET 4.0 library (.dll)?
When I try this, the compiler complains that it can't resolve any of the types that come from the library.
As soon as I change the exe to .NET 4.0, the errors go away and it compiles cleanly.
Any thoughts? Thanks.
|
|
|
|
|