Monday, December 14, 2009

How To fill PDF form field using ITextSharp

<%@ 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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    <asp:Button ID="Button1" runat="server" Text="Fill Pdf" OnClick="Button1_Click" />
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text.pdf;
using System.IO;

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

    }
    private void fillForm()
    {
        string formFile = Server.MapPath(@"Old\e.pdf");
        string newFile = Server.MapPath(@"New\e.pdf");
        PdfReader reader = new PdfReader(formFile);
        PdfStamper stamper = new PdfStamper(reader, new FileStream(
                    newFile, FileMode.Create));
        AcroFields fields = stamper.AcroFields;

        PdfContentByte d = new PdfContentByte(stamper.Writer);

        // set form fields
        fields.SetField("name", "[NAME_TEXT]");
        fields.SetField("msg", "[YOUR_MESSAGE]");
        stamper.FormFlattening = false;
        stamper.Close();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        fillForm();
    }
}

Thursday, December 10, 2009

How To Render the content of webcontrol as html

aspdotnetcodebook
<%@ Page Language="C#" ValidateRequest="false" EnableEventValidation="false" 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>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <table>
           <tr>
               <td>
                   <asp:GridView ID="grdDemo" runat="server">
                   </asp:GridView>
               </td>
               <td>
                   <asp:DropDownList ID="ddlDemo" runat="server">
                       <asp:ListItem Text="Cat1" Value="1"></asp:ListItem>
                       <asp:ListItem Text="Cat1" Value="1"></asp:ListItem>
                       <asp:ListItem Text="Cat1" Value="1"></asp:ListItem>
                   </asp:DropDownList>
               </td>
               <td>
                   <asp:Table ID="tblDemo" runat="server">
                       <asp:TableRow>
                           <asp:TableCell Text="Demo1" ID="tc1"></asp:TableCell>
                           <asp:TableCell Text="Demo1" ID="TableCell1"></asp:TableCell>
                       </asp:TableRow>
                   </asp:Table>
               </td>
           </tr>
       </table>
   </div>
   <div>
       <asp:Button ID="btnTable" runat="server" Text="Table Control" OnClick="btnTable_Click" />
       <asp:Button ID="btnGridView" runat="server" Text="GridView Control" OnClick="btnGridView_Click" />
       <asp:Button ID="btnDDl" runat="server" Text="Drop Down List" OnClick="btnDDl_Click" />
   </div>
   <asp:TextBox ID="TextBox1" runat="server" Height="262px" TextMode="MultiLine" Width="441px"></asp:TextBox>
   </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       if (!Page.IsPostBack)
       {
           grdDemo.DataSource = new Category().GetCategories();
           grdDemo.DataBind();
       }
   }
   private string ConvertControlToHTML(Control source)
   {
       StringWriter sw = new StringWriter();
       HtmlTextWriter htw = new HtmlTextWriter(sw);
       source.RenderControl(htw);
       return sw.ToString();
   }
   protected void btnGridView_Click(object sender, EventArgs e)
   {
       TextBox1.Text = ConvertControlToHTML(grdDemo);
   }
   public override void VerifyRenderingInServerForm(Control control)
   {
       //base.VerifyRenderingInServerForm(control);
   }
   protected void btnDDl_Click(object sender, EventArgs e)
   {
       TextBox1.Text = ConvertControlToHTML(ddlDemo);
   }
   protected void btnTable_Click(object sender, EventArgs e)
   {
       TextBox1.Text = ConvertControlToHTML(tblDemo);
   }
}
public class Category
{
   public int ID { get; set; }
   public string Name { get; set; }
   public List<Category> GetCategories()
   {
       List<Category> lists = new List<Category>();
       for (int i = 1; i <= 10; i++)
       {
           lists.Add(new Category { ID = i, Name = "Category" + i.ToString() });

       }

       return lists;

   }
}

Tuesday, November 17, 2009

How To Create TextBox Dynamically using Jquery t and Read Control Value In Code Behind

<%@ 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 src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnOfficial").click(function() {
                var hdValue = $("#theValue");
                var num = ($("#theValue").val() - 1) + 2;
                hdValue.val(num);
                var newDiv = $(document.createElement('div')).attr("id", 'my' + num + 'Div');
                newDiv.after().html('<input type="text"  name="TextBox' + num + '" value="TextBox' + num + '" >');
                newDiv.appendTo("#Div1");

            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="Div1">
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <input type="button" id="btnOfficial" value="Add Another TextBox" />
    <input type="hidden" value="1" id="theValue" runat="server" />
    <asp:Button ID="btnSave" runat="server" Text="Read" OnClick="btnSave_Click" />
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

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


    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        List<string> alForm = new List<string>();
        //Textbox id is started
        // with 2 like(TextBox2,TextBox3.....
        for (int i = 2; i < Request.Form.Count - 2; i++)
        {
            string strId = "TextBox" + i.ToString();
            string strValue = Request.Form[strId].ToString();
            alForm.Add(strValue);
            strValue = "";


        }
        //Uncomment this line and test.
        //foreach (string x in Request.Form)
        //{

        //   string strValue = Request.Form[x].ToString();
        //  alForm.Add(strValue);

        //}
        GridView1.DataSource = alForm;
        GridView1.DataBind();
    }
}

Sunday, November 15, 2009

Dynamic Drag’n Drop With jQuery And ASP.NET

Photobucket In thi post i will show how to drag’n drop & saving the new positions to the database. Here is, how it is done by using jQuery & jQuery UI:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default2" %>

<!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 src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

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

   <script type="text/javascript">
       $(document).ready(function() {
           $("#contentLeft ul").sortable({ opacity: 0.6, cursor: 'move', update: function() {
               var order = $(this).sortable("toArray");
               $.ajax(
                   {
                       type: "POST",
                       url: "Default.aspx/Update",
                       data: "{'NewOrder': '" + order + "'}",
                       dataType: "json",
                       contentType: "application/json"

                   });
           }

           });

       });   
   </script>

   <style type="text/css">
       .itemStyle
       {
           background-color: #c0c0c0;
           font-family: Verdana;
           list-style: none;
       }
       .alter
       {
           background-color: #000fff;
           font-family: Verdana;
           list-style: none;
       }
       .contentLeft
       {
           height: 100%;
           width: 300px;
           overflow: auto;
       }
   </style>
</head>
<body>
   <form id="form1" runat="server">
   <div id="contentLeft" class="contentLeft">
       <asp:Repeater ID="rptLan" runat="server">
           <HeaderTemplate>
               <ul>
           </HeaderTemplate>
           <ItemTemplate>
               <li id="<%#Eval("ID")%>" class="itemStyle">
                   <%#Eval("Name")%></li>
           </ItemTemplate>
           <AlternatingItemTemplate>
               <li id="<%#Eval("ID")%>" class="alter">
                   <%#Eval("Name")%></li>
           </AlternatingItemTemplate>
           <FooterTemplate>
               </ul>
           </FooterTemplate>
       </asp:Repeater>
   </div>
   <div id="divRight">
   </div>
   </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;

public partial class Default2 : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       DemoDataContext db = new DemoDataContext();
       var query = from c in db.demos
                   orderby c.Order
                   select c;
       rptLan.DataSource = query;
       rptLan.DataBind();

   }
   /// <summary>
   /// Page Method for updating order
   /// </summary>
   /// <param name="NewOrder"></param>
   [System.Web.Services.WebMethod]
   public static void Update(string NewOrder)
   {
       DemoDataContext db = new DemoDataContext();
       int listingCounter = 1;
       foreach (var item in NewOrder.Split(','))
       {
           demo demo = db.demos.Single(x => x.ID == int.Parse(item.ToString()));
           demo.Order = listingCounter;
           db.SubmitChanges();
           listingCounter++;

       }
   }
}
{{Download}}

Wednesday, November 11, 2009

How To Use Jquery Google Chart In asp.net

In this post i will show how to add Jquery Google Chart in asp.net. Click Here to download Jquery Google Chart Plugin
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Chart.aspx.cs" Inherits="Chart" %>

<!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>jQuery Google Chart Demo</title>

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

    <script src="jgcharts.pack.js" type="text/javascript"></script>

    <link href="Style/style.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnCreate").click(function() {
                $("#bar_chart").html("");
                var api = new jGCharts.Api();
                var opt =
            {
                data: eval($("[id$='hdValue']").val()),
                axis_labels: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
                legend: ['X', 'Y'],
                size: '600x335',
                type: $("[id$='ddlType']").val(),
                bg: $("[id$='ddlColor']").val(),
                bar_width: 15
            };
                jQuery('<img>').attr('src', api.make(opt)).appendTo("#bar_chart");
            });
        });
    </script>

    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="dform" runat="server">
    <div class="right">
        <h4>
            Demo Chart</h4>
        <div id="bar_chart">
        </div>
        <div id="bar_chart_data">
        </div>
    </div>
    <div class="left">
        <asp:HiddenField ID="hdValue" runat="server" />
        <asp:GridView ID="gvChart" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="X" HeaderText="X" />
                <asp:BoundField DataField="Y" HeaderText="Y" />
            </Columns>
        </asp:GridView>
    </div>
    <table style="width: 50%; margin-top: 40%;">
        <tr>
            <td>
                Chart Type
            </td>
            <td>
                <asp:DropDownList ID="ddlType" runat="server">
                    <asp:ListItem Value="stripes">Stripes</asp:ListItem>
                    <asp:ListItem Value="p">Pie</asp:ListItem>
                    <asp:ListItem Value="p3">Pie3D</asp:ListItem>
                    <asp:ListItem Value="lc">Line</asp:ListItem>
                    <asp:ListItem Value="bhs">Stacked Bar</asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td>
                Background Color
            </td>
            <td>
                <asp:DropDownList ID="ddlColor" runat="server">
                    <asp:ListItem Text="Red" Value="FF0000"></asp:ListItem>
                    <asp:ListItem Text="Light Blue" Value="0000FF"></asp:ListItem>
                    <asp:ListItem Text="Light Purple" Value="FF0080"></asp:ListItem>
                    <asp:ListItem Text="Light Gray" Value="C0C0C0"></asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <input type="button" id="btnCreate" value="Create" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Chart : System.Web.UI.Page
{
    private DataTable GetSampleData()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("X");
        dt.Columns.Add("Y");
        dt.Rows.Add("1000", "3003.55");
        dt.Rows.Add("1000", "72.65");
        dt.Rows.Add("1000", "760.89");
        dt.Rows.Add("1000", "354.55");
        dt.Rows.Add("1000", "180.52");
        dt.Rows.Add("1000", "408.54");
        return dt;

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = GetSampleData();
        gvChart.DataSource = dt;
        gvChart.DataBind();

        ArrayList chartData = new ArrayList();
        foreach (DataRow dr in dt.Rows)
        {
            chartData.Add(String.Format("[{0}, {1}]", dr[0], dr[1].ToString().Replace("-", "")));
        }

        //Convert .NET Array to JS Array
        string ReturnValue = String.Empty;
        for (int i = 0; i < chartData.Count; i++)
        {
            ReturnValue += chartData[i];
            if (i != chartData.Count - 1)
                ReturnValue += ",";
        }

        //Data is returned in the following format: 
        //[[X, Y]

        hdValue.Value = String.Format("[{0}]", ReturnValue);

    }
}
{{download}}

Saturday, November 7, 2009

How to use Generic Delegate in C#


Action<T>:Encapsulates a method that takes a single parameter and does not return a value.
Action<T1,T2>:Encapsulates a method that has two parameters and does not return a value.
Action<T1,T2,T3>:Encapsulates a method that has three and does not return a value.
Action<T1,T2,T3,T4>:Encapsulates a method that has four and does not return a value.


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

namespace GenericDelegate
{
 class Program
 {
     static void Main(string[] args)
     {
         //Action<T>
         Action print = s => Console.WriteLine(s);
         string message = "Hello World";
         print(message);

         //Action<T1,T2>
         Action add = (x, y) => Console.WriteLine(x+y);
         add(1, 2);
       


     }
 }
}


Thursday, November 5, 2009

How To Add Jquery Plugin Tablesorter in Gridview

<%@ 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 src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script src="Scripts/Jquery.tablesorter.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#grdStudent").tablesorter();
        }
        ); 
    
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdStudent" runat="server" UseAccessibleHeader="true">
        </asp:GridView>
    </div>
    </form>
</body>
</html>
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)
    {
        if (!IsPostBack)
        {
            grdStudent.DataSource = new Student().GetAll();
            grdStudent.DataBind();
            MakeAccessible(grdStudent);
        }

    }

    private void MakeAccessible(GridView grid)
    {
        if (grid.Rows.Count > 0)
        {
            //This replaces <td> with <th> and adds the scope attribute
            grid.UseAccessibleHeader = true;

            //This will add the <thead> and <tbody> elements
            grid.HeaderRow.TableSection = TableRowSection.TableHeader;

            //This adds the <tfoot> element. Remove if you don't have a footer row
            grid.FooterRow.TableSection = TableRowSection.TableFooter;
        }
    }
}
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public List<Student> GetAll()
    {
        List<Student> list = new List<Student>()
        {
            new Student{FirstName="S001",LastName="L01",Age=21},
            new Student{FirstName="S002",LastName="L21",Age=31},
            new Student{FirstName="S003",LastName="L341",Age=51},
            new Student{FirstName="S004",LastName="L021",Age=51},
            new Student{FirstName="S005",LastName="L0231",Age=45},
            new Student{FirstName="S006",LastName="L0231",Age=26},
            new Student{FirstName="S007",LastName="L021",Age=14},
            new Student{FirstName="S008",LastName="L5401",Age=21},
            new Student{FirstName="S009",LastName="L231",Age=21},
            new Student{FirstName="S009",LastName="L0231",Age=21},
            new Student{FirstName="S011",LastName="L0231",Age=21},

        };

        return list;
    }

}
Before using this code read this article How To Make GridView Control Accessible {{Download}}

Cascading Dropdownlist using JQuery and WebService

<%@ 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 src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

  <script type="text/javascript">
      $().ready(function() {
          $.ajax({
              type: "POST",
              url: "WebService.asmx/GetStates",
              data: "{}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function(msg) {
                  BindStateddl(msg.d)
              }
          });
          //Fetch related city
          $("#ddlStates").change(function() {
              var StateID = $("#ddlStates > option[@selected]").attr("value");
              $("#ddlCities").html("");
              $.ajax({
                  type: "POST",
                  url: "WebService.asmx/FindCityByID",
                  data: "{ID:'" + StateID + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(msg) {
                      BindCityddl(msg.d)
                  }
              });
          });
      });
      function BindStateddl(msg) {
          $.each(msg, function() {

              $("#ddlStates").append($("<option></option>").val(this['StateId']).html(this['Name']));

          });
      }
      function BindCityddl(msg) {
          $.each(msg, function() {

              $("#ddlCities").append($("<option></option>").val(this['CityID']).html(this['Name']));

          });
      }
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <table>
          <tr>
              <td>
                  State
              </td>
              <td>
                  <asp:DropDownList ID="ddlStates" runat="server">
                      <asp:ListItem Value="0">Select</asp:ListItem>
                  </asp:DropDownList>
              </td>
          </tr>
          <tr>
              <td>
                  Cities
              </td>
              <td>
                  <select id="ddlCities" runat="server">
                  </select>
              </td>
          </tr>
      </table>
  </div>
  </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

  /// <summary>
  /// Filter city by StateID
  /// </summary>
  /// <param name="ID"></param>
  /// <returns></returns>
  [WebMethod]
  public List<Cities> FindCityByID(string ID)
  {
      return GetCities().FindAll(x => x.StateId == int.Parse(ID));

  }
  /// <summary>
  /// Return list of cities.
  /// </summary>
  /// <returns></returns>
  public List<Cities> GetCities()
  {
      List<Cities> cities = new List<Cities>()
          {
              new Cities{CityID=1,StateId=1,Name="Lucknow"},
              new Cities{CityID=2,StateId=1,Name="Allahabad"},
              new Cities{CityID=3,StateId=2,Name="Patiala"},
              new Cities{CityID=4,StateId=2,Name="Amritsar"},
              new Cities{CityID=5,StateId=3,Name="Shimla"},
         
          };
      return cities;
  }


  /// <summary>
  /// Return List of states
  /// </summary>
  /// <returns></returns>
  [WebMethod]
  public List<State> GetStates()
  {

      List<State> states = new List<State>()
          {
              new State{StateId=1,Name="UP"},
              new State{StateId=2,Name="Punjab"},
              new State{StateId=3,Name="Himachal"}
          };
      return states;

  }
  /// <summary>
  /// 
  /// </summary>
  public class State
  {
      public int StateId { get; set; }
      public string Name { get; set; }
  }
  /// <summary>
  /// 
  /// </summary>
  public class Cities
  {
      public int CityID { get; set; }
      public int StateId { get; set; }
      public string Name { get; set; }
  }

}

Download

Wednesday, November 4, 2009

How To display Image using Linq To Sql




Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._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>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:GridView ID="grdCategories" runat="server" DataKeyNames="CategoryID" Width="600px"
           AutoGenerateColumns="false">
           <Columns>
               <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
               <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
               <asp:TemplateField>
                   <ItemTemplate>
                       <asp:Image ID="Image1" runat="server" ImageUrl='<%#"ImageHandler.ashx?CategoryID="+ Eval("CategoryID")  %>' />
                   </ItemTemplate>
               </asp:TemplateField>
           </Columns>
       </asp:GridView>
   </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;

namespace WebApplication1
{
   public partial class _Default : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {
           NorthwindDataContext db = new NorthwindDataContext();
           var cate = from c in db.Categories
                      select new
                      {
                          CategoryName = c.CategoryName,
                          CategoryID = c.CategoryID,
                          Image = c.Picture,
                      };
           grdCategories.DataSource = cate;
           grdCategories.DataBind();
       }
   }
}
ImageHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing.Imaging;

namespace WebApplication1
{

   public class ImageHandler : IHttpHandler
   {

       public void ProcessRequest(HttpContext context)
       {
           HttpRequest req = context.Request;
           // string categoryID = "1";
           string categoryID = req.QueryString["CategoryID"].ToString();
           // Get information about the specified category
           NorthwindDataContext db = new NorthwindDataContext();
           var category = from c in db.Categories
                          where Convert.ToInt32(c.CategoryID) == Convert.ToInt32(categoryID)
                          select c.Picture;
           int len = category.First().Length;
           // Output the binary data
           // But first we need to strip out the OLE header
           int OleHeaderLength = 78;
           int strippedImageLength = len - OleHeaderLength;
           byte[] imagdata = new byte[strippedImageLength];
           Array.Copy(category.First().ToArray(), OleHeaderLength, imagdata, 0, strippedImageLength);
           if ((imagdata) != null)
           {
               MemoryStream m = new MemoryStream(imagdata);
               System.Drawing.Image image = System.Drawing.Image.FromStream(m);
               image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
           }
       }

       public bool IsReusable
       {
           get
           {
               return false;
           }
       }
   }
}

CSV Parser

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

namespace CSVProvider
{
    class Program
    {
        static void Main(string[] args)
        {
            CSVProvider csv = new CSVProvider(@"C:\Student.txt");
            foreach (var item in csv.OfType())
            {
                Console.WriteLine(item.ToString());
            }
            Console.ReadLine();
        }
    }

    public class Student
    {
        public int ID { get; set; }
        public string FullName { get; set; }
        public int Age { get; set; }
        public override string ToString()
        {
            return string.Format(@"ID={0}  FullNam={1} Age={2}", ID, FullName, Age);
        }

    }
    public class CSVProvider : IDisposable, IEnumerable, IEnumerator
    {
        private string fileName = default(string);
        FileStream fsObject = null;
        StreamReader readerObject = null;
        private string currentLine = default(string);
        public CSVProvider(string fileName)
        {
            this.fileName = fileName;
            fsObject = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            readerObject = new StreamReader(fsObject);
            //To skip header line
            readerObject.ReadLine();
        }

        public void Dispose()
        {
            if (readerObject != null)
                readerObject.Close();
            if (fsObject != null)
                fsObject.Close();
        }

        public IEnumerator GetEnumerator()
        {
            return this;
        }
        public object Current
        {
            get
            {
                string[] split = currentLine.Split(',');
                return new Student
                {
                    ID = int.Parse(split[0]),
                    FullName = split[1],
                    Age = int.Parse(split[2])


                };

            }
        }

        public bool MoveNext()
        {
            currentLine = readerObject.ReadLine();
            return currentLine != null;
        }

        public void Reset()
        {
            this.currentLine = default(string);
        }

    }
}

Tuesday, November 3, 2009

How To Use Web Service Behavior in an ASP.NET Page To Invoke the Web service

If you are using Microsoft IE 5 or later, you can use the behavior/HTML-Component "WebService" to access a Web service. The "WebService" behavior communicates with Web services over HTTP using Simple Object Access Protocol (SOAP).To use the "WebService" behavior, you must attach it to an element using the STYLE attribute. How To Use Web Service Behavior in an ASP.NET Page To Invoke the Web service The first step in using the Web service behavior in a Web page is embedding it using syntax similar to this:
<div id="service" style="BEHAVIOR:url(webservice.htc)"></div>
The above code relies on the behavior functionality built into IE 5 (and higher) to identify the location of the JavaScript file that will be used to call Web services. As discussed previously, the webservice.htc file should be available on the same folder as that of the Web page. It is important to note that the loading of the behavior file occurs on the client rather than on the server.Once embedded, the behavior can be invoked and linked to a WSDL 1.1-compliant Web service using JavaScript code. This is accomplished by referencing the embedded behavior id (service in the previous code) and calling its useService method:
service.useService("http://localhost/TestService/Service.asmx?WSDL","test");
You invoke the useService method in the onload event handler for the page to ensure that the Web service is mapped before any methods are invoked on the Web service. The useService method accepts the following arguments. * Path to the WSDL file for the Web service * A friendly name that can be later used to reference the Web service. This name will be used each time the web methods in the EmployeeService.asmx file are called using the behavior. Service.asmx

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service()
    {


    }
    [WebMethod]
    public string HelloWorld(string strUserName)
    {
        return "Hello " + strUserName;
    }

}
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 id="Head1" runat="server">
    <title>Untitled Page</title>

    <script type="text/javascript">
        function init() {
            service.useService("http://localhost/TestService/Service.asmx?WSDL", "test");

        }
        function tst() {
            iCallID = service.test.callService("HelloWorld", "santosh");

        }
        function onmyresult() {

            service.innerHTML = "Result : " + event.result.value;
        }
    </script>

</head>
<body onload="init();">
    <form id="form1" runat="server">
    <button onclick="javascript:tst()" id="Button1">
        Call Add Web Method</button>
    <div id="service" style="behavior: url(webservice.htc)" onresult="onmyresult();">
    </div>
    </form>
</body>
</html>

Monday, November 2, 2009

Event Bubbling in asp.net

UCBubble.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UCBubble.ascx.cs" Inherits="UCBubble" %>
<fieldset>
    <legend>
        <label for="TextBox1">
            Enter Text and Press Tab</label>
        <asp:TextBox ID="TextBox1" runat="server" />
        <label for="ddlColor">
            Select Color</label>
        <asp:DropDownList AutoPostBack="true" ID="ddlColor" runat="server">
            <asp:ListItem Text="Red" Value="Red"></asp:ListItem>
            <asp:ListItem Text="Green" Value="Green"></asp:ListItem>
        </asp:DropDownList>
    </legend>
</fieldset>
UCBubble.ascx.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 UCBubble : System.Web.UI.UserControl
{
    public string SelectedIndex
    {
        get { return this.ddlColor.SelectedItem.Value; }
        set
        {
            this.ddlColor.SelectedItem.Value = value;
        }


    }
    public string Text
    {
        get { return this.TextBox1.Text; }
        set { this.TextBox1.Text = value; }
    }

    public bool AutoPostBack
    {
        get { return TextBox1.AutoPostBack; }
        set { TextBox1.AutoPostBack = value; }
    }

  

    protected override void OnInit(EventArgs e)
    {
        this.ddlColor.SelectedIndexChanged += new EventHandler(ddlColor_SelectedIndexChanged);
        this.TextBox1.TextChanged += new EventHandler(TextBox1_TextChanged);
        base.OnInit(e);
    }

    void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
    {
        OnBubbleSelectedIndexChange(e);
    }

    void TextBox1_TextChanged(object sender, EventArgs e)
    {
        OnBubbleTextChanged(e);
    }
    public event EventHandler BubbleIndexChanged;
    public event EventHandler BubbleTextChanged;
    public void OnBubbleSelectedIndexChange(EventArgs e)
    {
        if (BubbleIndexChanged != null)
            BubbleIndexChanged(this, e);
    }

    protected void OnBubbleTextChanged(EventArgs e)
    {
        if (BubbleTextChanged != null)
            BubbleTextChanged(this, e);

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

<%@ Register Src="UCBubble.ascx" TagName="UCBubble" TagPrefix="uc1" %>
<!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 id="myBody" runat="server">
    <form id="form1" runat="server">
    <div>
    </div>
    <uc1:UCBubble ID="UCBubble1" runat="server" AutoPostBack="true" runat="server" OnBubbleIndexChanged="ChangeBgColor"
        OnBubbleTextChanged="OnTextChanged" />
    </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 OnTextChanged(object sender, EventArgs e)
    {
        Response.Write(this.UCBubble1.Text);
    }


    protected void ChangeBgColor(object sender, EventArgs e)
    {
       myBody.Attributes.Add("bgcolor", UCBubble1.SelectedIndex);
    }
}
Download Code

Wednesday, October 28, 2009

How to prevent users from running more than one instance of our program.

By using Mutex object you can prevent users from running more than one instance of the application. Check out this code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SingleInstacle
{
    public class Program
    {
        static void Main(string[] args)
        {
            bool createdNew = false;
            Mutex mutex = new Mutex(true, "SingleInstance", out createdNew);

            if (createdNew)
            {
                Console.WriteLine("Hello world");

            }
            else
            {
                Console.WriteLine("You can only run a single instance of this app!");
            }
            Console.ReadLine();
        }
    }
}

Tuesday, October 27, 2009

Microsoft Ajax Client Template

<%@ 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>Ajax Client Side Template</title>

    <script src="Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>

    <script src="Scripts/MicrosoftAjaxTemplates.debug.js" type="text/javascript"></script>

    <script src="Scripts/MicrosoftAjaxAdoNet.debug.js" type="text/javascript"></script>

    <style type="text/css">
        .sys-template
        {
            display: none;
        }
    </style>

    <script type="text/javascript">
        function LoadData() {
            $create(Sys.UI.DataView, {
                dataProvider: "Service.svc",
                fetchOperation: "GetData",
                autoFetch: "true"
            }, {}, {}, $get("tblProduct"));
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <input type="button" id="btnFetch" value="Display Data" onclick="LoadData();" />
    <table id="tblProduct" class="sys-template" border="1">
        <tr>
            <td>
                {{ProductID}}
            </td>
            <td>
                {{ProductName}}
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Collections.Generic;
[DataContract]
public class Product
{
    [DataMember]
    public string ProductName;
    [DataMember]
    public int ProductID;
}
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
    // Add [WebGet] attribute to use HTTP GET
    [OperationContract]
    public List<Product> GetData()
    {
        List<Product> ret = new List<Product>();

        for (int i = 0; i < 10; i++)
        {
            ret.Add(new Product {ProductName = "Product " + i.ToString(), ProductID = i });
        }
        return ret;
    }

    
}
download