Showing posts with label March 2013. Show all posts
Showing posts with label March 2013. Show all posts

Wednesday, March 27, 2013

Auto Refresh Highcharts graph in regular intervals using ASP.NET



In last post we discussed how to render multiple series using highcharts. In this article we will look at how to refresh the chart in regular intervals. This feature can be used to refresh data in graph or to show real time data in graph using ASP.NET

We will use ‘updatepanel’ and ‘scriptmanager’ to do “AJAX” post back- so that the whole page will not be refreshed every time graph changes.

1. If have already haven’t done this- Do the steps in my previous post.

2. Add “ScriptManager” and “UpdatePanel” controls. Place the container div inside the update panel. Also add a timer inside update panel. We need timer to refresh graph in regular intervals

So controls will look like –

<asp:ScriptManager runat="server" id="scriptManager1"></asp:ScriptManager>
    <asp:UpdatePanel runat="server" ID="updatePanel1">
        <ContentTemplate>
            <!--Hidden controls for storing x and y axis data-->
            <asp:HiddenField runat="server" ID="hdnXaxis" />
            <asp:HiddenField runat="server" ID="hdnYaxis" />
            <!-- Container to render highchats graphs -->
            <div style="width:800px;height:400px;" id="container" > </div >
            <!-- Timer to refresh graph in regular intervals -->
            <asp:Timer runat="server" ID="graphRefreshTimer" Interval="5000"
                ontick="graphRefreshTimer_Tick" ></asp:Timer>
        </ContentTemplate>
    </asp:UpdatePanel>



3. In code behind page add code for timer tick event to refresh the graph

   protected void graphRefreshTimer_Tick(object sender, EventArgs e)
        {
            LoadData();
            ScriptManager.RegisterStartupScript(graphRefreshTimer, graphRefreshTimer.GetType(), "scriptname", "DrawMyGraph1();", true);
        }


That’s it! Run the app and the graph will refresh every 5 seconds without full page postback. You can change the data in ‘LoadData()’ method to show the updated data. You can connect to SQL database in the LoadData() method to show updated stats.

Rendering multiple series in Highcharts using ASP.NET


In this article we will create a web application to render multiple series using highcharts. I used visual studion 2010 for creating this app.

1) Create a ASP.NET web application

2) Get below 2 javascripts. Highcharts js can be downloaded from http://highcharts.com and latest jQuery can be downloaded from http://jquery.com/download/

a) Highcharts.js
b)  jquery-1.4.1.js

3) Create default.aspx page

4) Add references to these scripts . NOTE – add jQuery file reference before highcharts
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="js/highcharts.js" type="text/javascript"></script>

5) Create a class for chart series (Y-axis)
public class ChartEx
{
public string name { get; set; }
public List<int> data { get; set; }
}

6) Create 2 hidden fields in html to store X and Y axis data

<asp:HiddenField runat="server" ID="hdnXaxis" />
<asp:HiddenField runat="server" ID="hdnYaxis" />

7) Create a div for rendering graph and set id as “container”

<div style="width:900px;height:300px;" id="container" > </div >


9) Populate data for X and Y axis in page_load event in code behind. You can connect to SQL Server Database to get data in the LoadData() method.


    protected void Page_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        public void LoadData()
        {
            //X axis data
            List<int> lstXaxis = new List<int>() { 9, 10, 11, 12 };
            List<ChartEx> lstseries = new List<ChartEx>();

            //Y axis - series 1
            ChartEx series1 = new ChartEx();
            series1.name = "Revenue";
            series1.data = new List<int>() { 100, 200, 150, 175 };

            //Y axis - series 2
            ChartEx series2 = new ChartEx();
            series2.name = "Profit";
            series2.data = new List<int>() { 50, 120, 80, 95 };

            //Add 2 series to list
            lstseries.Add(series1);
            lstseries.Add(series2);

            //Convert X axis data to JSON
            JavaScriptSerializer oSerializer1 = new JavaScriptSerializer();
            hdnXaxis.Value = oSerializer1.Serialize(lstXaxis);

            //Convert Y axis data to JSON
            JavaScriptSerializer oSerializer2 = new JavaScriptSerializer();
            hdnYaxis.Value = oSerializer1.Serialize(lstseries);
        }

8)  Now- the last step- copy the below javascript function to render chart

    <script type="text/javascript">
        $(document).ready(DrawMyGraph1);

        function DrawMyGraph1() {
            var xaxis = $.parseJSON($("#hdnXaxis").val());
            var series1 = $.parseJSON($("#hdnYaxis").val());
            chart = new Highcharts.Chart({
                chart: {
                    type: 'column',
                    renderTo: 'container',
                    defaultSeriesType: 'area'
                },
                title: {
                    text: 'Revenu Profit'
                },
                subtitle: {
                    text: 'revenu profit graph'
                },
                xAxis: {
                    categories: xaxis
                },
                yAxis: {
                    title: {
                        text: 'Revenue/Profit'
                    }
                },
                tooltip: {
                    formatter: function () {
                        return '$' +
Highcharts.numberFormat(this.y, 0) + ' ' + this.series.name + ' in ' + this.x + ' hour';
                    }
                },
                series: series1
            });
        }
</script>


Done ! Run the application and you can see multiple series rendered in your graph.

Let me know if this worked for you. 

Tuesday, March 19, 2013

ASP.NET UpdatePanel and Gridview


Using update panel parts of webpage can be updated without refreshing the entire page. In the below example we will check how to edit contents in a gridview without refreshing the entire page.

1)  Create an ASP.NET web application

2)  Add default.aspx page

3)  Add scriptmanager
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>


4)Add updatepanel
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    </asp:UpdatePanel>

5)Add datagrid inside the update panel
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
       <ContentTemplate>
            <asp:GridView runat="server" ID="grvEmp" AutoGenerateColumns="false"
                onrowcancelingedit="grvEmp_RowCancelingEdit" onrowediting="grvEmp_RowEditing"
                onrowupdating="grvEmp_RowUpdating">
                <Columns>
                    <asp:TemplateField>
                        <HeaderTemplate>
                            Employee Name
                        </HeaderTemplate>
                        <ItemTemplate>
                            <%# Eval("employee_name")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox runat="server" Text='<%# Eval("employee_name")%>' ID="txtName" ></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Action">
                        <ItemTemplate>
                            <asp:Button ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" /><br />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:Button ID="btnUpdate" Text="Update" runat="server" CommandName="Update" /><br />
                            <asp:Button ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
                        </EditItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
       </ContentTemplate>
    </asp:UpdatePanel>


6)Add a text box outside the update panel
<asp:TextBox runat="server" ID="txtTime"></asp:TextBox>
              
7)Create a function to return dataset to bind to datagrind
public DataSet GetEmpData()
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("employee_name");

            DataRow dr = dt.NewRow();
            dr[0] = "Employee 1";

            dt.Rows.Add(dr);

            ds.Tables.Add(dt);
            return ds;
        }


8) On page load set time and bind the gridview

  protected void Page_Load(object sender, EventArgs e)
        {
            txtTime.Text = DateTime.Now.ToString();
            if (!IsPostBack)
            {
                grvEmp.DataSource = GetEmpData();
                grvEmp.DataBind();
            }
        }

9)Handle the row edit,update and cancel events
  protected void grvEmp_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvEmp.EditIndex = e.NewEditIndex;
            grvEmp.DataSource = GetEmpData();
            grvEmp.DataBind();
        }

        protected void grvEmp_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

        }
   

        protected void grvEmp_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvEmp.EditIndex = -1;
            grvEmp.DataSource = GetEmpData();
            grvEmp.DataBind();
        }


And we are done. Run the application and click on edit button on the gridview. You can see that only the grid is refreshed, time on the text box on main page does not change.

Friday, November 9, 2012

Windows Message Queue (MSMQ) with Threading using C#.NET

In last post we learned how to create a simple message queue. In this article we are going to write a C# app to use the message queue in thread, so that one thread can be used to send messages and other to read it.


1) Create a console application in C#

2) Declare class level variable

   static bool StopThread = false;

2) Write function to get message queue instance


private static MessageQueue GetStringMessageQueue()
        {
            MessageQueue msgQueue = null;
            string queueName = @".\private$\MyStringQueue";
            if (!MessageQueue.Exists(queueName))
            {
                msgQueue = MessageQueue.Create(queueName);
            }
            else
            {
                msgQueue = new MessageQueue(queueName);
            }
            return msgQueue;
        }

3)  Create function to send message to queue


  private static void SendStringMessageToQueue()
        {
            while (StopThread == false)
            {
                string msg = Console.ReadLine();
                if (msg == "x")
                {
                    Console.WriteLine("Stopping write thread...");
                    StopThread = true;
                    break;
                }
                else
                {
                    MessageQueue msgQueue = GetStringMessageQueue();
                    msgQueue.Send("New Message send to message queue at " + DateTime.Now.ToString() + "- " + msg);
                }
            }
        }


4) Create function to read message


    private static void ReadStringMessageFromQueue()
        {
            MessageQueue msgQueue = GetStringMessageQueue();
            msgQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });

            Message msg;
            while (StopThread == false)
            {            
                if (StopThread == true)
                {
                    Console.WriteLine("Stopping read thread...");
                    break;
                }
                try
                {
                    msg = msgQueue.Receive(new TimeSpan(0, 0, 2));
                    Console.WriteLine(msg.Body.ToString());
                }
                catch (Exception ex)
                {
                }
            }
        }

5) Now create threads within static main method


  static void Main(string[] args)
        {
            Console.WriteLine("Press x to stop thread");

            Thread sendMsgThread =  new Thread(new ThreadStart(SendStringMessageToQueue));
            Thread readMsgThread = new  Thread(new ThreadStart(ReadStringMessageFromQueue));

            sendMsgThread.Start();
            readMsgThread.Start();
         
        }

Thursday, November 8, 2012

Windows Message Queue (MSMQ) Using C#.Net

This article is about creating windows message queue using C#.NET.


In this article we will create a private queue example. Lets develop an app and understand how the private queue works


 1) Create a console application using Visual Studio

 2) In Program.cs create a static method to create/get a private queue. Don't forget to include the "System.Messaging" namespace

private static MessageQueue GetStringMessageQueue()
 {
 MessageQueue msgQueue = null;
 string queueName = @".\private$\MyStringQueue";
 if (!MessageQueue.Exists(queueName))
 {
 msgQueue = MessageQueue.Create(queueName );
 }
 else
 {
 msgQueue = new MessageQueue(queueName );
 }
 return msgQueue;
 }

3) So now we have the queue, lets send a message as given below

private static void SendStringMessageToQueue()
 {
 MessageQueue msgQueue = GetStringMessageQueue();
 msgQueue.Send("New Message send to message queue at "+ DateTime.Now.ToString());
 }

4) Given below is the function to read the message from queue

private static void ReadStringMessageFromQueue()
 {
 MessageQueue msgQueue = GetStringMessageQueue();
 msgQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
 Message msg = msgQueue.Receive(); Console.WriteLine(msg.Body.ToString());
 }

5) That's it! Now lets call the functions from 'static main'

static void Main(string[] args)
 {
 SendStringMessageToQueue();
 ReadStringMessageFromQueue();
 Console.ReadLine();
 }


Wasn't that easy! Well this is the basic queue...to make it more useful you have to send the message from one thread and read from another thread or application.

 Happy coding guys!

Thursday, August 30, 2012

Setup and Deployment project for Windows service

In last post we learned to create a simple windows service and used 'installutil' to install the service from console window.

In this post we will learn how to create a setup and deployment project to make the installation process easy!

1) Create a setup and deployment project. Setup project is available in 'Other Project Types' -> Setup and Deployment ->Windows Studio installer


2) Right Click on the project and Select 'Add -> Project Output'
3) Add Primary Output of the project created in previous post

4) Right click View-> Custom Actions

5) Right click on 'Install' and select 'Custom Actions'
6) Select 'File System on Target Machine' from dropdown and Select 'Application Folder' click 'Ok'
7) Select 'Primary Output from ....'
8) Do the same for install ,commit,rollback and uninstall
10) We are done! Build the project and right click and select install. This will install the service in your machine

11) To start the service go to service window (run Services.msc) and select the service and right click on the service and click start!

Tuesday, August 7, 2012

Create Windows Service using C#.NET

1) Create a console Application in .NET and name it "WinServiceTest"

2) Create a class to write data to file as given below


    public class TestWriteFile
    {
        public static bool Shutdown = false;
        Thread fileWriteThread;
        public static void WriteCurentTime()
        {
            while (Shutdown == false)
            {
                string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(TestWriteFile)).CodeBase).Replace("file:\\","");
                using (FileStream ofs = File.Open(path + "\\test.txt", FileMode.Append))
                {
                    UTF8Encoding enc = new UTF8Encoding();
                    String tmpstr = DateTime.Now.ToString() + "\n";
                    ofs.Write(enc.GetBytes(tmpstr), 0, enc.GetByteCount(tmpstr));
                    ofs.Close();
                }
                Thread.Sleep(10000);//sleep for 10 seconds
            }
        }
        public void StartProcess()
        {
            fileWriteThread = new Thread(new ThreadStart(WriteCurentTime));
            fileWriteThread.Start();
        }
        public void StopProcess()
        {
            Shutdown = true;
            fileWriteThread.Join();
        }
    }


3) Add reference to System.ServiceProcess

4) Add service class WinServiceTestService.cs which inherits from ServiceBase.cs


public class WinServiceTestService: ServiceBase
    {
        TestWriteFile oprocessor;
        public static void Main(string[] args)
        {
            ServiceBase.Run(new WinServiceTestService());
        }
        public WinServiceTestService()
        {
            this.ServiceName = "My Win Service Test";
        }
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            oprocessor = new TestWriteFile();
            oprocessor.StartProcess();
        }
        protected override void OnStop()
        {
            base.OnStop();
            oprocessor.StopProcess();
        }
    }




Ok... now we have to create the installer to install the service.

5) Add reference to System.Configuration.Install

6) Write Code for installer as given below


using System.Configuration.Install;
using System.ComponentModel;
using System.ServiceProcess;

namespace WinServiceTest
{
    [RunInstaller(true)]
    public class WinServiceTestInstaller : Installer
    {
        public WinServiceTestInstaller()
        {
            var processInstaller = new ServiceProcessInstaller();
            var serviceInstaller = new ServiceInstaller();

            // Service Account Information
            processInstaller.Account = ServiceAccount.LocalSystem;
            processInstaller.Username = null;
            processInstaller.Password = null;

            serviceInstaller.DisplayName = "My Win Service Test Process";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.ServiceName = "My Win Service Test Process";

            this.Installers.Add(processInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }
}




7) Remove "static" from the "Main" function in Program.cs file

We are done! Windows service is ready. Now we have to install it. For installing we can use 'InstallUtil'.

Open Visual Studio command window and type "installutil /i WinServiceTest.ext" to install the service

To Start the service, open service manager right click on the task "My Win Service..." and click 'Start'

SQL statement to get domain name from URL

Given below is a SQL statement to extract domain name from URLs stored in a table
CREATE TABLE #tmpurl (url varchar(1000))

INSERT INTO #tmpurl (url)VALUES ('http://yahoo.com/')
INSERT INTO #tmpurl (url)VALUES('http://yahoo.com/test')
INSERT INTO #tmpurl (url)VALUES('http://www.yahoo.com/test')
INSERT INTO #tmpurl (url)VALUES('https://www.yahoo.com/test')
INSERT INTO #tmpurl (url)VALUES('https://www.yahoo.com/test?test=a')
INSERT INTO #tmpurl (url)VALUES('https://www.yahoo.com?test=a')

SELECT 
url,
substring(
substring(url,charindex('://',url)+3,len(url)),
0,
case when charindex('/',substring(url,charindex('://',url)+3,len(url)))>0  
then charindex('/',substring(url,charindex('://',url)+3,len(url)))
when charindex('?',substring(url,charindex('://',url)+3,len(url)))>0  
then charindex('?',substring(url,charindex('://',url)+3,len(url)))
else
len(url)
end
)
FROM #tmpurl

Wednesday, March 28, 2012

LINQ - Get distinct values from collection

Below Code snippet shows how to select distinct values from generic collection using LINQ


public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}

List students = new List();
students.Add(new Student { ID = 1, Name = "Adam", Age = 15 });
students.Add(new Student { ID = 2, Name = "Tom", Age = 15 });
students.Add(new Student { ID = 3, Name = "John", Age = 15 });
students.Add(new Student { ID = 4, Name = "Abraham", Age = 15 });
students.Add(new Student { ID = 5, Name = "Abraham", Age = 15 });


/*Find students having same name*/
var samename = students.GroupBy(x => x.Name).Where(g => g.Count() > 1).Select(y => new { Code = y.Key, Desc = y.First() }).ToDictionary(z => z.Code, z => z.Desc);


/*Select distinct name of students*/
var distinctnames = students.GroupBy(x => x.Name).Where(g => g.Count() >0).Select(y => new { Code = y.Key, Desc = y.First() }).ToDictionary(z => z.Code, z => z.Desc);



Friday, January 6, 2012

ASP.NET web method call using AJAX (jQuery)

This article is about how to call a server side function (web method) from client side (aspx page) using AJAX(provided by Jquery).

Its interesting and easy to implement. As always- lets go directly to an example and see how to implement it...



In this example we will create a webmethod which will return a message to client side

1) Create an ASP.NET Application.

2) Add a new page 'WebForm1.aspx' and make it the start up page.

3) In WebForm1.aspx include jQuery file as given below. If you do not have jQuery file, you can download the latest files from http://jquery.com/

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>

4) In code behind page (WebForm1.aspx.cs) create a webmethod to return some data as given below. Make sure to add the attribute [WebMethod()] to the function. You have to include the namespace System.Web.Services. (using System.Web.Services;)

[WebMethod()]
public static string GetData(int userid)
{
    /*You can do database operations here if required*/
    return "my userid is" + userid.ToString();
}


5) Add script tags and include the function to call the web method. Pass the parameter (in this case 'userid') to web method as JSON object

function asyncServerCall(userid) {
    jQuery.ajax({
 url: 'WebForm1.aspx/GetData',
 type: "POST",
 data: "{'userid':" + userid + "}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {
     alert(data.d);
 }

    });
}


6) Add button on aspx page and call the ajax function on click event.

<input type="button" value="click me" onclick="asyncServerCall(1);" />

7) DONE! Run the app and click the button, you can see that the webmethod is called and data is returned.

Wasn't that easy? Let me know if you face any issue in running this example. I used Visual Studio 2010 to run this app.

Monday, June 27, 2011

PIVOT/UNPIVOT expression in SQL Server.

Pivot expression in SQL converts values returned by a query into columns. For example in below example, the temp table contains revenue data for different months for companies. If the result has to be displayed with each month as columns , then it can done easily using PIVOT expression.



Create temp table to store data
CREATE table #tmp (comp_id int,comp_name varchar(20), [month] int,rev int)

GO

insert into #tmp values (200,'comp1',1,32144)
insert into #tmp values (200,'comp1',2,56234)
insert into #tmp values (200,'comp1',3,1000)
insert into #tmp values (211,'comp2',1,2364)
insert into #tmp values (211,'comp2',2,8762)
insert into #tmp values (211,'comp2',3,7644)
insert into #tmp values (211,'comp2',3,1111)
insert into #tmp values (211,'comp2',3,1111)
insert into #tmp values (213,'comp3',3,1111)


Now if we want to show the month as columns (like ‘1’,’2’,’3’ etc) we can use PIVOT expression as given below

SELECT * FROM #tmp t PIVOT 
 (SUM(rev) FOR [month] IN ([1],[2],[3])) pvt


UNPIVOT

We can also UNPIVOT the result as given below

/*get  ‘pivot’ data into another temp table #tmp2*/

SELECT * INTO #tmp1 FROM #tmp t PIVOT 
 (SUM(rev) FOR [month] IN ([1],[2],[3])) pvt

/*UNPIVOT the data*/
SELECT * FROM #tmp1 t  UNPIVOT 
 (rev FOR [month] IN ([1],[2],[3])) pvt


Friday, June 24, 2011

Generating Excel file using .NET

Given below is an example of how to create excel file using .NET (C#)

Excel has to be installed on the machine for the below example to work, since EXCEL COM object is used to generate excel file


1. Create a (C#) console application in Visual Studio

2. Add reference to “Microsoft.Office.Interop.Excel”

3. import the required namespaces

using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Text;
using System.Data;
using System.Runtime.InteropServices;

4. The function to create EXCEL is given below

public void WriteToExcel(System.Data.DataTable dtResult, string strFileName, string strDirectoryName)
{
   
    Application xlApp = default(Application);
    Workbook xlWorkBook = default(Workbook);
    Worksheet xlWorkSheet = default(Worksheet);

    string fName = strFileName = strDirectoryName + strFileName;

    try
    {
        object misValue = Missing.Value;
        xlApp = new ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

        int iRow = 1;
        int iColumn = 1;

        /*Add header to excel File*/
        StringBuilder oBuilder;
        oBuilder = new StringBuilder();
        foreach (DataColumn dc in dtResult.Columns)
        {
            if (dc.ColumnName != null)
            {
                xlWorkSheet.Cells[iRow, iColumn] = dc.ColumnName;
            }
            else
            {
                xlWorkSheet.Cells[iRow, iColumn] = "";
            }

            iColumn = iColumn + 1;
        }


        /*Add data to excel File*/
        foreach (DataRow dr in dtResult.Rows)
        {
            iColumn = 1;
            iRow = iRow + 1;
            oBuilder = new StringBuilder();
            foreach (DataColumn dc in dtResult.Columns)
            {
                if (dr[dc.ColumnName] == null || dr[dc.ColumnName] == DBNull.Value)
                {
                    xlWorkSheet.Cells[iRow, iColumn] = "";
                }
                else
                {
                    xlWorkSheet.Cells[iRow, iColumn] = dr[dc.ColumnName].ToString();
                }
                iColumn = iColumn + 1;
            }
        }

        
        xlWorkBook.SaveAs(fName, XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        Marshal.ReleaseComObject(xlWorkSheet);
        Marshal.ReleaseComObject(xlWorkBook);
        Marshal.ReleaseComObject(xlApp);

        if (xlApp != null)
        {
            Marshal.FinalReleaseComObject(xlApp);
        }

    }
    finally
    {
        if (xlApp != null)
            Marshal.ReleaseComObject(xlApp);
        if (xlWorkBook != null)
            Marshal.ReleaseComObject(xlWorkBook);
        if (xlWorkSheet != null)
            Marshal.ReleaseComObject(xlWorkSheet);

        if (xlApp != null)
        {
            Marshal.FinalReleaseComObject(xlApp);
        }
    }
}

5. Now call the function by passing in the datatable ,excel name and folder path

DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Age");

DataRow dr = dt.NewRow();
dr[0] ="Name1";
dr[1] = "12";
   
dt.Rows.Add(dr);

WriteToExcel(dt, "test.xls", @"Path");

Tuesday, June 21, 2011

Delegates And Events in .NET

Today I was working on a project which required the use of 'delegates'. I wanted to see the difference in calling a function using delegates and by events; so created a simple example to show the difference in invoking methods using events and delegates.

Delegates are function pointers in .net. The advantage of using delegates is that the calling program can define the function for a specific task. For example, let us consider the logging of message or exceptions in an application. We can just expose a delegate with signature “public delegate void LogMessage (string msg);” and the calling program can decide whether to do the logging in file or database or to display in console/UI.

An event is a message sent by an object to signal the occurrence of an action.Events are raised in response of an user action or it could be program triggered. It normally has the sender and event arguments as input parameters. But for the example below, I am comparing delegate and event calls and not using sender/event argument parameters



1) Create a console application in .NET (C#).

2) Create a delegate as given below in 'Program.cs'

public delegate void LogMessage(string msg);


3) Create a class (DelegateTestClass) for delegate test

public class DelegateTestClass
    {
        public LogMessage MessageLogger { get; set; }

        public void PerformTask1()
        {
            MessageLogger("Performing Task1");
        }

        public void PerformTask2()
        {
            MessageLogger("Performing Task2");
        }
    }

4) Create a class for Event test as given below

class EventTestClass
    {
        public event LogMessage MessageLogger;

        public void PerformTask1()
        {
            MessageLogger("Performing Task1");
        }

        public void PerformTask2()
        {
            MessageLogger("Performing Task2");
        }
    }

5) In “Program.cs” create a function to handle the delegate and event

private static void ShowMessage(string strMsg)
        {
            Console.WriteLine(strMsg);
        }

6) Now call the event and delegate from ‘Main’ as given below

static void Main(string[] args)
        {
            DelegateTestClass oDelegateTest = new DelegateTestClass();
            /*Specify the function to handle the message logging*/
            oDelegateTest.MessageLogger = new LogMessage(ShowMessage);

            oDelegateTest.PerformTask1();
            oDelegateTest.PerformTask2();


            EventTestClass oEventTest = new EventTestClass();
            /*Attach function to the event*/
            oEventTest.MessageLogger += new LogMessage(ShowMessage);

            oEventTest.PerformTask1();
            oEventTest.PerformTask2();

            Console.ReadLine();
        }

Friday, June 10, 2011

Convert image to binary and upload to database using ASP.NET

This article is about uploading images to server/database using ASP.NET. For uploading an image to database ,it has to be first converted to binary format. Then it has to be saved to a database table; the table should have a column with data type [image] for storing the binary image data.

Ok, enough of theory. Let us try out an example.

1) Create a ASP.NET web application using VS2008/2010

2) In default.aspx provide a input control of type “file” and a button

<input type="file" runat="server" id="photoupload" />
<asp:Button runat="server" ID="btnSave" Text="Save" onclick="btnSave_Click"/>

3) Create a function to convert stream to byte[]

public byte[] StreamToByteArray(Stream input)
{
    byte[] total_stream = new byte[0];
    byte[] stream_array = new byte[0];
    byte[] buffer = new byte[1024];

    int read = 0;
    while ((read = input.Read(buffer, 0, buffer.Length )) > 0)
    {
 stream_array = new byte[total_stream.Length + read];
 total_stream.CopyTo(stream_array, 0);
 Array.Copy(buffer, 0, stream_array, total_stream.Length, read);
 total_stream = stream_array;
    }

    return total_stream;
}


4) In the button click event, write code to get the stream from uploaded image and convert to byte array.(Import System.IO- using System.IO;)

Stream oStream = photoupload.PostedFile.InputStream;
byte[] arr = StreamToByteArray(oStream);
oStream.Close();
oStream.Dispose();


5) Now pass the byte[] data to database

SqlConnection oConnection= new SqlConnection("[connectionstring]”);
SqlParameter oParam1 = new SqlParameter("@data", arr);
oParam1.DbType = System.Data.DbType.Binary;
SqlParameter oParam2 = new SqlParameter("@description", photoupload.PostedFile.FileName);

SqlCommand oCommand = new SqlCommand(“[storedprocname]”);
oCommand.Parameters.Add(oParam1);
oCommand.Parameters.Add(oParam2);

oCommand.CommandType = CommandType.StoredProcedure;
oCommand.Connection = oConnection;
oConnection.Open();
int i = oCommand.ExecuteNonQuery();
oConnection.Close();

Done! Now the image is saved in database.

6) Code snippet for getting the binary data back from database is given below

/*Get binary data into dataset*/
DataSet ds = oDal.GetData("[stored procedure name]" + photoid.ToString());

byte[] arr = (byte[])ds.Tables[0].Rows[0]["data"];
MemoryStream oStream = new MemoryStream(arr);
Response.ContentType = "image/png";
Response.BinaryWrite(arr);

Wednesday, June 1, 2011

C#.NET and Greenplum

This article is about connecting to greenplum (GP) database using C#.NET. Greenplum DB is based on the open source database PostgreSQL.

Greenplum database is optimized for faster searches. For searching data in tables having millions of rows, Greenplum is really fast.

Given below is a C# example for opening a connection to GP database and executing a search query.

1) The first step is to download the dll which connects to GP. It is called Npgsql.dll. It can be downloaded from http://npgsql.projects.postgresql.org/docs/manual/UserManual.html

2) Create a C#.NET console application using Visual Studio.


3) Create a new file for GP connection. Lets name it GPDData.cs

4) Copy the dll to a local folder in the project and add a reference to the dll from project. Or you can register it in Global Assembly Cache using "gacutil".

5) Include the namespace

using Npgsql;

6) In the GPData class create method to execute query in greenplum as given below.

public DataSet FillDataSet(string strCommand,string strConnection)
{
NpgsqlConnection oConnection = new NpgsqlConnection(strConnection);
DataSet ds = new DataSet();

NpgsqlCommand oCommand = new NpgsqlCommand(strCommand, oConnection);
NpgsqlDataAdapter oAdp = new NpgsqlDataAdapter();
oCommand.CommandTimeout = 100;
oAdp.SelectCommand = oCommand;

oConnection.Open();
oAdp.Fill(ds);
CloseConnection();

return ds;
}

public void CloseConnection()
{
if (oConnection.State == System.Data.ConnectionState.Open)
{
oConnection.Close();
}
}

7) Now you can execute query by calling the method as given below.

GPData oData = new GPData();
DataSet ds = oData.FillDataSet([command],[connectionstring]);

Tuesday, May 31, 2011

Parallel Processing in .NET 4.0

I was reading about the new features of .net 4.0 today and found the new parallel processing feature really interesting. The new parallel processing class is called “Task” and it is available in the namespace “System.Threading.Tasks”

The example given below is a comparison of how functions are called in thread model and in the new parallel task way. Though I have included the time taken for to execute the task by each method (thread and task), this example is not specifically to compare performance. It is more about the difference in invoking functions.

I used VS2010 express edition for this test. Though it is easy to do the threading tests in console application, I did this in web application. I implemented ‘ICallbackEventHandler’ and did the example in the “RaiseCallbackEvent” function. For simplicity you can use a console application also.


1) Create a function which does looping as given below

 public string Task1(int iCount)
        {
            DateTime dtStart = DateTime.Now;
            StringBuilder oBuilder = new StringBuilder();
            for (int i = 0; i < iCount; i++)
            {
                oBuilder.Append(i.ToString());
            }
            DateTime dtEnd = DateTime.Now; 
            string strReturn = "Time Taken for Method2 " + dtStart.ToLongTimeString() + "- " + dtEnd.Subtract(dtStart).TotalMilliseconds.ToString(); 
            return strReturn;
        }
2) Since the “ThreadStart” object takes a pointer to void function, I created 4 other functions to test “Thread”
private void Task1Thread()
{
str1 = "\n" + Task1(500000);
}
private void Task2Thread()
{
str2 = "\n" + Task1(600000);
}

private void Task3Thread()
{
str3 = "\n" + Task1(700000);
}

private void Task4Thread()
{
str4 = "\n" + Task1(800000);
}
3) And then I wrote the code to call the functions as below.
DateTime dtStart = DateTime.Now;
switch (eventArgument)
{
case "1":// sequential 
data = Task1(500000);
data = data + "\n" + Task1(600000);
data = data + "\n" + Task1(700000);
data = data + "\n" + Task1(800000);
break;
case "2": //Task - the NEW parallel processing way in .NET 4.0

Task<string> mytask1 = Task<string>.Factory.StartNew(() => Task1(500000));
Task<string> mytask2 = Task<string>.Factory.StartNew(() => Task1(600000));
Task<string> mytask3 = Task<string>.Factory.StartNew(() => Task1(700000));
Task<string> mytask4 = Task<string>.Factory.StartNew(() => Task1(800000));

data = mytask1.Result;
data = data + "\n" + mytask2.Result;
data = data + "\n" + mytask3.Result;
data = data + "\n" + mytask4.Result;

break;
case "3":// Thread – common method of multi threading in .NET 1.1, 2.0

Thread oThread1 = new Thread(new ThreadStart(Task1Thread)); 
Thread oThread2 = new Thread(new ThreadStart(Task2Thread));
Thread oThread3 = new Thread(new ThreadStart(Task3Thread));
Thread oThread4 = new Thread(new ThreadStart(Task4Thread));

oThread1.Start();
oThread2.Start();
oThread3.Start();
oThread4.Start();

oThread1.Join();
oThread2.Join();
oThread3.Join();
oThread4.Join();

data = str1 + str2 + str3 + str4;

break;
}
DateTime dtEnd = DateTime.Now;
string finalTime = "Total Time Taken - " + dtStart.ToLongTimeString() + "- " + dtEnd.Subtract(dtStart).TotalMilliseconds.ToString();

data = data + "\n" + finalTime;


You can see that calling methods using “Task” object is much easier than thread. And also its more efficient than using thread.

Friday, May 20, 2011

ASP.NET and HighCharts

High charts (http://www.highcharts.com ) is a really nice tool to generate graphs/reports on web applications. This article is about how to use high charts in ASP.Net and also shows how to pass data from .net to high chart control (JS/JQuery function) using JSON.

The charts generated by HighCharts control are really nice and have lots of client side features like zoom, selecting/highlighting series etc.

Before starting the example, we need two JS files for this. Both can be obtained from high charts website (http://www.highcharts.com ). The javascript file required are ‘highcharts.js’ and ‘jquery-1.4.1.min.js’

Ok..now let us develop an ASP.NET web application which displays high-chart graph.


1 Create a new web application using Visual Studio

2 Include the two js files inside the head tag of default.aspx

<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="Scripts/highcharts.js"> </script>

3) Now we need X and Y coordinate data to generate the graph. Let us first create X-axis data. Since we are going to generate a revenue graph, let us include year as X-axis. Add the below code in code behind page, in page_load event

/*X axis coordinates*/
List<int> lstXaxis = new List<int>();
lstXaxis.Add(2007);
lstXaxis.Add(2008);
lstXaxis.Add(2009);
lstXaxis.Add(2010);


4) Create public properties for X and Y axis so that they can be accessed from aspx page.

public string Series1 { get; set; }
public string Xaxis { get; set; }

5) Using JavascriptSerializer, convert the x-axis data to Json

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
Xaxis= oSerializer.Serialize(lstXaxis);

6) Let us now generate Y-axis data (revenue data). Create a class to store the Y-axis data

public class ChartEx
{
public string name { get; set; }
public List<int> data{ get; set; }
}

7) Fill Y-axis object with data and serialize it using Javascript serializer

/*Series1 - Yaxis*/
ChartEx oEx = new ChartEx();
oEx.data = new List<int> ();

oEx.name = "Revenue";
oEx.data.Add(350);
oEx.data.Add(410);
oEx.data.Add(220);
oEx.data.Add(421);

JavaScriptSerializer oSerializer1 = new JavaScriptSerializer();
Series1= oSerializer1.Serialize(oEx); ;

8) Create a div container in aspx page. The graph will be rendered in this container.

<div id="container" > </div >

9) Now call the Javascript function to draw the graph and pass the serialized C# object to javascript function. (Place the below code inside script tags)

$(document).ready(DrawMyGraph1);

function DrawMyGraph1 () {

chart = new Highcharts.Chart({
chart: {
renderTo: 'Container',
defaultSeriesType: 'area'
},
title: {
text: 'Revenu'
},
subtitle: {
text: 'Source: Test '
},
xAxis: {
categories: <%=Xaxis %>
},
yAxis: {
title: {
text: 'Revenue Vs Profit'
}
},
tooltip: {
formatter: function () {
return this.series.name + ' produced ' +
Highcharts.numberFormat(this.y, 0) + 'revenue in ' + this.x;
}
},
series: [<%=Series1 %>]
});
}




Done ! Now run the application and you can see the hightchart graph rendered in UI.

There are a lot of useful client side functionalities provided by this graph component like - zooming , highlighting specific graphs etc. Try it out an you will be amazed by how powerful this tool is.