Monday, November 22, 2010

Google Charts API for ASP.NET

Google Visualization has provided a powerful set of JavaScripts which allows us to develop various graphs and charts. I think if we are developing something like dashboard or something like Google Analytic dashboard, then using Google Visualizations is amazing idea. In case of Asp.net we can simply develop a logic to use DataTables as input and Graph will be generated automatically. Again we can capture the click events for the graph and display alerts or run some JavaScript as per our logic (DemoCode).

In this article we will simply check out different graphs and its integration with asp.net. Check out following Screen shots.





Google Charts API can be implemented effectively in Asp.net, this is just a small part of actual assignment I did for the development of a dashboard.
Step 1: Understanding Table structure of Google API.Google Charts API accepts table as input and generate graphs accordingly. It takes Table in Following format. (for more information check out  Google References )


We should be careful while generating Table in HTML, i.e. while adding Rows and Columns in Google DataTable. Google Data Table creation looks as follows

var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Salary');
        data.addRows(4);
There are many things we can do with Google Table which I am not including in this article.

Check out following JavaScript code for creating Google Table and Adding data in it
var data = new google.visualization.DataTable();
   function setDataforGraph()
        {
         // Create and populate the data table.
       var raw_data =  [['INFOSYS', 3077.15, 3081.65, 3015.9, 3059.80, 3082.65, 3054.65, 2997.85, 3030.05, 2970.95, 3003.95]];
            var xAxis = ['05-Nov-10', '08-Nov-10', '09-Nov-10', '10-Nov-10', '11-Nov-10', '12-Nov-10', '15-Nov-10', '16-Nov-10', '18-Nov-10','19-Nov-10'];

            data.addColumn('string', 'Date');
            for (var i = 0; i < raw_data.length; ++i) {
                data.addColumn('number', raw_data[i][0]);
            }
            
            data.addRows(xAxis.length);
            for (var j = 0; j < xAxis.length; ++j) {
                data.setValue(j, 0, xAxis[j].toString());
            }
            for (var i = 0; i < raw_data.length; ++i) {
                for (var j = 1; j < raw_data[i].length; ++j) {
                    data.setValue(j - 1, i + 1, raw_data[i][j]);
                }
            }
          
        }

We also need to include JavaScript sources, there are some packages Google Provides, as we are going to use this for Charts we include coreCharts
Add script file "http://www.google.com/jsapi"


Once we done with DataTable creation we go for the logic to display Charts. We need to call Google Function

function drawVisualization(Type) {

            // Create and draw the visualization.
            var targetDiv = document.getElementById('visualization');
            var chart;
            if(Type == "ColumnChart") chart = new google.visualization.ColumnChart(targetDiv);
            else if(Type == "PieChart") chart = new google.visualization.PieChart(targetDiv);
            else if (Type == "AreaChart") chart = new google.visualization.AreaChart(targetDiv);
            else if (Type == "BarChart") chart = new google.visualization.BarChart(targetDiv);
            else if(Type == "LineChart") chart = new google.visualization.LineChart(targetDiv);
            chart.draw(data);
            new google.visualization.events.addListener(chart, 'select', selectionHandler);

            function selectionHandler(e) {
                selection = chart.getSelection();
                for (var i = 0; i < selection.length; i++) {
                    var item = selection[i]; 
                    alert(data.getValue(item.row, 1));
                }
            }
        }

Above function can be called on any event. Which will generate Chart of Particular Type. Refer Demo Code. We can add selectionHandler to capture events on click of chart. Above function will give us value of the Item i.e. Data. Check out following image.


HTML Structure of form is something like below, where we have Div tag for Google Visualization.

At this point we are done with the Google Charts API usage in HTML. Now to make Google Charts work in asp.net we simply need to develop a logic in code behind which will enable us to Create GoogleDataTable.

To generate data in code behind we use string elements which we can simple get in JavaScript on page render.

public string x_Axis = string.Empty;
    public string graphTable = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            graphTable = getGoogleVisualizationStr(DemoDataTable);
            x_Axis = "'05-Nov-10', '08-Nov-10', '09-Nov-10', '10-Nov-10', '11-Nov-10', '12-Nov-10', '15-Nov-10', '16-Nov-10', '18-Nov-10','19-Nov-10'";
        }
    }

We keep Demo Table in c# code, with same data values used in above table.
private DataTable DemoDataTable
    {
        get
        {
            DataTable DT = new DataTable();
            DT.TableName = "GENERAL";
            DT.Columns.Add(new DataColumn("Name", typeof(string)));
            DT.Columns.Add(new DataColumn("Data1", typeof(long)));
            DT.Columns.Add(new DataColumn("Data2", typeof(long)));
            DT.Columns.Add(new DataColumn("Data3", typeof(long)));
            DT.Columns.Add(new DataColumn("Data4", typeof(long)));
            DT.Columns.Add(new DataColumn("Data5", typeof(long)));
            DT.Columns.Add(new DataColumn("Data6", typeof(long)));
            DT.Columns.Add(new DataColumn("Data7", typeof(long)));
            DT.Columns.Add(new DataColumn("Data8", typeof(long)));
            DT.Columns.Add(new DataColumn("Data9", typeof(long)));
            DT.Columns.Add(new DataColumn("Data10", typeof(long)));
            DT.Rows.Add(new object[] { "INFOSYS", 3077.15, 3081.65, 3015.9, 3059.80, 3082.65, 3054.65, 2997.85, 3030.05, 2970.95, 3003.95 });
            return DT;
        }
    }

We write a simple code to generate rowData used in above lines of code.

private string getGoogleVisualizationStr(DataTable DT)
    {
        string googleVisualTable = string.Empty;
        googleVisualTable = "[";
        for (int i = 0; i < DT.Rows.Count; i++)
        {
            for (int j = 0; j < DT.Columns.Count; j++)
            {
                if (j == 0)
                {
                    googleVisualTable += "[ '" + DT.Rows[i][j] + "'";
                }
                else if (j == DT.Columns.Count - 1) googleVisualTable += "," + DT.Rows[i][j] + "]";
                else googleVisualTable += "," + DT.Rows[i][j];

            }
            if (i != DT.Rows.Count - 1) googleVisualTable += ",";
        }
        googleVisualTable += "]";
        return googleVisualTable;
    }
We replace our JavaScript code with
var raw_data = <%= graphTable %>
var xAxis = [<%=x_Axis %>];

Thats it we are done with development of Google Charts API for ASP.NET. Above code used data of only one company to keep things simple. To add more companies simply add it in data table. So that our graphs will look like




Download Democode for reference --> GoogleVisualizationDemo.zip Submit this story to DotNetKicks

Read more...

Wednesday, November 3, 2010

Generate captcha image in asp.net - simple way

When it comes to captcha images simple question pops in i.e. how to generate captcha images?
This article is about generating Captcha image in asp.net, this is very simple logic which can be implemented immediately for any website. You can directly Download Demo and use it.
We have used following simple steps to Generate Captcha Image in asp.net
  1. Create Captcha Image from random numbers and store that number in session variable, we have used Captcha.aspx page for the same.
  2. Use Captcha.aspx as source for the captcha image in Default.aspx page, i.e. for image tag give Captcha.aspx as SRC.
  3. On Submit click simply verify captcha entered by user and captcha in session. 
Our folder structure is very simple, check out following image


To understand the way we have checked captcha, have look on HTML of Default.aspx page (Check out DemoCode, for better understanding.)


Catptcha Text



Check out the way we have used Captcha.aspx page in image source.

On submit click we simply checks whether Captcha entered in "txtCaptcha" is valid or not, we have following code for submit button clicked.

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Session["Captcha"] != null)
        {
            if (txtCaptcha.Text == Session["Captcha"].ToString())
            {
                Response.Redirect("RedirectPage.aspx");
            }
            else
            {
                Response.Write("Please Enter Valid Captcha code");
                txtCaptcha.Text = "";
            }
        }
        else
        {
            Response.Write("Session Expired, please re-enter Captcha.");
        }
    }

Now what remains is the logic for Generate captcha image, we don't have any HTML tags on captcha.aspx, we simply write following code for Binary Image Generation and write it. We have used Random number; but we can have our different logic for the same.

protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/plain";
        Random random = new Random(DateTime.Now.Millisecond);

        int number = random.Next(100000);

        Session.Add("Captcha",number.ToString());

        System.Drawing.Bitmap bmpOut = new Bitmap(100, 50);

        Graphics graphics = Graphics.FromImage(bmpOut);

        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;

        graphics.FillRectangle(Brushes.Aquamarine, 0, 0, 100, 50);

        graphics.DrawString(number.ToString(), new Font("TimesNewRoman", 20), new SolidBrush(Color.Coral), 0, 0);

        MemoryStream memorystream = new MemoryStream();

        bmpOut.Save(memorystream, System.Drawing.Imaging.ImageFormat.Png);

        byte[] bmpBytes = memorystream.GetBuffer();

        bmpOut.Dispose();

        memorystream.Close();

        Response.BinaryWrite(bmpBytes);

        Response.End();

    }

Thats it we are done with our Generate captcha image in asp.net. Very simple code to use, download democode and use it directly in your web application.

Download Democode here---> CaptchaInAsp.net.zip Submit this story to DotNetKicks

Read more...