May 29, 2010

Working with ExtJS Pie Charts

In the previous post we saw how to create & customize charts using ExtJS. In this post, we will have a look at Pie charts. Pie charts are little different from other charts as they do not have axis and the data displayed is in percentage.

First Pie Chart

Let’s start with the data store. In this tutorial, I am getting the data from a remote URL. My server returns me a set of JSON object with product name and their sales value. Here is the data store:
var store = new Ext.data.JsonStore({
      fields:['product','sales'],
      root: 'rec',
      url: ‘/piechart/data/’
});
Unlike other charts, pie charts do not have axis. So, instead of using xField and yField properties of charts to pass data, we have dataField and categoryField in pie charts. Here is the code for pie chart:
new Ext.Panel({
title: 'Pie Chart',
      renderTo: 'chartDiv',
      width:400,
      height:300,                        
      items: {
            xtype: 'piechart',
            store: store,
      dataField: 'sales',
            categoryField: 'product'
      }
});
Very simple indeed! ExtJS does all the necessary calculations even if you don’t represent the data in percentage.

Adding Legend

Now, let’s add a legend to this chart. Without it, there is no much use in displaying a chart. An important property for styling is extraStyle. It helps you to add extra styles that will add or override default styles of the chart. Here is the final code for the pie chart and panel:
new Ext.Panel({
       title: 'The Pie Chart',
       renderTo: 'chartDiv',
       width:400,
       height:300,
items: {
       xtype: 'piechart',
       store: store,
       dataField: 'sales',
       categoryField: 'product',
       extraStyle: {
            legend:{
                display: 'right',
                padding: 10,
                border:{
                   color: '#CBCBCB',
                   size: 1
                }
            }
        }
      }
 });
While displaying the legend,notice that I have also made some beautification to it. I have provided a thin border using a specific color. There is no chart specific code for displaying legend, so the same code will work for other types of charts as well.

Custom Colors in your Pie chart

By default, ExtJS picks out the colors when rendering the chart. You might find these color shade dull. Lets try to brighten up our chart. I am going to apply a color scheme called Esprit_80s. In order to apply, we need to basically modify the style of series. So we will modify seriesStyles property of our pie chart:
new Ext.Panel({
       title: 'The Pie Chart',
       renderTo: 'chartDiv',
       width:600,
       height:300,
       items: {
           xtype: 'piechart',
           store: store,
           dataField: 'sales',
           categoryField: 'product',
           seriesStyles: {
             colors:['#F8869D','#25CDF2',
                     '#FFAA3C','#DEFE39',
                     '#AB63F6'] //eSprit 80s
            },
           extraStyle: {
                 legend:{
                    display: 'right',
                 padding: 10,
                 border:{
                   color: '#CBCBCB',
                   size: 1
                 }
           }
       }
    }
});

Note that the property colors is used only for pie charts. If you need to change the colors for other charts you will have to use the color property.

Textures & images in your Pie chart

ExtJS also provides us the ability to use images instead of color. So, if you have few texture images or any other images, you can easily substitute them for colors. This is possible through the images property of seriesStyles. I have five simple texture images and here is how I am adding them to our pie chart:
new Ext.Panel({
       title: 'The Pie Chart',
       renderTo: 'chartDiv',
       width:600,
       height:300,
       items: {
           xtype: 'piechart',
           store: store,
           dataField: 'sales',
           categoryField: 'product',
           seriesStyles: {
           images:['images/one.png',
                'images/three.png',
                'images/two.png',
                'images/four.png',
                'images/five.png']
            },
            extraStyle: {
                legend:{
                display: 'bottom',
                padding: 10,
                border:{
                   color: '#CBCBCB',
                   size: 1
                }
            }
       }
   }
});

Apart from these properties, extraStyle can be used to change the font styles as well. Have a look at the APIs and try out different customizations. I will be back with more customization tutorials on ExtJS charts. Let me know your feedback either through comments or using the contact form.

Learn how to Handle events in ExtJS charts or read other articles on ExtJS.

May 19, 2010

Getting Started with ExtJS Charts

The Charts feature in ExtJS is not a new thing, but recently few Techno Paper readers asked me questions regrading the same. This article is about getting started with ExtJS Charts how to do some basic customizations. For now, we will see what kind of charts ExtJS provide and how to get your first chart displayed.

Prerequisites

I assume you already have knowledge in building the UI (panels at least) and have worked on DataStores ( I will be using JSONStore). If you are not ready with these, may be you can have a look at my basic tutorials like "All about...".

What ExtJS offers
ExtJS offers you Line, Bar, Column, Pie and stacked charts. It also offers good amount of customization options as well. All the chart related classes are under the package Ext.chart and Chart is the base class. Apart from the chart classes, the library also provides classes that can be used to customize the axis, series and even the chart display. But note that, ExtJS makes use of Flash to render the charts and its not pure JavaScript component. Internally ExtJS is making use of YUI charts features and classes. Now, lets get started with coding!

Hello World of Charts

Building charts with ExtJS requires three things. The Datastore, the Chart object and a Panel to display the chart. In our first example i am going to keep things very simple. Lets build a DataStore first:
var store = new Ext.data.JsonStore({
fields:['month', 'sales'],
data: [
    {month:'Jan', sales: 2000},{month:'Feb', sales: 1800},
    {month:'Mar', sales: 1500},{month:'Apr', sales: 2150},
    {month:'May', sales: 2210},{month:'Jun', sales: 2250},
    {month:'Jul', sales: 2370},{month:'Aug', sales: 2500},
    {month:'Sep', sales: 3000},{month:'Oct', sales: 2580},
    {month:'Nov', sales: 2100},{month:'Dec', sales: 2650}
]});
I have a simple JsonStore here with the data hardcoded. In later examples, we will be fetching the data through ajax request. In the JsonStore, I have provided metadata and data. The fields attribute describe the fields in my records. The data attribute actually holds the data in the form of JSON. Instead of using JSON, we could also use XML.

Next, to create the chart object. For this example, I have used the line chart. Here is the code:
var chart = new Ext.chart.LineChart({
    store: store,
    xField: 'month',
    yField: 'sales'
});
Its very clean and simple! I have just provided the data store and what has to be plotted along x and y axis. And finally we need to put the chart into display. Here is our Panel:
var Panel = new Ext.Panel({
    title: 'Yearly Sales',
    renderTo: 'chartDiv',
    width: 400,
    height: 200,
    items:[chart]
});
If you are experienced coder I suggest you define the chart object in the panel rather than declaring it separately. Lets begin dig deeper!

Working with Axis

Chat's axis can be configured using xAsix and yAsix properties. There properties can accept objects of CategoryAsix, NumericAxis or TimeAxis. Lets add titles to our chart's axis:
xAxis: new Ext.chart.CategoryAxis({
                 title: 'Month'
                  }),
                  yAxis: new Ext.chart.NumericAxis({
                  title:'USD',
                  majorUnit: 500
                  })
Note that we have made use of CategoryAxis for y-axis as it hold months. Whereas, we have used NumericAxis for x-axis as it represents sales value in USD. I also changed the units in which the x-axis is represented. Check the API for other properties of these classes.

Working with Series

You don't always plot one parameter on a chart. At times, you have multiple data to be visualized onto the charts. Lets take our example of sales per month and add revenue to it. Now we need to plot both sales and revenue for each month. ExtJS allows you to do this by adding series object to the chart. The framework provides five implementations for different types of charts. Let's modify our chart to show revenue as well:
new Ext.Panel({
       title: 'A Simple Chart',
       renderTo: 'container',
       width:600,
       height:300,
       items: {
           xtype: 'linechart',
           store: store,
           xField: 'month',
xAxis: new Ext.chart.CategoryAxis({
                 title: 'Month'
}),
yAxis: new Ext.chart.NumericAxis({
title:'USD',
majorUnit: 500
}),
series: [{
yField: 'sales'
},{
yField: 'rev'
             }]
}
   });
I have kept the series objects very simple. We have just added the data alone. Upon execution, you will notice that it difficult to interpret the data as we do not have a legend on our chart. And that's exactly our next objective. To start with, lets modify the series as:
series: [{
yField: 'sales',
displayName: 'Sales'
},{
yField: 'rev',
displayName: 'Revenue'
 }]
I have just added the displyName property. To complete our modifications we need to do one final task, i.e display the legend!

Working with Extra Styles

extraSyle is an important property for styling your charts. It helps in modifying the colors, fonts, borders for various parts of your chart like axis, data tips, legends etc. First lets add a legend to our existing chart. Here is the code:
new Ext.Panel({
       title: 'A Simple Chart',
       renderTo: 'container',
       width:600,
       height:300,
       items: {
           xtype: 'linechart',
           store: store,
           xField: 'month',
xAxis: new Ext.chart.CategoryAxis({
                 title: 'Month'
}),
yAxis: new Ext.chart.NumericAxis({
title:'USD',
majorUnit: 500
}),
series: [{
yField: 'sales',
displayName: 'Sales'
},{
yField: 'rev',
displayName: 'Revenue'
             }],
extraStyle: {
legend: {
display: 'right'
}
}
}
   });
If you think of more customizations and styling, you need to have a good look at the extraStyle.
Well, that all for now. Feel free to provide me your feedback on this post. Next, we will have a look at pie charts.

May 17, 2010

Creating JSON using ASP Repeater

I had to implement an interesting task over the last few days. A part of the task, had to deal with what this article is all about. It sounded simple and easy but it turned ugly! The aim was to use ASP.Net's Repeater tag to create JSON when the page is loaded and later use it for some user manipulations and ajax operation. But in this article, we will see how to create JSON.

The ASP Repeater is a very handy tag. Everybody know it, but at times you will have to get messy with it. You get to solve many interesting problems with it. I my real case I had to deal with multiple repeater tags. Here we will have a look at one simple example. Its assume we want to make a JSON with product information. Lets just implement it:

<asp:Repeater ID="ProductJSON" runat="server">
 <HeaderTemplate>
  <script type="text/javascript">
  var products = [
 </HeaderTemplate>
 <ItemTemplate>{ pid: '<%#((Product)Container.DataItem).ProductID%>',
  name: '<%#((Product)Container.DataItem).ProductName%>', 
  image: '<%#((Product)Container.DataItem).Image %>',                        
  summary: '<%#((Product)Container.DataItem).Summary %>',
  price: '<%#((Ecomm.Code.ProductDM)Container.DataItem).Price%>'},
 </ItemTemplate>    
 <FooterTemplate>
  ];</script>
 </FooterTemplate>
</asp:Repeater>
That was it! really? well unfortunately No! Problems occur when your javascipt start using this JSON. You will notice that the last JSON object completes with a comma (which is a syntax error). The hard part for me started from here. How do I eliminate the final comma so that the JSON array is correctly represented. Finally after lot of googling and trails, I got the correct result. Here is the final code:
<asp:Repeater ID="ProductJSON" runat="server">
 <HeaderTemplate>
  <script type="text/javascript">
  var products = [
 </HeaderTemplate>
 <ItemTemplate>{ pid: '<%#((Product)Container.DataItem).ProductID%>',
  name: '<%#((Product)Container.DataItem).ProductName%>', 
  image: '<%#((Product)Container.DataItem).Image %>',                        
  summary: '<%#((Product)Container.DataItem).Summary %>',
  price: '<%#((Ecomm.Code.ProductDM)Container.DataItem).Price%>'}
  <%#Container.ItemIndex==(((List<Product>)ListViewDisplay.DataSource).Count - 1)?' ':','%>
 </ItemTemplate>    
 <FooterTemplate>
  ];</script>
 </FooterTemplate>
</asp:Repeater>
Many of you will now argue why not use some event like PreRender or some other events.. I would say for doing such a thing, when you need to have other complex solutions! I hope this will come helpful to others.

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.