Tuesday, 28 May 2013

Pie chart using ASP.NET with AJAX Library

Step 1:

 Download latest  AjaxToolKit from  here . (Please download with compatible version of .net 3.5/4/4.5)

Step 2: 
 
  Add library to reference for solution.

Step 3:
 
  Default.aspx page code:

  <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
  
       <cc1:ToolkitScriptManager ID="scriptmanager1" runat ="server"></cc1:ToolkitScriptManager>
        <asp:DropDownList ID="ddlCountries" runat="server" OnSelectedIndexChanged="ddlCountries_SelectedIndexChanged"
            AutoPostBack="true">
        </asp:DropDownList>
        <hr />
        <cc1:piechart id="PieChart1" runat="server" chartheight="300"
        chartwidth="300" charttype="Column"
            charttitlecolor="#0E426C" visible="false">
        </cc1:piechart>
   
    </form>
</body>
</html>



Step 4:

  Default.aspx.cs page code:

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string query = "select distinct shipcountry from [Test].[dbo].[Ship_orders]";
                DataTable dt = GetData(query);
                ddlCountries.DataSource = dt;
                ddlCountries.DataTextField = "shipcountry";
                ddlCountries.DataValueField = "shipcountry";
                ddlCountries.DataBind();
                ddlCountries.Items.Insert(0, new ListItem("Select", ""));
            }
 
        }

        protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
        {
            string query = string.Format("SELECT  [shipCity],count([orderId]) TotalOrders FROM [Test].[dbo].[Ship_orders] where [shipCountry] ='{0}' group by shipcity", ddlCountries.SelectedItem.Value);
            DataTable dt = GetData(query);           
            PieChart PieChart1 = (PieChart)Page.FindControl("PieChart1");
            foreach (DataRow row in dt.Rows)
            {
               
                PieChart1.PieChartValues.Add(new AjaxControlToolkit.PieChartValue
                {
                    Category = row["ShipCity"].ToString(),
                    Data = Convert.ToDecimal(row["TotalOrders"])                  
                });
            }
            PieChart1.Visible = ddlCountries.SelectedItem.Value != "";          
        }

        private static DataTable GetData(string query)
        {
            DataTable dt = new DataTable();
            string constr = ConfigurationManager.ConnectionStrings["SQLServerConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        sda.Fill(dt);
                    }
                }
                return dt;
            }
        }



Step 5: Make sql server connection with Table design as
         
           id                  int
           shipCity         nvarchar(50)
           orderId          int
           shipCountry    nvarchar(50)


Step 6: Note: [If you will get java runtime exception.then its browser issue]
           Above code only support IE 9 + , Firfox,Chrome .Does't support IE 8 Version
           So copy localhost url from IE 8 to any mention browsers

Step 7: Enjoy output




Thursday, 16 May 2013

Session Management Techniques in ASP.Net

Session are the server side method of managing the state of an application i.e. all the web applications' state related info will be stored on server side if we use this technique.

The advantages of using Session State are
  • Better security
  • Reduced bandwidth
The disadvantages of using Session state are
  • More resource consumption of server.
  • Extra code/care if a Web form is used

Using Session State

ASP.NET allows us to save values using Session state. It is a global storage mechanism that is accessible from all pages in the Web application. Session state is stored in the Session key/value dictionary. This information will be user specific i.e. for each user separate dictionary will be created and no one can access other session information. below is the Example usage of sessions.

global.asaxvoid Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started    Session["number"] = 0;
}

// Web formsSession["number"] ="123";

To configure the session management we need to specify the settings in the web.config file

<sessionState mode="InProc" 
 stateConnectionString="tcpip=127.0.0.1:42424" 
 sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;" 
 cookieless="false" 
 timeout="100"/>
mode This specifies the type of session management we want to use. it could be InProc, SQLServer, and StateServer
stateConnectionString If we use StateServer as session management technique then this specifies the location of the server that is handling the session data.
sqlConnectionString If we use SQLServer as session management technique then this specifies the database connectionstring that will store the session data.
cookieless This specifies whether we will be using cookies to identify sessions or we want session info appended in URL. It could be true or false.
timeout This specifies the time for which the session should be active. after this much time of inactivity the session will expire. 

Configuring the Session Modes

Using In-Proc Session Mode

In-Proc Session Mode
If we are using In-Proc session handling then all the session information will be stored in the server memory. This is the default session state in ASP.NET.
This approach works fine as long as we are keeping small session information. Since the memory location was handled by the ASP.NET worker thread only it involves a considerable overhead for the worker thread to manage these. Also, since this is in the memory of server, chances are that large session information would lead to more memory usage and thus lowering the performance.
Let us try to visualize this session management technique.









In-Proc sessions in Web Farm scenario

As we have discussed above the web farm will have a load balancer accepting all the requests. It will then forward the request to any server based on some criteria. Lets try to see a scenario which could create problems for us if we are using In-Proc sessions.
  1. The request from Computer1 reaches the load balancer and load balancer forwards it to server1.
  2. The In-Proc session led the session data created in the server1's memory.
  3. The next request comes from Computer1 and this time load balancer pushes it to Server2.
  4. Since the server1 had this user specific data in its memory server2 will not be able to recognize this request leading to failure of our application logic.
So what should we do to tackle this situation. The whole problem was because each server in our web form was keeping the session data in their own memory. If we could somehow move this data from each server memory to a centralized location then we will not face this problem. And that is where the SQLServer and stateServer comes to rescue. using these two approaches we can easily configure a central repository to store session data.









SQLServer Session Mode

If we use the SqlServer mode of session management then the session data will be stored in the SqlServer. The benefit of having this scenario is that the data is stored in a centralized database rather than the server memory. Let us see how this can be configured from web.config



StateServer Session Mode

If we use the StateServer mode of session management then the session data will be stored in a separate computer(server) and the session data will be handled by a windows service. The benefit of having this scenario is that the data is stored in a centralized location i.e. a state server rather than the individual server memory. Let us see how this can be configured from web.config

<sessionState mode="StateServer" 
                stateConnectionString="tcpip=127.0.0.1:42424" 
                sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;" 
                cookieless="false" 
                timeout="100"/>




mode This specifies the type of session management we want to use. it could be InProc, SQLServer, and StateServer
stateConnectionString If we use StateServer as session management technique then this specifies the location of the server that is handling the session data.
sqlConnectionString If we use SQLServer as session management technique then this specifies the database connectionstring that will store the session data.
cookieless This specifies whether we will be using cookies to identify sessions or we want session info appended in URL. It could be true or false.
timeout This specifies the time for which the session should be active. after this much time of inactivity the session will expire. 
mode This specifies the type of session management we want to use. it could be InProc, SQLServer, and StateServer
stateConnectionString If we use StateServer as session management technique then this specifies the location of the server that is handling the session data.
sqlConnectionString If we use SQLServer as session management technique then this specifies the database connectionstring that will store the session data.
cookieless This specifies whether we will be using cookies to identify sessions or we want session info appended in URL. It could be true or false.
timeout This specifies the time for which the session should be active. after this much time of inactivity the session will expire. 

Thursday, 9 May 2013

Select gridview row using Javascript



I want to select particular row of gridview with using UpdatePanel or postback

For that I prefer javascript ,

Javascript Code :

     <script type="text/javascript">

      /*Script For Highlighting particlar row */

        function HighlightRow(chkB) {
            var IsChecked = chkB.checked;
            if (IsChecked) {
                chkB.parentElement.parentElement.style.backgroundColor = '#F5D0A9';
                chkB.parentElement.parentElement.style.color = 'white';
                // chkB.parentElement.cell[7].disabled = true;
                //  document.getElementbyID('ddlGridSubDepartment').disabled = '';
                chkB.removeattr

            } else {
                chkB.parentElement.parentElement.style.backgroundColor = 'white';
                chkB.parentElement.parentElement.style.color = 'black';
            }
        }


    /*Script For selecting all rows */

    function selectAll(invoker) {
            // Since ASP.NET checkboxes are really HTML input elements
            //  let's get all the inputs            
             var inputElements = document.getElementsByTagName('input');
            for (var i = 0; i < inputElements.length; i++) {
                var myElement = inputElements[i];
                // Filter through the input types looking for checkboxes
                if (myElement.type === "checkbox") {
                    // Use the invoker (our calling element) as the reference
                    //  for our checkbox status
                    myElement.checked = invoker.checked;
                }
            }
        } 

</script>


<asp:GridView ID="gvMasterRecord" ..... >

 <Columns>
                                              
 <asp:TemplateField HeaderText="chk">
        <ItemTemplate>
               <asp:CheckBox ID="chkRecord" runat="server" AutoPostBack="true" onClick="javascript:HighlightRow(this);" OnCheckedChanged="chkRecord_CheckedChanged" />
       </ItemTemplate>
        <HeaderTemplate>
                <asp:CheckBox ID="chkRecord" runat="server" OnClick="selectAll(this)" />
       </HeaderTemplate>
</asp:TemplateField>
</columns>

</asp:GridView>





Saturday, 4 May 2013

Private assembly and a shared assembly

Introduction

I have seen many people posting the questions about what is shared assemblly, What is private assembly, so I thought of bringing it in the articles section so that everyone could be benefitted from it. This article explains a mcuh needed introduction to new comers in .Net

ASSEMBLIES

Assemblies are basically the compiled code in .Net which contains the code in Microsoft Intermediate Langauge and one more thing that assembiles do for us as compared to dlls is they can maintain versioning with the help of the manifest.
You dont need to register the assemblies after compiling like we needed in dlls. you can put the assemblies in the bin folder and refer the namespaces from there.
In short find the assembly description as :
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

Differences Between Shared and Private Assemblies and how to use them.


A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is intended to be used by multiple applications, and is normally stored in the global assembly cache (GAC), which is a central repository for assemblies. (A shared assembly can also be stored outside the GAC, in which case each application must be pointed to its location via a codebase entry in the application's configuration file.) The main advantage of deploying assemblies to the GAC is that the GAC can support multiple versions of the same assembly side-by-side.

Shared and Private Assembly: A private assembly is a assembly that is available to particular applications where they are kept. And cannot be references outside the scope of the folder where they are kept.
In contrast, Shared Assemblies are the assemblies that are accessible globally/shared across the machine to all the applications. For using the shared assemblies you need to register the assembly with a strong name in the global assembly cache(GAC) using gacutil.exe. GAC can be found on all the computers with .Net framework installed.

Assemblies deployed to the GAC must be strong-named. Outside the GAC, strong-naming is optional.