Thursday, March 28, 2013

How to get a website live using ASP.NET and SQL


OK, I know this is a big topic to discuss in one blog post but I want to start a post which I will update constantly as I learn and implement new ideas/concepts in developing/hosting a website. The reason why I wanted to start this post is because I created couple of websites in last few months and there were lot of interesting things that I learned. These are not really complex stuff, but more simple things like setting sitemap, robots etc.

I created a website using ASP.NET and SQL as backend. I am not going into the details of development; let me list what I had to do to deploy/host this site.

This is more like a checklist- some are minor stuff but things that really helped me to run a successful site.

1.  Website name – the first thing to do is to come up with a website name. You can check if the name is available in sites like register.com or godaddy.com

2.  Register name and set up hosting servers – Again these can be done using services provided by godaddy.com or register.com

3.  Create DB – I used SQL DB for backend. Run scripts to create tables, stored procedures and functions.

4.  Upload web application files – Upload the files of your application to the FTP server.
Make sure that pages have –
a Meaningful titles
b Meta tags with description/keywords
These are mainly for optimizing your site for search engine (SEO)

Don't forget to set a 'default' landing page for your site.

5.  Setup Email server – You need an email sever to send mails and to get mails from ‘contact us’ section of your website

6.  Track exceptions/errors – Track exceptions occurring from your site by logging in database and/or sending emails to you. Also make sure that you have a custom error page to handle all exceptions.

7.  Create a sitemap.xml – Sitemap lists the pages of your site. This will be used by crawlers

8.  Create a robots.txt – Robot file specifies which urls the crawler should exclude from crawling.

9.  User behavior/traffic -  If you want to know about the user traffic and behavior you should implement Google analytics in your site

10.  Favorite icon – Don’t forget to set an icon for your website

11.  Advertise!

I will be updating this post with more details later.

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!