March 30, 2010

How To configure Apache log4net for ASP.Net

Apache log4net is a tool that helps programmer to log outputs to a variety of output targets. Its basically a port of log4j framework and can be used with all types of .Net applications. In this post, we will see how to configure and start using the logging framework in an ASP.Net web application.

You can download the framework from Apache site. Once downloaded, you need to add the reference of Log4net.dll to the project.

Configuring the logging framework to work with your web application can be done by 3 simple steps:

Step 1: Update web.config file
In the web.config file, you will need to add a new section under configSections tag. Notice that you will already have some section in sectionGroup tag. Do not place the new tag in them as this will lead to build errors. You need to add the following:


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

Step 2: Configure log4net
Next we need to provide some configurations to log4net. In our example, we are going to store all the logs in a file. You may refer the documentation for other Appenders available. Below is my log4net configuration:
<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="D:\\Data\\logs\\log.txt" />
      <appendToFile value="true" />      
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message %newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="FileAppender" />
    </root>
  </log4net>
There are different ways of presenting this configuration to our framework. You can store the configuration in a separate xml file or use web.config to store it. In this example, I am storing it in web.config. just after ending the configSections tag, I have my log4net configurations. Now, we are ready to start using the logging framework.

Step 3: Start using log4net
To start using log4net, our web application should read the configurations. To do so, need to inform log4net to configure the logging environment. This is done with the help of the statement given below:
log4net.Config.XmlConfigurator.Configure();
I would recommend you add this to Application_Start method in Global.asax so that the logging environment is ready at the start of the applications. Inorder to log any infomation you need to get an instance of the Logger. This is done with the help of GetLogger method as shown below:
private static readonly ILog log = LogManager.GetLogger(typeof(MyclassName));
And finally, you just need to call log.Info, Debug etc methods to log you messages.

March 20, 2010

XML Transformation using C#

XML is now heavily used by developers for describing, transporting and storing data. XSLT is used to transform these XML files into different formats like HTML, XML, PDF and others. In my current project, my requirements are to generate XML and HTML. Here, I will explain how to transform XML file using C#.


Microsoft’s .Net framework provides us with a rich library. It supports XML document manipulation out of the box. All you need to do is use the necessary namespaces:


  • System.Xml
  • System.Xml.XPath
  • System.Xml.Xsl
I have created a simple class for my transformation activates. Below is the complete code:
public class Transformer
{
    private string xmlPath;
    public string xmlFilePath
    {
        get
        {
            return xmlPath;
        }
        set
        {
            xmlPath = value;
        }
    }

    private string xslPath;
    public string xslFilePath
    {
        get
        {
            return xslPath;
        }
        set
        {
            xslPath = value;
        }
    }

    private string htmlPath;
    public string htmlFilePath
    {
        get
        {
            return htmlPath;
        }
        set
        {
            htmlPath = value;
        }
    }


    public void xsltTransform()
    {
       XPathDocument xmlDoc = new XPathDocument(xmlPath);
       XslCompiledTransform xsltDoc = new XslCompiledTransform();

       xsltDoc.Load(xslPath);    

       XmlTextWriter writer = new XmlTextWriter(htmlPath, System.Text.Encoding.UTF8);       
       xsltDoc.Transform(xmlDoc, writer);
       writer.Close();
    }   
}
Lets staight way go to the xsltTransform method. Notice that, I need to set some of my class propeties; xmlPath, xslPath and htmlPath before I call the xsltTransform method.

First, I create a XPathDocument. This class provide a fast read only representation of the XML document. Next I need to load the stylesheet file. I create an instace of XslCompliedTrasform class to perform the transformation. The stylesheet is loaded using the Load method.

Now we are ready for the transformation. You can transform by call the Transform method. The method has over 15 overloads, so you will have to select the most appropriate for you. In my case, I am saving the output as a file to a specific location. I am using XmlTextWriter to do the task and provides the save to location and encoding type as construction parameters.

Here is the sample code:
Transformer tx = new Transformer();
tx.xmlFilePath = "D:\\Pragma\\data\\product.xml";
tx.xslFilePath = "D:\\Pragma\\xsl\\product.xsl";
tx.htmlFilePath = "D:\\Pragma\\output\\product.html";
tx.xsltTransform();
I suggest you try other overloaded methods available for Transform method. That’s all for now, you can expect few more .Net articles in the coming week.

March 02, 2010

Configuring View Resolver for Spring web flow

From the previous post, we learned how to setup spring web flow application. With the minimal set up there are few downsides. One of it is the usage default view revolver. In this post, we are going to see how to configure view resolver.

The major concern with the minimal setup is that, both flow definition XML file and the views should be in the same directory. Also, the default view resolver expect a JSP or JSPX page. If you look at the flow definition in the previous post, you will see that, we have provided the complete filename for the view attributes. What if I want to organize my views in different folders like MVC applications?

To configure view resolver, you need to "what is" and "how to configure" flow builder service. FlowBuilderServices class simply hold the services used by flow builder. When configuring these services, we need to provide concrete service implementations. We will configure a view resolver using the InternalResourceViewResolver. I am also using the JSTL view class and here is my bean definition:


<bean id="viewResolver" 
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" 
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
Well, that's pretty normal for a Spring MVC application. Notice that I have defined a prefix and all my JSP files will reside under WEB-INF/jsp/ folder. Next is the define the flow builder service. This is defined using flow-builder-services tag as shown below:
<flow:flow-builder-services id="flowBuilderService" view-factory-creator="viewFactoryCreator"/>
Since we are configuring the view resolver for our application, we need to provide reference of view-factory-creator. View factory creator is an instance of MvcViewFactoryCreator class. The class detects whether it is running in a Servlet or Portlet MVC environment, and returns instances of the default view factory implementation for that environment. Here is how the bean is configured:
<bean id="viewFactoryCreator" 
class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">  
<property name="viewResolvers">  
<list>  
<ref bean="viewResolver"/>  
</list>  
</property>  
</bean>
We will use our previously configured viewResolver to set the viewResolvers propertyof the MvcViewFactoryCreator class.

To sum up the configurations:
<flow:flow-registry id="flowRegistry" 
flow-builder-services="flowBuilderService">
<flow:flow-location id="loginform" 
path="/WEB-INF/flows/simple-flow.xml" />
</flow:flow-registry>
<flow:flow-builder-services 
id="flowBuilderService" 
view-factory-creator="viewFactoryCreator"/>
<bean id="viewFactoryCreator" 
class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">  
<property name="viewResolvers">  
<list>  
<ref bean="viewResolver"/>  
</list>  
</property>  
</bean>  
<bean id="viewResolver" 
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" 
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

Hope this post help people who are trying out Spring web flow.