Solved

error handling

Posted on 2010-09-14
22
430 Views
Last Modified: 2012-05-10
Hi experts, I have finished developing a form of 30 questions.
I would like your help with the implementation of error handling, as it is a single form should be something simple that I can handle errors properly and avoid showing any error framework

I understand I should use try catch, but I need to implement its recommendations
0
Comment
Question by:enrique_aeo
22 Comments
 
LVL 11

Expert Comment

by:lenordiste
ID: 33677812
your best bet is to use global.asax to manage any error that might occur on your site (in this case a single page). You can also simply provide a custom page in case of errors by modifying your web.config.

here is a starting point:
http://www.15seconds.com/issue/030102.htm

I personally would not use try/catch scenario on a small form unless you have specific error messages or mechanics you want to implement for that particular page.
0
 
LVL 5

Expert Comment

by:LlamaJoe
ID: 33678395
also, be sure to look at the asp.net validation controls - this will handle most of your "data entry" error catching - then use the global asax approach for logic and programming errors.

http://www.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp
0
 
LVL 8

Expert Comment

by:cubaman_24
ID: 33680774
A form? Windows form you mean? Try this in Program.cs


Log is a logger of my own.

Best regards
In Main()

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ThreadException += Application_ThreadException;

private static void Application_ApplicationExit(object sender, EventArgs e){
            Application.ThreadException -= Application_ThreadException;
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e){
            Log.Fatal(e.Exception.GetBaseException());
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e){
            Log.Fatal(e.ExceptionObject.ToString());
        }

Open in new window

0
 

Author Comment

by:enrique_aeo
ID: 33681784
is a web application and c # ap.net.
I am attaching the file to have a better idea of what I need. Regards
mostrarActividadDiscentes.txt
0
 
LVL 8

Expert Comment

by:cubaman_24
ID: 33681981
Hello Enrique:
You should use error handling whenever there is a chance that an error leave your app in a corrupt state. For example, in a teller machine transaction, if there is an error in a cash withdrawal, rollback transaction in order to return to previous account state. If you just want to be notified of errors in order to helping debugging, just put in Global.asax this code.
Suerte! ;)
void Application_Error(object sender, EventArgs e) {
        if (HttpContext.Current != null){
            if(HttpContext.Current.Error != null){
                LogError(HttpContext.Current.Error);
            }
            HttpContext.Current.Response.Redirect("~/ErrorPage.aspx");
        }
    }

static void LogError(Exception ex) {
        if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated){
            log.Error("Exception. User:" + HttpContext.Current.User.Identity.Name);
        }
        log.Error(ex.GetBaseException().ToString());
    }

Open in new window

0
 
LVL 8

Expert Comment

by:cubaman_24
ID: 33682012
By the way, if you place all your buttons that you need to disable in the same aspnet panel, then you just have to disable this panel in order to get all content disabled ;)

private void DesabilitarBotones()
        {
            btnProcesarInformacion.Enabled = false;
            btnVisualizar.Disabled = true;
            btnImprimirArchivo.Visible = false;
            btnGenerarFolio.Disabled = true;
            btnGenerarInforme.Disabled = true;
            btnGenerarInformeConstanciaDetalladoMag.Disabled = true;
            btnGenerarInformeConstanciaDetalladoAux.Disabled = true;
        }
0
 

Author Comment

by:enrique_aeo
ID: 33682992
i nhave this error
Error 2 The name 'log' does not exist in the current context
errorLOG.png
0
 
LVL 8

Expert Comment

by:cubaman_24
ID: 33689973
Hello:
Yes, log is an instance of Log4Net I have declared somewhere else.
http://logging.apache.org/log4net/
But you can use anything you decide as you log provider. I just wanted to show you the rigth method for handling errors.
If you want to use log4net too, download it, add a reference to log4net.dll in you web app and configure it.


<configSections>
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
		<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date - %message%newline"/>
			</layout>
		</appender>
		<appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
			<file value="Logs/general.txt"/>
			<appendToFile value="true"/>
			<maximumFileSize value="300KB"/>
			<rollingStyle value="Size"/>
			<maxSizeRollBackups value="5"/>
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%d{dd-MM-yyyy HH:mm:ss.fff} [%t] %-5p %c - %m%n"/>
			</layout>
		</appender>
		<!-- levels: DEBUG, INFO, WARN, ERROR, FATAL -->
		<root>
			<level value="DEBUG"/>
			<appender-ref ref="GeneralLog"/>
		</root>
		<logger name="WebLog" additivity="false">
			<level value="ERROR"/>
			<appender-ref ref="GeneralLog"/>
		</logger>
</log4net>


And in Global.Asax:

private static readonly ILog log = LogManager.GetLogger("WebLog");

Open in new window

0
 

Author Comment

by:enrique_aeo
ID: 33694379
please
this portion of code is not clear to me

<configSections>
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 8

Expert Comment

by:cubaman_24
ID: 33698976
Hello Enrique:
That piece of xml goes in your web.config file. It informs aspnet infrastructure how to handle the log4net section that comes after.
More info about configSections here:
http://msdn.microsoft.com/en-us/library/ms228256%28v=VS.90%29.aspx
best regards.
0
 

Author Comment

by:enrique_aeo
ID: 33702558
hi, this is my change
<configSections>
    <sectionGroup name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
....
i have this error:
Unrecognized configuration section log4net/appender.

i attached my web.config

I am working with Visual Studio 2008
webCONFIG.txt
0
 
LVL 8

Expert Comment

by:cubaman_24
ID: 33714304
Hello Enrique:
Have you added a reference to log4net.dll in your web project?
Best regards.
0
 
LVL 14

Expert Comment

by:existenz2
ID: 33714306
<sectionGroup name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>

should be:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
0
 

Author Comment

by:enrique_aeo
ID: 33716741
Hi experts, The application is working
what I did to test the error handling is
1. stop the service of the database and got the following error
Error underlying provider Open.
I was hoping that I redirect to error page,
in any case as it should work?
0
 

Author Comment

by:enrique_aeo
ID: 33716796
forget the previous question, and is working correctly, ie is redirected to error page
My question is, where I see the error?
0
 
LVL 8

Expert Comment

by:cubaman_24
ID: 33717661
Enrique:
Youll fin the log in the path specified in web.config. If you copied it as is, it should be in the root of your web app, in the Logs folder.
Remember to give write acces to the aspnet user in that folder.
Best regards.
0
 

Author Comment

by:enrique_aeo
ID: 33717791
the folder exists, but I see no error
I see the error in event viewer
eventVIEWER.jpg
fodelSLN.jpg
0
 
LVL 8

Accepted Solution

by:
cubaman_24 earned 500 total points
ID: 33723012
Enrique, you must give write permissions on that folder to the user under which aspnet process is running.  In your development machine it should be aspnet user. Right click on Logs folder, go to Properties, Security Tab. Add aspnet user with write permissions there.
Also, modify you webconfig to receive logs from all levels. Look for:
<level value="DEBUG"/>
Modify it to:
<level value="ALL"/>
If you play around with log leves and loggers, you can get a very flexible and powerful logging system. Remember, RTFM ;-)
Best regards.
0
 

Author Closing Comment

by:enrique_aeo
ID: 33725600
it is fine
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now