2012-10-26

Configure log4net with asp.net (Logging with asp.net)

Logging is a very important thing for a web site specially if the website is on live! It will help you to debug your live web application without needing to enable remote debug on the server, so it comes very handy when you need to log the errors which can occur at the live site, when users are using it.
So here I’m going to explain how to configure log4net with a website built on asp.net.

1. Download the log4net dll file from here.
2. Add the log4net.dll file to your project
3. Add reference to the log4net.dll file in your project.
4. Add the below section at the top of your web.config file (right after you open the <configuration> section).
<configSections>     
      <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> 
</configSections>
5. Add the below section to your web.config file within the <configuration> section.
<log4net>
   <root>
     <level value="Debug"/>
     <appender-ref ref="LogFileAppender"/>
   </root>
   <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
     <param name="File" value="C:\CentralCMS_Logs\Logs.txt"/>
     <param name="AppendToFile" value="true"/>
     <rollingStyle value="Size"/>
     <maxSizeRollBackups value="10"/>
     <maximumFileSize value="3MB"/>
     <staticLogFileName value="true"/>
     <layout type="log4net.Layout.PatternLayout">
       <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline"/>
     </layout>
   </appender>
   <logger name="CentralCMS">
     <level value="DEBUG"/>
   </logger>
 </log4net>
  • I’ve defined the level as ‘Debug’ since I just need to debug my application. If you need to stop the application or need something like that when an error occurs, you should go for a level like ‘Fatal’.
  • I’ve used appender type as log4net.Appender.RollingFileAppender. So it will roll the log files based on rollingStyle. In this example, ‘Size’.
  • Here, you can set the path where you need log files to be saved by specifying the parameter name ‘File’. In this example, I’m storing them on the directory CentralCMS_Logs in C drive. If there is no directory like that, your program will automatically create a folder.
  • Set ‘AppendToFile’ parameter to ‘true’ if you need the new logs to be appended to the existing log file. If you need to override the old logs with new log, set it to ‘false’.
  • Here I’ve set rollingStyle to the ‘Size’, which means it will roll the file once the maximum File Size reaches. The default value for the rollingStyle is ‘Composite’, which means it will roll the file both depending on the file size and the date. If it reached the maximum file size before the day ends, it will go for a new file. If not, it will open a new file on next day.
  • Here I’ve defined maxSizeRollBackups as 10, which means it will create 10 backup files before the oldest one is erased. Once it reach for 10 files, it will delete the oldest log file and create a new file.
  • As the name suggests, maximumFileSize is the maximum file size for a log file. It will go for a new file when the maximum file size reaches. If the rollingStyle is set to ‘Date’, then it will not log further logs if the maximum file size reaches before the end of the day.
  • I’ve set staticLogFileName to ‘true’ since I want to log on the same file. If you need separate file for each log, set it to false.
  • I’ve set layout type to PatternLayout because I need my own pattern for the log texts. Through the ConversionPattern parameter, I’ve specified my own format for the log texts. I.e.
    • %date - Date and time followed by,
    • [%thread] - thread number which generated the log event followed by,
    • %-5level - level of the logging event (Right pad with spaces if the level of the logging event is less than 5 characters long) followed by,
    • %logger – the logger of the logging event (Global file, Default file etc. with the namespace) followed by,
    • %message – log message followed by,
    • %newline – a new line.
6. In your Global.asax file, import the log4net class like this
using log4net;
7. Configure log4net at the Application_Start() method like this
void Application_Start(object sender, EventArgs e) {
      // Code that runs on application startup
      log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
 }
8. To use the logging, initiate a global variable like below in your class where you need to log the information. Note that I’ve passed the logger name I’ve given in the web.config file to the GetLogger() method. It will return a ILog object which you can use to do the logging.
private static readonly ILog log = LogManager.GetLogger("CentralCMS");
In my example, I’m showing how to log all the unhandled exceptions you are getting for your web application. So I’m going to declare this variable in the Global.asax file.
9. Now you can successfully use the log4net for logging. By doing the logging on the Application_Error() method, we can get all the unhandled exceptions like below
void Application_Error(object sender, EventArgs e) {
      Exception ex = Server.GetLastError();
      log.Debug("++++++++++++++++++++++++++++");
      log.Error("Exception - \n" + ex);
      log.Debug("++++++++++++++++++++++++++++");
 }

2012-10-19

How to un bind an event from a HTML element

Sometimes we need to stop an event being fired. We can remove/unbind that particular event with the use of removeEventListener method in JavaScript.

For an example, let’s say we need to unbind the function named ‘test’ from the event ‘onkeypress’ event. Then we can use the removeEventListener method as follows,

HTML code

<input type=”text” onkeypress=”test();” id=”textboxID” />

JavaScript code

function test()
{
  // Some code here
}

function removeEvent()
{
  var elementObject = document.getElementById(“textboxID”);
  elementObject.removeEventListener("onkeypress", test);
}

Here the elementObject is the object which has the event.

How to make word-wrap work for asp:Label

word-wrap CSS3 property won't work for inline elements. asp:Label is getting rendered as span in the browser. Spans are inline elements. So we have to specifically set the span to an inline-block behavior to get the word-wrap property to work with asp:Labels.

.test{
width:20px;
word-wrap:break-word;
display:inline-block
}

The above CSS class demonstrate of an example of how to properly set word-wrap for an asp:Label.

Unrecognized tag prefix or device filter 'asp' error

Sometimes we are getting the Unrecognized tag prefix or device filter 'asp'. warning message and intellisense will also not work for asp.net controls. There could be two reasons for this kind of behavior.

  1. Because of a wrong Page directive. If that’s the case, you can check the Page directive at the top of the page and correct it.
  2. Failure of generating correct Reflected Schemas. If that’s the case, first thing you can try is restart the PC and open the Visual Studio so it will regenerate the schemas. Or delete the schemas manually by going to the below path.

C:\Documents and Settings\[Username]\Application Data\Microsoft\VisualStudio\10.0\ReflectedSchemas

How to make HTML5 work in old browsers

First of all, I need to tell that only the latest versions of browsers support HTML5. If the browser doesn't support HTML5 then you don't really have any choice. It's an internal thing of the browser. You cannot force it to load HTML5.

Being said that, there are some ‘tricks’ we can do to replace HTML5 features with alternatives. Modernizr is such a library which can detect the HTML5 and CSS3 capability of the browser. It does not make browser works for HTML5 or CSS3. You have to detect the features browser supports and write alternatives for the features it does not support. Modernizr is just a library  which tells you whether a particular feature is available in the browser or not.

With the use of html5shiv we can add basic support for HTML5 in IE. html5shiv is only working in IE and it only allow styling of HTML5. It will not recognize tags such as <audio>, <video>.