Sunday, 5 May 2013

C# Ado.net SqlCommand Example

C# Ado.net SqlCommand Example:-

.cs
-----------------

  protected void Page_Load(object sender, EventArgs e)
    {
        string webConfig = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        SqlConnection con = new SqlConnection(webConfig);
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from dbo.SampleData";
        cmd.Connection = con;
        //SqlCommand cmd = new SqlCommand("select * from SampleData", con);
        SqlDataReader reader = cmd.ExecuteReader();
        //reader.Read();
        //Label1.Text = reader.GetValue(1).ToString();
        StringBuilder sb = new StringBuilder();
        while (reader.Read())
        {
            sb.Append(reader.GetValue(0));
            sb.Append(" ");
            sb.Append(reader["name"]);
            sb.Append("<br />");
        }
        Label1.Text = sb.ToString();
        reader.Close();
        con.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string webConfig = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        SqlConnection con = new SqlConnection(webConfig);
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from SampleData; select * from dbo.NullData";
        cmd.Connection = con;
        //SqlCommand cmd = new SqlCommand("select * from SampleData", con);
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        //reader.Read();
        //Label1.Text = reader.GetValue(1).ToString();
        StringBuilder sb = new StringBuilder();
        do
        {
            while (reader.Read())
            {
                if (reader.GetValue(0) == DBNull.Value)
                {
                    sb.Append("null value");
                }
                else
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        sb.Append(reader.GetValue(i));
                        sb.Append(" ");                       
                    }
                    sb.Append("<br />");
                }
            }
        } while (reader.NextResult());
        Label2.Text = sb.ToString();
        reader.Close();
    }
}

C# Ado.Net Sql Parameter Example

C# Ado.Net Sql Parameter Example:-

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

<!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">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /><br />
        <br />
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F8FAFA" />
            <SortedAscendingHeaderStyle BackColor="#246B61" />
            <SortedDescendingCellStyle BackColor="#D4DFE1" />
            <SortedDescendingHeaderStyle BackColor="#15524A" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>


.cs

  protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("select * from SampleData where Id = @Id", con))
                {
                    SqlParameter param1 = new SqlParameter("@Id", TextBox1.Text);
                    cmd.Parameters.Add(param1);
                    SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    GridView1.DataSource = reader;
                    GridView1.DataBind();
                }
            }
        }
        catch (Exception error)
        {
            Page.Response.Write("Error on page");
        }
    }
}

C# Ado.Net Excute Procedure Example


C#  Ado.Net Excute Procedure Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

public partial class Procedure : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString);
        //con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "InsertSampleData";
        cmd.Connection = con;
        cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4));
        cmd.Parameters["@Id"].Value = 27492;
        //cmd.Parameters["@Id"].Direction = ParameterDirection.Output;

        cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar, 20));
        cmd.Parameters["@Name"].Value = "Pankaj Srivastav";

        con.Open();
        cmd.ExecuteNonQuery();
        Page.Response.Write(cmd.Parameters["@Id"].Value);
        con.Close();
    }
}

C# Ado.net Transaction example:

 C# Ado.net Transaction example:

.aspx

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

<!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">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

public partial class Transaction : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = null; new SqlConnection(WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString);
        SqlCommand cmd1 = new SqlCommand();
        cmd1.CommandType = CommandType.Text;
        cmd1.CommandText = "update SampleAccount set Balance = Balance - @Amount where Id='A'";
        cmd1.Connection = con;
        cmd1.Parameters.Add(new SqlParameter("@Amount", Convert.ToInt32(TextBox1.Text)));

        SqlCommand cmd2 = new SqlCommand("update SampleAccount set Balance = Balance + @Amount where Id='B'", con);
        cmd2.Parameters.Add(new SqlParameter("@Amount", Convert.ToInt32(TextBox1.Text)));
        SqlTransaction trans = null;

        try
        {
            con.Open();
            trans = con.BeginTransaction();
            cmd1.Transaction = trans;           
            cmd1.ExecuteNonQuery();
            trans.Save("pankaj");
            throw new ApplicationException();
            cmd2.Transaction = trans;           
            cmd2.ExecuteNonQuery();
            trans.Commit();
            Page.Response.Write("Success");
        }
        catch (Exception)
        {
            trans.Rollback("pankaj");
            Page.Response.Write("Fail");
            trans.Commit();
        }
        finally
        {
            con.Close();
        }
    }
}


Saturday, 4 May 2013

C# Compare Generic List Collection Compare

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CompareLists
{
    class Program
    {
        static void Main(string[] args)
        {
List<string> myfirstList= new List<string>() { "One", "Two", "Three"};
List<string> mysecondList = new List<string>() { "One", "Four", "Three"};
List<string> myThirdList = new List<string>() { "One", "Four", "Three", "Five" };
List<string> myfourthList = new List<string>() { "One", "Two", "One", "Four", "Two" };

IEnumerable<string> newList= null;


// Compare two List<string> and display common elements

newList= myfirstList.Intersect(mysecondList , StringComparer.OrdinalIgnoreCase);

//OutPut in  newList

// Compare two List<string> and display items of myfirstList not in mysecondList
newList= myfirstList.Except(mysecondList , StringComparer.OrdinalIgnoreCase);
//OutPut in  newList

// Unique List<string>

newList= myfourthList .Distinct(StringComparer.OrdinalIgnoreCase);
//output in newList
// Convert elements of List<string> to Upper Case
newList= myfriestList.ConvertAll(x => x.ToUpper());

//output in newList

// Concatenate and Sort two List<string>

newList= myfirstList.Concat(mysecondList).OrderBy(s => s);
/output in newList
// Concatenate Unique Elements of two List<string>
newList= myfirstList.Concat(mysecondList).Distinct();
//Output in newList

 // Order by Length then by words (descending)         newList = mythirdList.OrderBy(x => x.Length)
                    .ThenByDescending(x => x);



/ /Create a string by combining all words of a List<string>
           
            string delim = ",";
            var strresult = myfirstList.Aggregate((x, y) => x + delim + y);
        

    // Create a List<string> from a Delimited string
            string s = "One Two Three";
            char separator = ' ';
            newList = s.Split(separator).ToList();          


// Convert a List<int> to List<string>

            List<int>listNum = new List<int>(new int[] { 3, 6, 7, 9 });
            newList = listNum .ConvertAll<string>(delegate(int i)
            {
               return i.ToString();
            });



 // Count Repeated Words
            var q = myfourthList.GroupBy(x => x)
               .Select(g => new { Value = g.Key, Count = g.Count() })
               .OrderByDescending(x => x.Count);

            foreach (var x in q)
            {
               Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
            }



// Reverse a List<string>
myfirstList.Reverse();

// Search a List<string> and Remove the Search Item
// from the List<string>

int Count= myfourthList.RemoveAll(x => x.Contains("Two"));
Console.WriteLine("{0} items removed", Count);


            Console.ReadLine();         
        }

Autocomplete using asp.net Jquery Webservice calliing Core Ajax

.aspx

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

<!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>AutoComplete Box with jQuery</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 

    <script type="text/javascript">
        $(function() {
            $(".
txtAutosuggest").autocomplete({
                source: function(request, response) {
                    $.ajax({
                        url: "EmployeeList.asmx/
GetEmailList",
                        data: "{ 'mail': '" + request.term + "' }",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function(data) { return data; },
                        success: function(data) {
                            response($.map(data.d, function(item) {
                                return {
                                    value: item.Email
                                }
                            }))
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
                minLength: 2
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="demo">
        <div class="ui-widget">
            <label for="AutoSuggest">Enter Email: </label>
             <asp:TextBox ID="txtAutosuggest" class="tb" runat="server">
             </asp:TextBox>
        </div>
    </div>
    </form>
</body>
</html>


App_Code:-
Employee.cs
 using System.Collections.Generic;
/// <summary>
/// Summary description for Employee
/// </summary>
public class Employee
{
    public int ID { get; set; }
    public string Email { get; set; }

    public Employee()
    {
    }
    public List<Employee> GetEmployeeList()
    {
        List<Employee> empList = new List<Employee>();
        empList.Add(new Employee() { ID = 1, Email = "Pankaj@mymail.com" });
        empList.Add(new Employee() { ID = 2, Email = "akash@
mymail.com" });
        empList.Add(new Employee() { ID = 3, Email = "Aaditya@
mymail.com" });
        empList.Add(new Employee() { ID = 4, Email = "suresh@
mymail.com" });
        empList.Add(new Employee() { ID = 5, Email = "suraj@
mymail.com" });
     
        return empList;
    }

}

EmployeeList.cs:-//create WebMethod

using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Web.Script.Services;

[WebService(Namespace = "http://tempuri.org/")]
 
[ScriptService]
public class EmployeeList : System.Web.Services.WebService
{
[WebMethod]
public List<Employee> GetEmailList(string mail)
{
    var emp = new Employee();
    var getEmail = emp.GetEmployeeList()
    .Where(m => m.Email.ToLower().StartsWith(mail.ToLower()));
    return
getEmail .ToList();
}   
}

 

Asyncronus Image in GridView

Asyncronus Image in GridView:


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

<!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>Asynchronous Image</title>
    <script type="text/javascript" language="javascript">
        function RetrievePictureFromHandler(imgCtrl, picid)
        {
            imgCtrl.onload = null;
            imgCtrl.src = 'ShowImage.ashx?id=' + picid;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataSourceID="SqlDataSource1" AllowPaging="True">
    <Columns>
        <asp:BoundField DataField="pic_id" HeaderText="Picture ID" InsertVisible="False"
            ReadOnly="True" SortExpression="pic_id" />
        <asp:BoundField DataField="picture_tag" HeaderText="Tags"
            SortExpression="picture_tag" />
            <asp:TemplateField>
                <HeaderTemplate>Picture</HeaderTemplate>
                <ItemTemplate>
                    <img alt="pic" src="images/cursor.jpg" onError="this.src='images/error.jpg'"
                    onload="
RetrievePictureFromHandler(this,'<%# Eval("pic_id")%>');"  width="150" height="150"/>
                </ItemTemplate>
            </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:PictureAlbumConnectionString %>"
    SelectCommand="SELECT [pic_id], [picture_tag] FROM [Album]">
</asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>



.ashx(generic handler) file:
<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.ComponentModel;

public class ShowImage : IHttpHandler
{
    long seq = 0;
    byte[] empPic = null;

    public void ProcessRequest(HttpContext context)
    {
        Int32 picid;
        if (context.Request.QueryString["id"] != null)
            picid = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        // Convert Byte[] to Bitmap
        Bitmap newBmp = ConvertToBitmap(ShowAlbumImage(picid));
        if (newBmp != null)
        {
            newBmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            newBmp.Dispose();
        }

    }

    // Convert byte array to Bitmap (byte[] to Bitmap)
    protected Bitmap ConvertToBitmap(byte[] bmp)
    {
        if (bmp != null)
        {
            TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
            Bitmap b = (Bitmap)tc.ConvertFrom(bmp);
            return b;
        }
        return null;
    }

    public byte[] ShowAlbumImage(int picid)
    {
        string conn = ConfigurationManager.ConnectionStrings["PictureAlbumConnectionString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT pic FROM Album WHERE Pic_ID = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", picid);
        try
        {
            connection.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                seq = dr.GetBytes(0, 0, null, 0, int.MaxValue) - 1;
                empPic = new byte[seq + 1];
                dr.GetBytes(0, 0, empPic, 0, Convert.ToInt32(seq));
                connection.Close();
            }

            return empPic;
        }

        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


}

Asp.Net Panel SlideShow Using Jquery

 Asp.Net Panel SlideShow Using Jquery :-

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

<!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>
    <style type="text/css">
        .divNoBorder
        {
            background-color:White;
            font-family:"Lucida Sans Unicode", "Lucida Grande", Verdana, Arial;
            font-size:12px;
            color:#000000;
            width:510px;
            margin-left:auto;
            margin-right:auto;
            padding:10px;
        }   
    </style>
   
     <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"
     type="text/javascript"></script>

    
     <script type="text/javascript">
        $(function() {
            var $divSlide = $("div.slide");
            $divSlide.hide().eq(0).show();
            var panelCnt = $divSlide.length;

            setInterval(panelSlider, 3000);

            function panelSlider() {
                $divSlide.eq(($divSlide.length++) % panelCnt)
                .slideUp("slow", function() {
                    $divSlide.eq(($divSlide.length) % panelCnt)
                        .slideDown("slow");
                });
            }
        });
     </script>
    
</head>
<body>
<form id="form1" runat="server">
    <div class="divNoBorder">
        <h2>Slide Show with Panels.
        Each Panel is Visible for 3 seconds.</h2>
        <br /><br />
         <asp:Panel ID="panelOne" runat="server" class='slide'>
            Panel 1 Content Panel 1 Content Panel 1 Content
            Panel 1 Content Panel 1 Content Panel 1 Content
            Panel 1 Content Panel 1 Content Panel 1 Content
            Panel 1 Content Panel 1 Content Panel 1 Content           
        </asp:Panel>
        <asp:Panel ID="panelTwo" runat="server" class='slide'>
            Panel 2 Content Panel 2 Content Panel 2 Content
            Panel 2 Content Panel 2 Content Panel 2 Content
          
        </asp:Panel>
        <asp:Panel ID="panelThree" runat="server" class='slide'>
           Panel 3 Content Panel 3 Content Panel 3 Content
           Panel 3 Content Panel 3 Content Panel 3 Content
       
        </asp:Panel>
        <asp:Panel ID="panelFour" runat="server" class='slide'>
             Panel 4 Content Panel 4 Content Panel 4 Content
             Panel 4 Content Panel 4 Content Panel 4 Content
        </asp:Panel>
        <asp:Panel ID="panelFive" runat="server" class='slide'>
            Panel 5 Content  Panel 5 Content  Panel 5 Content
        </asp:Panel>
    </div>
    </form>
</body>
</html>

Asp.net 4.0 Bind Chart to XML

.aspx.cs

using System;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

       protected void btnBindChart_Click(object sender, EventArgs e)
    {
        string dataPath = MapPath(".") + "\\books.xml";

        DataSet ds = new DataSet();
        ds.ReadXml(dataPath);
        DataTable dt = ds.Tables[0];
        DataView dataView = new DataView(dt);
        // Bind XML
        chartBooks.Series[0].Points.DataBindXY(dataView, "title", dataView, "price");       
    }
}

.aspx:

<%@ Page Title="Home Page" Language="C#"  AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

    <asp:Button ID="btnBindChart" runat="server" Text="Bind Chart to XML"
        onclick="btnBindChart_Click" />
    <asp:Chart ID="chartBooks" runat="server"  Width="700" Height="450"
         BackColor="LightBlue" BackSecondaryColor="AliceBlue"
         BackGradientStyle="TopBottom" BorderColor="DarkBlue">
        <Series>
            <asp:Series Name="Series1" ChartArea="ChartArea1" ChartType="Column"
                Color="Wheat">
            </asp:Series>
        </Series>
        <ChartAreas>
            <asp:ChartArea Name="ChartArea1" Area3DStyle-Enable3D="true" 
            BackColor="#0066cc" BorderColor="DarkBlue">
            </asp:ChartArea>
        </ChartAreas>
    </asp:Chart>

Highlight GridView Row on RowClick


 Highlight OnRowClick GridView Row:-


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

<!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 id="Head1" runat="server">
<title>Highlight Row on Click</title>

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

<script type="text/javascript">
    $(document).ready(function() {
        $("tr").filter(function() {
            return $('td', this).length && !$('table', this).length
        }).click(function() {
            $(this).toggleClass('currRow');
        });
    });
</script>

<style type="text/css">
    .currRow
    {
        background-color:Gray;
        cursor:pointer;
    }   
</style>

</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
        SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
    </asp:SqlDataSource>   
    <br />          
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
        DataSourceID="SqlDataSource1" AllowPaging="False" AllowSorting="True" >
        <Columns>                          
            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
            <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
            <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
            <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
        </Columns>
    </asp:GridView>
</div>
</form>
</body>
</html>

Highlight GridViewRow on Hover Using Jquery

 Highlight GridViewRow on Hover Using  Jquery :

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

<!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 id="Head1" runat="server">
    <title>Highlight Row on Hover</title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function() {
            $("tr").filter(function() {
                return $('td', this).length && !$('table', this).length
            }).css({ background: "ffffff" }).hover(
                function() { $(this).css({ background: "#C1DAD7" }); },
                function() { $(this).css({ background: "#ffffff" }); }
                );
        });
    </script>
   
</head>
<body>
    <form id="form1" runat="server">
       <div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
            </asp:SqlDataSource>   
            <br />          
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
                DataSourceID="SqlDataSource1" AllowPaging="False" AllowSorting="True" >
                <Columns>                          
                    <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                    <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                    <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
                    <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                    <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Drag Drop GridView Rows Using Jquery :-

Default.aspx:-

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

<!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>Drag Drop Rows</title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tablednd_0_5.js" type="text/javascript"></script>  //dragand drop jquery plugins
   
    <script type="text/javascript">
        $(document).ready(function() {
            $("#GridView1").tableDnD();
        });
</script>

</head>
<body>
    <form id="form1" runat="server">
       <div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
            </asp:SqlDataSource>   
            <br />          
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
                DataSourceID="SqlDataSource1" AllowPaging="False" AllowSorting="True" >
                <Columns>                          
                    <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                    <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                    <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
                    <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                    <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Creating Ajax Enabled WCF Services Asp.Net

MyService.svc
MyService.cs


using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

[ServiceContract(Namespace = "PankajNM")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService
{
   
    [OperationContract]
    public void DoWork()
    {
        // Add your operation implementation here
        return;
    }

  
    [OperationContract]
    public string GetUser(string uname)
    {
        return "Hello " + uname;
    }

}


Default.aspx


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

<!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>Create AJAX-enabled WCF Service</title>

    <script language="javascript" type="text/javascript">

        function btnCallWCF_onclick() {
            var GetTo= new PankajNM.MyService();
           
GetTo.GetUser($get("txtUNm").value, OnComplete, OnError);         
        }

        function OnGreetingComplete(result) {
            $get("
dispGuser").innerHTML = result;
        }

        function OnError(result) {
            alert(result.get_message());
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/MyService.svc" />
            </Services>
        </asp:ScriptManager>
       
        <input id="btnCallWCF" type="button" value="GetUser" onclick="return btnCallWCF_onclick()" />
        <input id="txtUNm" type="text" />
        <div id="dispGuser">
        </div>
    </div>
    </form>
</body>
</html>

Rotating ads using ASP.NET AdRotator and jQuery

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

<!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>
    <script type="text/javascript"
        src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            setInterval(function () {
                $("#adr").load(location.href + " #adr", "" + Math.random() + "");
            }, 4000);
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
<div class="ads">
        <asp:AdRotator
        id="adr"
        AdvertisementFile="~/App_Data/Ads.xml"
        KeywordFilter="small"
        Runat="server" />
</div>
    <br /><br />

    <asp:Label ID="lblTime" runat="server" Text=""></asp:Label>   
    </form>
</body>
</html>

Upload Mutiple File Using Jquery

Upload Mutiple File Using Jquery:-

Default.aspx 

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

<!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>Upload Multiple Files in ASP.NET Using jQuery</title>
        <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
        <script src="Scripts/jquery.MultiFile.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" class="multi" />
        <br />
        <asp:Button ID="btnUpload" runat="server" Text="Upload All"
            onclick="btnUpload_Click" />
    </div>
   
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    hpf.SaveAs(Server.MapPath("MyFiles") + "\\" +
                      System.IO.Path.GetFileName(hpf.FileName));
                    Response.Write("<b>File: </b>" + hpf.FileName + "  <b>Size:</b> " +
                        hpf.ContentLength + "  <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
                }
            }
        }
        catch (Exception ex)
        {
           
        }
    }
}


NOTE :-

Please use the following Jquery plugins..

1.jquery.MultiFile.js
2.jquery-1.9.1.js

Xml To Dictionary..

XML :-

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee EmpId="1'" Name="Pankaj" />
  <Employee EmpId="2" Name="Deepanshu"/>
  <Employee EmpId="3" Name="Akash"/>
  <Employee EmpId="4" Name="Ajay"/>
  <Employee EmpId="5" Name="Dinesh"/>
  <Employee EmpId="6" Name="Rahul"/>
  <Employee EmpId="7" Name="Deepak"/>
</Employees>


C# Code :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XMLToDict
{
    class Program
    {
static void Main(string[] args)
{
    XElement xelement = XElement.Load("..\\..\\Employees.xml");

    var empDict = (from element in xelement.Descendants("Employee")
                      let name = (string)element.Attribute("Name")
                      orderby name                   
                      select new
                      {
                          EmployeeID = element.Attribute("EmpId").Value,
                          EmployeeName = name
                      })
           .ToDictionary(a => a.EmployeeID,
                         a => a.EmployeeName);

    Console.ReadLine();

}
    }
}

Wednesday, 1 May 2013

Asp.net GridVew To PDF

.aspx

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

<!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>Sample Export</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <center><b>Export GridView to PDF</b></center>
                </td>
            </tr>
            <tr>
                <td>
                 
                    <div style="height:200px; overflow:auto">
                        <asp:GridView ID="gvExport" runat="server" AutoGenerateColumns="true">
                        </asp:GridView>
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnExport" runat="server" Text="Export to PDF" OnClick="btnExport_Click" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


.cs

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
        SqlCommand cmd = new SqlCommand("select * from StudentDetails", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvExport.DataSource = ds.Tables[0];
        gvExport.DataBind();
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        ExportToPDF(gvExport, true);
    }
    protected void ExportToPDF(GridView gvReport, bool LandScape)
    {
        int noOfColumns = 0, noOfRows = 0;
        DataTable tbl = null;

        if (gvReport.AutoGenerateColumns)
        {
            tbl = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control.
            noOfColumns = tbl.Columns.Count;
            noOfRows = tbl.Rows.Count;
        }
        else
        {
            noOfColumns = gvReport.Columns.Count;
            noOfRows = gvReport.Rows.Count;
        }

        float HeaderTextSize = 8;
        float ReportNameSize = 10;
        float ReportTextSize = 8;
        float ApplicationNameSize = 7;

        // Creates a PDF document
        Document document = null;
        if (LandScape == true)
        {
          
            document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
        }
        else
        {
            document = new Document(PageSize.A4, 0, 0, 15, 5);
        }

      
        iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

        // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
        mainTable.HeaderRows = 4;

        // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
        iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);

       
        Phrase phApplicationName = new Phrase("Sample Application", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

      
        PdfPCell clApplicationName = new PdfPCell(phApplicationName);
      
        clApplicationName.Border = PdfPCell.NO_BORDER;
       
        clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

     
        Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

        // Creates a PdfPCell which accepts the date phrase as a parameter.
        PdfPCell clDate = new PdfPCell(phDate);
        // Sets the Horizontal Alignment of the PdfPCell to right.
        clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
        // Sets the border of the cell to zero.
        clDate.Border = PdfPCell.NO_BORDER;

        // Adds the cell which holds the application name to the headerTable.
        headerTable.AddCell(clApplicationName);
        // Adds the cell which holds the date to the headerTable.
        headerTable.AddCell(clDate);
      
        headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;
       
        PdfPCell cellHeader = new PdfPCell(headerTable);
        cellHeader.Border = PdfPCell.NO_BORDER;
        // Sets the column span of the header cell to noOfColumns.
        cellHeader.Colspan = noOfColumns;
        // Adds the above header cell to the table.
        mainTable.AddCell(cellHeader);

        // Creates a phrase which holds the file name.
        Phrase phHeader = new Phrase("Sample Export", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
        PdfPCell clHeader = new PdfPCell(phHeader);
        clHeader.Colspan = noOfColumns;
        clHeader.Border = PdfPCell.NO_BORDER;
        clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
        mainTable.AddCell(clHeader);

        // Creates a phrase for a new line.
        Phrase phSpace = new Phrase("\n");
        PdfPCell clSpace = new PdfPCell(phSpace);
        clSpace.Border = PdfPCell.NO_BORDER;
        clSpace.Colspan = noOfColumns;
        mainTable.AddCell(clSpace);

        // Sets the gridview column names as table headers.
        for (int i = 0; i < noOfColumns; i++)
        {
            Phrase ph = null;

            if (gvReport.AutoGenerateColumns)
            {
                ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
            }
            else
            {
                ph = new Phrase(gvReport.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));               
            }

            mainTable.AddCell(ph);
        }

        // Reads the gridview rows and adds them to the mainTable
        for (int rowNo = 0; rowNo < noOfRows; rowNo++)
        {
            for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
            {
                if (gvReport.AutoGenerateColumns)
                {
                    string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                    Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                    mainTable.AddCell(ph);
                }
                else
                {
                    if (gvReport.Columns[columnNo] is TemplateField)
                    {
                        DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
                        string s = lc.Text.Trim();
                        Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                        mainTable.AddCell(ph);
                    }
                    else
                    {
                        string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                        Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                        mainTable.AddCell(ph);
                    }                   
                }
            }
           
            // Tells the mainTable to complete the row even if any cell is left incomplete.
            mainTable.CompleteRow();
        }

        // Gets the instance of the document created and writes it to the output stream of the Response object.
        PdfWriter.GetInstance(document, Response.OutputStream);

        // Creates a footer for the PDF document.
        HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
        pdfFooter.Alignment = Element.ALIGN_CENTER;
        pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;

      
        document.Footer = pdfFooter;
   
        document.Open();
                document.Add(mainTable);
        // Closes the document.
        document.Close();

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename= mypdf.pdf");
        Response.End();
    }
}