Tuesday, 8 October 2013

Chart Example in C#.NET

First we need to install MS chart Software in our system if not installed. Follow this link to download MS Chart. Download

Now install it to your system.

Now Open Visual Studio 2008

1. Create a website and a page with name MSChart.aspx (anything)
2. Right click on Toolbox, click on "Add Tab" and name it to 'MS Chart'.
3. Right click on 'MS Chart' click on 'Choose Items..'
4. A dialogue box will appear here click on 'Browse..' button and add 'System.Web.DataVisualiztion.dll' which is
    stored "C:\Program Files\Microsoft Chart Controls\Assemblies" here.

5. Click OK.

Now you can see MS Chart Control in Toolbox inside MSChart Tab.


Note:

1.    Don't Forget to Register like
<%@ Register Assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

2. Web.Congif
    1.  <appSettings>
    <!--<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />-->  <!-- this may fire error so better to use written below. -->
       
        <add key="ChartImageHandler" value="storage=file;timeout=20;" />
       
    2.  <httpHandlers>

          <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />

    3.    <handlers>       <! -- Attention: It may added already. -->

          <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
         
    4.    <assemblies>

          <add assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>


Now your MSChart.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MSChart.aspx.cs" Inherits="MSChart" %>

<%@ Register Assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
<!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>MS Chart</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Chart ID="Chart1" runat="server">
            <Series>
                <asp:Series Name="Series1">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                </asp:ChartArea>
            </ChartAreas>
        </asp:Chart>
        <br />
        <asp:Chart ID="Chart2" runat="server" Width="506px">
            <Series>
                <asp:Series Name="Series1">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                    <Area3DStyle Enable3D="true" />
                </asp:ChartArea>
            </ChartAreas>
            <Legends>
                <asp:Legend Name="Legend1" Title="Testing" BackColor="128, 255, 255">
                </asp:Legend>
            </Legends>
        </asp:Chart>
        <br />
        <asp:Chart ID="Chart3" runat="server" Width="506px">
            <Series>
                <asp:Series Name="Population" ChartType="Column" BorderColor="Red" Color="Blue">
                </asp:Series>
                <asp:Series Name="People In Job" ChartType="Column" BorderColor="Red" Color="Green">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                </asp:ChartArea>
            </ChartAreas>
            <Legends>
                <asp:Legend Name="Legend1" Title="Jobs" BackColor="Gray">
                </asp:Legend>
            </Legends>
        </asp:Chart>
    </div>
    </form>
</body>
</html>


and your C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using MyFreameWork;
using System.Data;


public partial class MSChart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        fillTempPulseEtc();
        Countries();
        CountriesAndJobs();
    }

    private void fillTempPulseEtc()
    {
        double[] temp = { 0.0, 111.0 };
        double[] time = { -23.0, 23.59 };
        for (int i = 0; i <= 2; i++)
        {
            Chart1.Series[0].Points.DataBindXY(time, temp);
        }
        Chart1.Series[0].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Column;
    }

    private void Countries()
    {
        MyDataUtility objUtility = new MyDataUtility();
        DataTable dt = new DataTable();
        dt = objUtility.GetDataTable("Select * From Countries");
        if (dt.Rows.Count > 0)
        {
            Chart2.DataSource = dt;

            Chart2.Series["Series1"].XValueMember = Convert.ToString("Names");
            Chart2.Series["Series1"].YValueMembers = Convert.ToString("Populations");

            Chart2.DataBind();
        }
    }

    private void CountriesAndJobs()
    {
        MyDataUtility objUtility = new MyDataUtility();
        DataTable dt = new DataTable();
        dt = objUtility.GetDataTable("Select * From CountriesAndJobs");
        if (dt.Rows.Count > 0)
        {
            Chart3.DataSource = dt;

            Chart3.Series["Population"].XValueMember = Convert.ToString("Names");
            Chart3.Series["Population"].YValueMembers = Convert.ToString("Populations");

            Chart3.Series["People In Job"].XValueMember = Convert.ToString("Names");
            Chart3.Series["People In Job"].YValueMembers = Convert.ToString("PeoplesInJob");

            Chart3.DataBind();
        }
    }
}

** I used here framework you can simply use SQLConnection, Command etc.

Here it your database.


Create Table Countries(Contid int Identity(1,1),Names varchar(50), Populations bigint)

Insert INTO Countries values('India',1250000000)
Insert INTO Countries values('Pakistan',250000000)
Insert INTO Countries values('China',2250000000)
Insert INTO Countries values('America',20000000)
Insert INTO Countries values('Australia',350000000)
Insert INTO Countries values('South Africa',2000000)
Insert INTO Countries values('Nepal',1250000000)
Insert INTO Countries values('Bhutan',300000)
Insert INTO Countries values('New Zeland',100000000)
--    Select * From Countries

Create Table CountriesAndJobs(Contid int Identity(1,1),Names varchar(50), Populations bigint,PeoplesInJob bigint)

Insert INTO CountriesAndJobs values('India',1250000000,1050000000)
Insert INTO CountriesAndJobs values('Pakistan',250000000,20000000)
Insert INTO CountriesAndJobs values('China',2250000000,250000000)
Insert INTO CountriesAndJobs values('America',20000000,200000)
Insert INTO CountriesAndJobs values('Australia',350000000,30000000)
Insert INTO CountriesAndJobs values('South Africa',2000000,2000000)
Insert INTO CountriesAndJobs values('Nepal',1250000000,150000000)
Insert INTO CountriesAndJobs values('Bhutan',300000,300000)
Insert INTO CountriesAndJobs values('New Zeland',100000000,100000000)

--    Select *  From CountriesAndJobs


--SELECT *, SUM(PeoplesInJob) OVER() as TotalSales FROM CountriesAndJobs


Ref:  http://www.codeproject.com/Tips/269985/How-to-draw-charts-in-asp-net-using-MS-chart


I hope it may help you.

Cheers!!!

Monday, 7 October 2013

string vs StringBuilder



Most of the people use string everywhere in their code. Actually when doing string concatenation, do you know what exactly you are doing? It has a big drawback mainly in concatenation which can be overcome by StringBuilder. It will give a vast improvement in performance when you use concatenation of string over String.

What is the Exact Difference?

First we will look at what happens when you concatenate two strings. For a rough idea, think like this. In a loop, you are adding few numbers to get a string to give all the numbers.
 
string returnNumber = "";
for(int i = 0; i<1000; i++)
{ 
    returnNumber = returnNumber + i.ToString();
}
 
Here we are defining a string called returnNumber and after that, in the loop we are concatenating the old one with the new to get a string. Do you know when we do like that we are assigning it again and again? I mean it's really like assigning 999 new strings!

Actually the concatenation will create a new string returnNumber, with both old returnNumber and i.ToString(). If we think roughly, how will the performance of the code be? Can you imagine it? No one thinks about this when coding.
If we can have something which is to be defined only once and add all the strings into it, what can you say about the performance. That's what StringBuilder does.
 
StringBuilder returnNumber = new StringBuilder(10000);
for(int i = 0; i<1000; i++)
{ 
    returnNumber.Append(i.ToString());
}
 
We are creating a StringBuilder of length 10000 in memory where we can add all the strings. This surely won't create a new string each and every time. Actually we are creating a StringBinder, and whenever something is added it will get copied into that memory area. At the end, we can get the string by StringBuilder.ToString(). Here also, it won't create a new string. It will return a string instance that will point to the string inside the StringBuilder. See, how efficient this is?

 

 

Why String? Can't Use StringBinder Everywhere?

 

No. You can't. When initializing a StringBuilder, you are going down in performance. Also many actions that you do with string can't be done with StringBinder. Actually it is used mostly for situations as explained above. If you using StringBuilder to just add two strings together! It's really nonsense. We must really think about the overhead of initialization. In my personal experience, a StringBuilder can be used where more than four or more string concatenations take place. Also if you try to do some other manipulation (like removing a part from the string, replacing a part in the string, etc.), then it's better not to use StringBuilder at those places. This is because we are anyway creating new strings. Another important issue. We must be careful to guess the size of StringBuilder. If the size which we are going to get is more than what is assigned, it must increase the size. This will reduce its performance.



String is immutable. It means that you can't modify string at all, the result of modification is new string. This is not effective if you plan to append to string

System.Text;
StringBuilder is mutable. It can be modified in any way and it doesn't require creation of new instance. When work is done, ToString() can be called to get the string.


Ref: http://codeproject.com/

Sunday, 15 September 2013

Register Ajax on asp.net page


1. Add Reference "Ajax.dll".

2. Write To Register.

    <httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      <!-- Add This To Register Ajax. -->
      <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
        </httpHandlers>
      
3. On Page

using Ajax;


4. Page_Load
public partial class ProgramFiles_Administration_Modules : System.Web.UI.Page
Ajax.Utility.RegisterTypeForAjax(typeof(ProgramFiles_Administration_Modules));

5.

[Ajax.AjaxMethod]
    public string InsertValues(string hID)
    {
        string myVal= hid+" is Fine.";
        return myVal.ToString();
    }
   
6.  Call C# Method Form Aspx.

Add jquery-1.4.1.min.js

 <script type="text/javascript">
   
        var count=1;
       
        function EEEE(ddlvalue)
        {
            var response = ProgramFiles_Administration_Modules.InsertValues(ddlvalue);
        }
    </script>       
** NOTE:   ajax method must be public.

Cheers!!!   

Monday, 19 August 2013

How to force controls to work on postback of other controls inside GridView



1.

     <asp:TemplateField HeaderText="">
        <EditItemTemplate>
            <asp:RadioButtonList ID="rdVorI" runat="server" RepeatDirection="Horizontal" AutoPostBack="true"
                OnSelectedIndexChanged="rdVorI_SelectedIndexChanged">

                <asp:ListItem Value="Video" Text="Video" Selected="True"></asp:ListItem>
                <asp:ListItem Value="Image" Text="Image"></asp:ListItem>
            </asp:RadioButtonList>
        </EditItemTemplate>
    </asp:TemplateField>
   
    <asp:TemplateField HeaderText="Video">
        <ItemTemplate>
            <asp:ImageButton ID="vdoBtn" Height="60px" Width="60px" AlternateText="Video" BorderWidth="1px"
                BorderColor="Black" runat="server" title="Click Here" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtEvCode" runat="server" Width="160px" />
        </EditItemTemplate>
    </asp:TemplateField>
   
    <asp:TemplateField HeaderText="Images">
        <ItemTemplate>
            <asp:HiddenField ID="key" runat="server" Value='<%#Eval("EventID") %>' />   
                                          
            <asp:ImageButton ID="imgBtn" class="thumbnail" AlternateText="Image" BorderWidth="1px"
                BorderColor="Black" runat="server" />
            <asp:ImageButton ID="imgBtn2" class="thumbnail" AlternateText="Image" BorderWidth="1px"
                BorderColor="Black" runat="server" />
            <asp:ImageButton ID="imgBtn3" class="thumbnail" AlternateText="Image" BorderWidth="1px"
                BorderColor="Black" runat="server" />
        </ItemTemplate>                                
        <EditItemTemplate>
            <asp:FileUpload ID="FileUpload1" runat="server" /><br />
            <asp:FileUpload ID="FileUpload2" runat="server" /><br />
            <asp:FileUpload ID="FileUpload3" runat="server" />
        </EditItemTemplate>
    </asp:TemplateField>
   
2.
   
    protected void rdVorI_SelectedIndexChanged(object sender, EventArgs e)
    {
 
        GridViewRow gr = (GridViewRow)((DataControlFieldCell)((RadioButtonList)sender).Parent).Parent;
        RadioButtonList rdl = (RadioButtonList)gr.FindControl("rdVorI");
        FileUpload vFile1 = (FileUpload)gr.FindControl("FileUpload1");
        FileUpload vFile2 = (FileUpload)gr.FindControl("FileUpload2");
        FileUpload vFile3 = (FileUpload)gr.FindControl("FileUpload3");
        TextBox vTitle = (TextBox)gr.FindControl("txtEvCode");
        if (rdl.SelectedValue == "Video")
        {
            vFile1.Enabled = false;
            vFile2.Enabled = false;
            vFile3.Enabled = false;
            vTitle.Enabled = true;
        }
        else
        {

            vTitle.Enabled = false;
            vFile1.Enabled = true;
            vFile2.Enabled = true;
            vFile3.Enabled = true;
        }

    }


Cheers!!!

Tuesday, 13 August 2013

Dynamically generate and display Thumbnail picture by resizing the Image in ASP.Net

In this article I explain how to dynamically resize image and generate its Thumbnail and also display it on ASP.Net web page.
HTML Markup
In the form below as you can see I have 2 ASP.Net Image Controls of which one displays the original image while other displays the Thumbnail of the original image. Also there is an ASP.Net Button control which generates the Thumbnail.
 
<form id="form1" runat="server">
<asp:Image ID="Image1" runat="server" ImageUrl = "~/Jellyfish.jpg" Height = "400px" Width = "400px"/>
<br />
<asp:Button ID="btnGenerate" OnClick = "GenerateThumbnail" runat="server" Text="Generate Thumbnail" />
<hr />
<asp:Image ID="Image2" runat="server" Visible = "false"/>
</form>
 
 
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
 
Resizing Image and Generating Thumbnail
Below is the code that dynamically resizes the picture and generates the Thumbnail and also displays it in Image Control
C#
protected void GenerateThumbnail(object sender, EventArgs e)
{
    string path = Server.MapPath("~/Jellyfish.jpg");
    System.Drawing.Image image = System.Drawing.Image.FromFile(path);
    using (System.Drawing.Image thumbnail = image.GetThumbnailImage(100, 100, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            thumbnail.Save(memoryStream, ImageFormat.Png);
            Byte[] bytes = new Byte[memoryStream.Length];
            memoryStream.Position = 0;
            memoryStream.Read(bytes, 0, (int)bytes.Length);
            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
            Image2.ImageUrl = "data:image/png;base64," + base64String;
            Image2.Visible = true;
        }
    }
}
 
public bool ThumbnailCallback()
{
    return false;
}
 
 In GridView As:
 
If you want to show thumbnal in girdview than;

1.  OnRowDataBound="gvEditEvents_RowDataBound"

    <asp:TemplateField HeaderText="Images">
        <ItemTemplate>
            <asp:ImageButton ID="imgBtn" AlternateText="Image" BorderWidth="1px"
                BorderColor="Black" runat="server" />                                 
        </ItemTemplate>
    </asp:TemplateField>
   
2.
    protected void gvEditEvents_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
             if ((e.Row.RowState & DataControlRowState.Edit) == 0)
                {
                    string imgPath = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ImagePathOne"));
                    if (!string.IsNullOrEmpty(imgPath))
                    {
                        ImageButton imgBtn = (ImageButton)e.Row.FindControl("imgBtn");

                        string path = Server.MapPath(imgPath.Replace("\\RootFolder", "..\\.."));
                        System.Drawing.Image image = System.Drawing.Image.FromFile(path);
                        using (System.Drawing.Image thumbnail = image.GetThumbnailImage(60, 60, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
                        {
                            using (MemoryStream memoryStream = new MemoryStream())
                            {
                                thumbnail.Save(memoryStream, ImageFormat.Png);
                                Byte[] bytes = new Byte[memoryStream.Length];
                                memoryStream.Position = 0;
                                memoryStream.Read(bytes, 0, (int)bytes.Length);
                                string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                                imgBtn.ImageUrl = "data:image/png;base64," + base64String;
                                imgBtn.Visible = true;
                            }
                        }
                    }
                 }
            }
        }
      
3.

    public bool ThumbnailCallback()
    {
        return false;
    }
   
4.
   
    using System.IO;
    using System.Drawing;
    using System.Drawing.Imaging;
Cheers!!
   
    

Friday, 9 August 2013

Disable all events in web pages.

1.  Disable all events of a page.
<script language="javascript" type="text/javascript">
 $(document).ready(function() {
            $(document).bind("contextmenu", function(e) {
                     return false;

             }); 
}); 
 </script>
2.  Disable all events in Iframe.
 <script language="javascript" type="text/javascript">
      function disableRightClick(frameID)
      {
            var ifrm = document.getElementById(frameID);
            var innerDoc = ifrm.contentDocument ? ifrm.contentDocument : ifrm.contentWindow.document;
            $(innerDoc).bind("contextmenu", function(e) {
                return false;
            });
      }

 </script>
 and Call : onload="javascript:disableRightClick('
myframe');"

 NOTE: 
1. must add jquery file (jquery-1.4.min.js) to enable jquery on your page.
2. In iframe put all attrubute in double quote as id="myframe".


Cheers!!




Friday, 31 May 2013

Bind Days, Months and Year To Dropdown

 using System.Globalization;


protected void Fill_DD_MM_YYYY()
        {
        //  Date.
        for (int i = 1; i <= System.DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); i++)
        {
            ddlDay.Items.Add(i.ToString());
        }
        ddlDay.Items.Insert(0, "Select");
        ddlDay.SelectedIndex = 0;


        //  Months.
        ListItem lcc;
        foreach (string item in DateTimeFormatInfo.CurrentInfo.MonthNames)
        {
            if (item != "")
            {
                lcc = new ListItem();
                lcc.Text = item;
                lcc.Value = item;
                ddlMonths.Items.Add(lcc);
            }
        }
        ddlMonths.Items.Insert(0, "Select");
        ddlMonths.SelectedIndex = 0;



        //  Years.
        for (int i = 0; i <= 30; i++)
        {
            ddlYear.Items.Add((1990 + i).ToString());
        }
        ddlYear.Items.Insert(0, "Select");
        ddlYear.SelectedIndex = 0;
    }



Days: <asp:DropDownList ID="ddlDay" runat="server"></asp:DropDownList><br/>
       
Months:<asp:DropDownList ID="ddlMonths" runat="server"></asp:DropDownList><br/>

Years:<asp:DropDownList ID="ddlYear" runat="server"></asp:DropDownList><br/>