Tuesday, September 30, 2008

Get a copy of dll in GAC (or) add Reference to a dll in GAC

Sometimes in .net application we need to have a copy of a dll which is available in GAC. But when we view the GAC through C:\Windows\assembly folder or Runà assembly it will show like this

Using this we cannot copy the dll. Only uninstall option is available.

To view the available dll using the naked eye follow the steps

Dot net have a dll file Shfusion.dll which is a Assembly Cache Viewer (Shfusion.dll) is a Windows shell extension that allows you to view and manipulate the contents of the global assembly cache using Windows Explorer. Shfusion.dll is located in the <Windows Folder>\Microsoft.NET\Framework\vx.x.xxxx folder, where x.x.xxxx is the version and build number of the .NET Framework you are using.

  1. uninstall the dll using the following command in the run dialog box.

regsvr32 -u C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\shfusion.dll

  1. Now type assembly in the Run dialog box.
  2. Now you will see the folder view of the GAC. copy the dll you want

To get back to the previous state of view register the Shfusion dll using the following command

regsvr32 C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\shfusion.dll

Tutorial Reading A Text File Using LINQ

Tutorial Reading A Text File Using LINQ

Posted using ShareThis

LINQ To SQL Tutorial

LINQ To SQL Tutorial

Posted using ShareThis

Monday, September 29, 2008

Friday, September 26, 2008

C# The process cannot access the file because it is being used by another process

This error message is mostly comes up, when you try to access a file which is opened by another process. You may open an image file in one of your form in a picturebox with using ImageFromFile or something. I mostly use memorystream to open an image. After read it in byte[] write it into a stream and close it.

You can check whether a file is being used or not with a simple function.

Try to open a file with none share.

 public bool IsFileUsedbyAnotherProcess(string filename)
    {
        try
        {

            File.Open(filename), FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (System.IO.IOException exp)
        {
            return true;
        }
        return false;
    }

This function will return true if the file because it is being used by another process or not.

Wednesday, September 17, 2008

Enumeration and Iterators

An enumerator is a read-only, forward-only cursor over a sequence of values. An enumerator is an object that either:

  • Implements IEnumerator or IEnumerator

  • Has a method named MoveNext for iterating the sequence, and a property called Current for getting the current element in the sequence

The foreach statement iterates over an enumerable object. An enumerable object is the logical representation of a sequence, and is not itself a cursor, but an object that produces cursors over itself. An enumerable object either:

  • Implements IEnumerable or IEnumerable

  • Has a method named GetEnumerator that returns an enumerator

Iterators

An iterator is a method, property, or indexer that contains one or more yield statements. An iterator must return one of the following four interfaces (otherwise, the compiler will generate an error):

 // Enumerable interfaces
 System.Collections.IEnumerable
 System.Collections.Generic.IEnumerable

 // Enumerator interfaces
 System.Collections.IEnumerator
 System.Collections.Generic.IEnumerator

Iterators that return an enumerator interface tend to be used less often. They're useful when writing a custom collection class: typically, you name the iterator GetEnumerator and have your class implement IEnumerable.

Iterators that return an enumerable interface are more common—and simpler to use because you don't have to write a collection class. The compiler, behind the scenes, writes a private class implementing IEnumerable (as well as IEnumerator).

foreach statement is a consumer of an enumerator, an iterator is a producer of an enumerator. In this example, we use an iterator to return a sequence of Fibonacci numbers (where each number is the sum of the previous two):
using System;
using System.Collections.Generic;

class Test
{
  static void Main()
  {
      foreach (int fib in Fibs(6))
          Console.Write(fib + " ");
      Console.Read();
  }

  static IEnumerable<int> Fibs(int fibCount)
  {
      int prevFib = 1;
      int curFib = 1;
      for (int i = 0; i < fibCount; i++)
      {
       
          int newFib = prevFib + curFib;
          prevFib = curFib;
          curFib = newFib;
          yield return prevFib;
      }
  }
}


Whereas a return statement expresses "Here's the value you asked me to return from this method," a yield return statement expresses "Here's the next element you asked me to yield from this enumerator." On each yield statement, control is returned to the caller, but the callee's state is maintained so that the method can continue executing as soon as the caller enumerates the next element. The lifetime of this state is bound to the enumerator, such that the state can be released when the caller has finished enumerating.


How To Avoid conflicts in C#

If you really want to use an identifier that clashes with a keyword, you can qualify it with the @ prefix. For instance:
 class class  {...}    // illegal
 class @class {...}    // legal
The @ symbol doesn't form part of the identifier itself, so @myVariable is the same as myVariable. check out this example
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication7
{
   class Program
   {
       static void Main(string[] args)
       {
           int @int = 10;
           double @double = 10.121;
           float @float = (float)(@int + @double);
           Console.WriteLine(@float.ToString());
           Console.Read();

       }
   }
}

Changing ASP.net Temporary Files Folder

Edit the Global web.config (placed at %Windows Install Folder%Microsoft.NET\Frame
work\v2.0.50727\CONFIG). add the new full folder path in the Compilation section of the configuration file. <compilation tempDirectory="E:\New Location\"  debug="false">

Tuesday, September 16, 2008

How To Pass multiple values to CommandArgument

In this post i will show you that how you can pass the multiple valuesCommandArgument ...
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultipleCommandArgument.aspx.cs"
   Inherits="MultipleCommandArgument" %>

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
               <Columns>
                   <asp:BoundField DataField="carid" HeaderText="Card Id" />
                   <asp:BoundField DataField="Year" HeaderText="year" />
                   <asp:TemplateField>
                       <ItemTemplate>
                           <asp:Button ID="btnTest" runat="Server" CommandName="Test" Text="Select" CommandArgument='<%#Eval("carid") + ","+Eval("year") %>' />
                       </ItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
           <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
           <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

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

            GridView1.DataSource = GetData();
            GridView1.DataBind();
        }
      

    }
  
    DataTable data;
    DataTable GetData()
    {
        data = Session["data"] as DataTable;
        if (data != null)
        {
            return data;
        }
        data = new DataTable();
        DataColumn primaryColumn
        = new DataColumn("carid", typeof(Int32));
        data.Columns.Add(primaryColumn);
        data.Columns.Add(new DataColumn("year", typeof(Int32)));
        data.Columns.Add(new DataColumn("make", typeof(string)));
        data.Columns.Add(new DataColumn("model", typeof(string)));
        DataRow dr;
        dr = data.NewRow();
        dr[0] = 1;
        dr[1] = 1998;
        dr[2] = "Isuzu";
        dr[3] = "Trooper";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 2;
        dr[1] = 2000;
        dr[2] = "Honda";
        dr[3] = "Civic";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 3;
        dr[1] = 2000;
        dr[2] = "BMW";
        dr[3] = "GM";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 4;
        dr[1] = 2000;
        dr[2] = "Swift";
        dr[3] = "Tata";
        data.Rows.Add(dr);
        DataColumn[] primaryColumns = new DataColumn[1];
        primaryColumns[0] = primaryColumn;
        data.PrimaryKey = primaryColumns;
        Session["data"] = data;
        return data;
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Test")
        {
            string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });

       Label1.Text= commandArgs[0];
       Label2.Text = commandArgs[1];

        }
    }
}



Tuesday, September 9, 2008

How To Pass Value from database to google map( javascript function)

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

<!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">
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>Google Maps JavaScript API Example</title>

 <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAjQ5pL86XOoQ41VopETg1BxRfqogRWDFFWKC2bFG72235ZrnYERRoUjFELdorAiLMorc8KixeuNcskQ"
     type="text/javascript"></script>

 <script type="text/javascript">

 //<![CDATA[

 function load() {
   if (GBrowserIsCompatible()) {
   var lat = document.getElementById("lat").value;
   var lon = document.getElementById("lon").value;
   var map = new GMap2(document.getElementById("map"));
   map.setCenter(new GLatLng(lat,lon), 13);
   }
 }

 //]]>
 </script>

</head>
<body onload="load()" onunload="GUnload()">
 <form id="form1" runat="server">
 <div>
     <div id="map" style="width: 500px; height: 300px">
     </div>
 </div>
 </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
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 System.Xml.Linq;

public partial class GoogleMap : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {   string lat = "37.4419";
     string lon = "-122.1419";

     Page.ClientScript.RegisterHiddenField("lat", lat);
     Page.ClientScript.RegisterHiddenField("lon", lon);

 }
}

Monday, September 8, 2008

How To Add Design Time Support to Custom Controls

In this post i will show how to create custom control and also how to add design time support . When inheriting from the WebControl class, you must override the Render method to provide the desired output. The following is a code sample of LogoControl that contains a property for the LogoUrl and the CompanyName:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.Design;
using System.Drawing;
using System.ComponentModel;

namespace CustomControl
{
 [Designer("CustomControl.LogoControlDesigner, CustomControl")]
 [ToolboxData(@"<{0}:LogoControl runat=""server"" CompanyName="" "" LogoUrl="" "" />")]
 public class LogoControl : WebControl
 {
     public LogoControl()
     {
     }
     public string LogoUrl
     {
         get { return _logoUrl; }
         set { _logoUrl = value; }
     }
     private string _logoUrl;
     public string CompanyName
     {
         get { return _companyName; }
         set { _companyName = value; }
     }
     private string _companyName;
     protected override void Render(HtmlTextWriter writer)
     {
         writer.WriteFullBeginTag("div");
         writer.Write(@"<img src=""{0}"" /><br />", LogoUrl);
         writer.Write(CompanyName + "<br />");
         writer.WriteEndTag("div");
     }
 }
}
  • The ToolboxBitmapAttribute class is located in the System.Drawing namespace in the System.Drawing.dll assembly. The following code snippet shows the ToolboxBitmap being set to a .bmp file that is configured to be an embedded resource. (When you use the ToolBoxBitmapAttribute, the Attribute suffix is optional.)
  • You can also change the namespace prefix that is assigned by the Web page designer by assigning the TagPrefixAttribute to the assembly that contains your custom control. The following snippet shows the namespace prefix being changed to “mcl” for the controls in the Customcontrol project
[assembly: TagPrefix("LogoControl", "mcl")]
Now we add custom designer for our that is used to render the control when in design mode by adding a reference to the System.Design.dll assembly and creating a class that inherits from the ControlDesigner class. This can be beneficial when the normal rendering of the control may not be visible due to code that needs to run to populate specific properties. For example, you may want to provide a custom designer for the LogoControl that provides a default rendering when the LogoUrl property has not been set, as shown in the following code sample:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.Design;
using System.Drawing;
using System.ComponentModel;

namespace CustomControl
{
   class LogoControlDesigner : System.Web.UI.Design.ControlDesigner
   {
       private LogoControl _logoControl;
       public override string GetDesignTimeHtml()
       {
           if (_logoControl.LogoUrl.Trim().Length == 0)
           {
               return "<div id=\'mcl1\' "
               +
               "style=\'background-color:red;border-width:2px;\' >"
               +
               "<center>LogoControl</center><br />"
               +
               "<center>Please set LogoUrl property.</center><br />"
               + "</div>";
           }
           else
           {
               return base.GetDesignTimeHtml();
           }
       }
       public override void Initialize(IComponent component)
       {
           _logoControl = (LogoControl)component;
           base.Initialize(component);
           return;
       }
   }
}

How To Add calendar control inside a GridView

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

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False">
               <Columns>
                   <asp:BoundField DataField="Title" HeaderText="Title" />
                   <asp:TemplateField HeaderText="Year">
                       <ItemTemplate>
                           <asp:TextBox ID="text1" runat="server"></asp:TextBox>
                           <asp:Calendar ID="Cal1" runat="Server" OnSelectionChanged="Cal1_SelectionChanged"></asp:Calendar>
                       </ItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

public partial class CalInsideGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetCustomMadeDataTable();
            GridView1.DataBind();
        }

    }
    public DataTable GetCustomMadeDataTable()
    {
        //Create a new DataTable object
        System.Data.DataTable objDataTable = new System.Data.DataTable();
        //Create three columns with string as their type
        objDataTable.Columns.Add("ISBN", typeof(string));
        objDataTable.Columns.Add("Title", typeof(string));
        objDataTable.Columns.Add("Publisher", typeof(string));
        objDataTable.Columns.Add("Year", typeof(string));
        DataColumn[] dcPk = new DataColumn[1];
        dcPk[0] = objDataTable.Columns["ISBN"];
        objDataTable.PrimaryKey = dcPk;
        objDataTable.Columns["ISBN"].AutoIncrement = true;
        objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
        //Adding some data in the rows of this DataTable
        DataRow dr;
        for (int i = 1; i <= 10; i++)
        {
            dr = objDataTable.NewRow();
            dr[1] = "Title" + i.ToString();
            dr[2] = "Publisher" + i.ToString();
            dr[3] = "12/12/200" + i.ToString();
            objDataTable.Rows.Add(dr);
        }
        Session["strTemp"] = objDataTable;
        return objDataTable;
    }
    protected void Cal1_SelectionChanged(object sender, EventArgs e)
    {
        Calendar cal = (Calendar)sender;
        TextBox text1 = (TextBox)((GridViewRow)cal.Parent.Parent).FindControl("text1");

        text1.Text = cal.SelectedDate.ToShortDateString();
    }
}

How To Encrypt Connection Strings ?

The connectionStrings element can be encrypted by running the Visual Studio 2005 Command Prompt, executing the following command, and specifying the full path to your Web site folder: aspnet_regiis -pef "connectionStrings" "C:\...\EncryptWebSite" Note that the –pef switch requires you to pass the physical Web site path, which is the last parameter. Be sure to verify the path to your Web.config file. The encrypted Web.config file will look like the following:

Sunday, September 7, 2008

How To Create a schedule using asp.net Calendar Control

Many people think that the Calendar control is only used as a date picker control, but the Calendar control can also be used to display a schedule. The trick to using the Calendar control to display scheduled items and special days is to make the control large enough to display text in each day, and then add Label controls (or other controls) to the Cell object’s Controls collection in the DayRender event handler. The following example shows how a Calendar control can be used as a schedule display showing special days. In this example, a Web page was created and a Calendar control was added to the page. The following code was added to the code-behind page to show how the Calendar control’s properties can be set programmatically and the Calendar control events can be used.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Calender2.aspx.cs" Inherits="Calender2" %>

<!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>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
     <div>
         <asp:Calendar ID="Calendar1" runat="server" OnDayRender="Calendar1_DayRender" OnPreRender="Calendar1_PreRender"
             OnSelectionChanged="Calendar1_SelectionChanged1" OnVisibleMonthChanged="Calendar1_VisibleMonthChanged1">
         </asp:Calendar>
     </div>
 </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

public partial class Calender2 : System.Web.UI.Page
{
  Hashtable schedule = new Hashtable();
  protected void Page_Load(object sender, EventArgs e)
  {
      GetSchedule();
      Calendar1.Style.Add("position", "absolute");
      Calendar1.Style.Add("left", "5px");
      Calendar1.Style.Add("top", "50px");
      Calendar1.Caption = "Special Days";
      Calendar1.FirstDayOfWeek = FirstDayOfWeek.Sunday;
      Calendar1.NextPrevFormat = NextPrevFormat.ShortMonth;
      Calendar1.TitleFormat = TitleFormat.MonthYear;
      Calendar1.ShowGridLines = true;
      Calendar1.DayStyle.HorizontalAlign = HorizontalAlign.Left;
      Calendar1.DayStyle.VerticalAlign = VerticalAlign.Top;
      Calendar1.DayStyle.Height = new Unit(75);
      Calendar1.DayStyle.Width = new Unit(100);
      Calendar1.OtherMonthDayStyle.BackColor =
      System.Drawing.Color.WhiteSmoke;
      Calendar1.TodaysDate = new DateTime(2008, 12, 1);
      Calendar1.VisibleDate = Calendar1.TodaysDate;
  }
  private void GetSchedule()
  {
      schedule["11/23/2008"] = "Thanksgiving";
      schedule["12/5/2008"] = "Birthday";
      schedule["12/16/2008"] = "First day of Chanukah";
      schedule["12/23/2008"] = "Last day of Chanukah";
      schedule["12/24/2008"] = "Christmas Eve";
      schedule["12/25/2008"] = "Christmas";
      schedule["12/26/2008"] = "Boxing Day";
      schedule["12/31/2008"] = "New Year's Eve";
      schedule["1/1/2009"] = "New Year's Day";
  }



  protected void Calendar1_PreRender(object sender, EventArgs e)
  {

  }
  protected void Calendar1_VisibleMonthChanged1(object sender, MonthChangedEventArgs e)
  {
      Response.Write("Month changed to: " + e.NewDate.ToShortDateString());
  }
  protected void Calendar1_SelectionChanged1(object sender, EventArgs e)
  {
      Response.Write("Selection changed to: "
      + Calendar1.SelectedDate.ToShortDateString());
  }
  protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
  {
      Literal lit = new Literal();
      lit.Visible = true;
      lit.Text = "<br />";
      e.Cell.Controls.Add(lit);
      if (schedule[e.Day.Date.ToShortDateString()] != null)
      {
          Label lbl = new Label();
          lbl.Visible = true;
          lbl.Text = (string)schedule[e.Day.Date.ToShortDateString()];
          e.Cell.Controls.Add(lbl);
      }
  }
}

Friday, September 5, 2008

How To Export GridView to Excel

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

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan"
               BorderWidth="1px" CellPadding="2" Font-Names="Tahoma" ForeColor="Black" GridLines="None"
               Width="300px"  AutoGenerateColumns="False">
               <FooterStyle BackColor="Tan" />
               <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
               <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
               <HeaderStyle BackColor="Tan" Font-Bold="True" />
               <AlternatingRowStyle BackColor="PaleGoldenrod" />
               <Columns>
                   <asp:BoundField DataField="Id" Visible="False" />
                   <asp:BoundField DataField="Name" HeaderText="Name">
                       <HeaderStyle HorizontalAlign="Left" />
                   </asp:BoundField>
                   <asp:BoundField DataField="Description" HeaderText="Description">
                       <HeaderStyle HorizontalAlign="Left" />
                   </asp:BoundField>
               </Columns>
           </asp:GridView>
           <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" /></div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 System.Collections.Generic;
using System.IO;

public partial class ExportToExcel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BuildUserList();

        }

    }
    private void BuildUserList()
    {
        IList<User> users = new List<User>();
        users.Add(new User("Xyz", "Coder"));
        users.Add(new User("Abc", "Writer"));
        users.Add(new User("Charles", "Poet"));

        // assign users to GridView
        GridView1.DataSource = users;
        GridView1.DataBind();
    }
    public class User
    {

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="name"></param>
        /// <param name="description"></param>
        public User(string name, string description)
        {
            _name = name;
            _description = description;
            _id = Guid.NewGuid().ToString();
        }

        private string _id;

        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private string _description;

        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        StringWriter stringWrite = new System.IO.StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {

        // Confirms that an HtmlForm control is rendered for the
        //specified ASP.NET server control at run time.
        //for more details check out this link
        //http://msdn.microsoft.com/en-us/library/system.web.ui.page.verifyrenderinginserverform.aspx

        GridView grid = control as GridView;
        if (grid != null && grid.ID == "GridView1")
            return;
        else
            base.VerifyRenderingInServerForm(control);
    }
}

HowTo: Display a radiobuttonlist with images


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

<!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>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
      <div>
          <asp:RadioButtonList ID="rdoI" runat="Server">
          </asp:RadioButtonList>
      </div>
  </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

public partial class RadioListImage : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       string[] strImages = System.IO.Directory.GetFiles(Server.MapPath("~/img"));

       foreach (string strImage in strImages)
       {
           this.rdoI.Items.Add(new ListItem(String.Format("<img src='{0}'>", strImage.ToString()), strImage.ToString()));
       }
   }
}

How To Access Gridview row information inside RowCommand

In .net 1.1, the GridCommandEventArgs used to give access to the row that triggered the command. In .net 2.0, it isn't as obvious as that. Fritz posted an excellent discussion on the matter, and i'm just posting his 2-line solution here for reference. If your button is a ButtonField, then you can access the index of the item via e.CommandArgument. This may be enough information to do whatever you need. If your button is a LinkButton in a TemplateField, you have to add the CommandArgument as an attribute to the LinkButton: CommandArgument='<%# Eval("id") %>'

Then in the code behind for RowCommand, you can use the following syntax:

string id = (string)e.CommandArgument;

Compiling Asp.Net 2.0 to a single assembly

I wanted to install my web application assembly into the GAC, but this is made more complicated by the multitude of assemblies produced by VS when i publish the web site. On the newsgroups, i found some talk of a tool called Merge_Aspnet.exe but i couldn't find it anywhere. Eventually i found it as a download on MSDN, it is bundled as part of the Web Deployment Projects. You install it, and then right-click your project in VS and you should see a new menu item "Add Web Deployment Project". I am baffled as to why they didn't just add a new project type in the list of projects under "Deployment". There is a link to "Search online templates" so i think it should really be available there. but it looks like MS did a hack just to add in a new item to the project context menu. but it works... so i'll stop complaining.

Thursday, September 4, 2008

GridView Javascript Click Row and Webservice

This post shows 2 common tasks with the ASP.NET GridView: Binding a List (generic) of objects as DataSource and on clicking a row, getting the values of the selected row by a javascript function. In the example a List with User-objects is displayed. On clicking a row containing the data of a User-object, the Id of the object is used to get the address of the user by an Ajax-call and display it in a details-field.

Binding objects to a GridView in ASP.NET is a well supported feature. You need to add the objects you like to bind to a Collection like an IList<> and assign the list as datasource to the GridView. The mechanism of binding works by reading out the properties of the bound objects. Each property of your object maps to a column in the GridView.

So binding and displaying your data isn't very hard. A little more tricky is the procedure to refer to your data in a client-script. There are some use-cases where you need this, for example when you want to get some detail-information that correspond to the selected row, but don't want to reload the page for that. In our sample-project we get the address of the selected user by executing a Webservice-call and display the information in a DIV-element.

Binding the List

First we define a User and Address-object for binding to a GridView:(in App_Code Folder)

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;

/// <summary>
/// User
/// </summary>
public class User
{

/// <summary>
/// ctor
/// </summary>
/// <param name="name"></param>
/// <param name="description"></param>
public User(string name, string description)
{
   _name = name;
   _description = description;
   _id = Guid.NewGuid().ToString();
}

private string _id;

public string Id
{
   get { return _id; }
   set { _id = value; }
}

private string _name;

public string Name
{
   get { return _name; }
   set { _name = value; }
}
private string _description;

public string Description
{
   get { return _description; }
   set { _description = value; }
}
}

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;

/// <summary>
/// Summary description for Address
/// </summary>
public class Address
{
public Address(string street, string location, string zipCode)
{
    _street = street;
    _location = location;
    _zipCode = zipCode;
}

private string _street;
public string Street
{
    get { return _street; }
    set { _street = value; }
}

private string _location;
public string Location
{
    get { return _location; }
    set { _location = value; }
}

private string _zipCode;
public string ZipCode
{
    get { return _zipCode; }
    set { _zipCode = value; }
}

public override string ToString()
{
    string result = "";

    result += "Street: " + _street + "<BR/>";
    result += "Location: " + _location + "<BR/>";
    result += "ZipCode: " + _zipCode + "<BR/>";


    return result;
}


}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageMethods.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>GridView, javascript and Webservice</title>

 <script type="text/javascript">
       /**
              * a user has been clicked
              * @param userId id of the user
              * Now we defined that whenever a DataRow is clicked,
              * the javascript-function CallMyWebService is called. 
              * And here is the function in the head of the aspx-page:
              */
      function CallMyWebService( userId)
     {

       PageMethods.GetAddressForUser(userId, OnRequestComplete);
     }
   function OnRequestComplete(result)
      {
        document.getElementById('addressBox').innerHTML = result;
     }
 </script>

</head>
<body style="font-family: Tahoma">
 <form id="frmMain" runat="server">
     <asp:ScriptManager ID="ScriptManger1" runat="Server" EnablePageMethods="true">
     </asp:ScriptManager>
     <div>
         <h1>
             GridView, javascript and Ajax</h1>
         <span style="font-size: 10pt"><strong>Users:</strong></span><br />
         <asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan"
             BorderWidth="1px" CellPadding="2" Font-Names="Tahoma" ForeColor="Black" GridLines="None"
             Width="300px" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False">
             <FooterStyle BackColor="Tan" />
             <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
             <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
             <HeaderStyle BackColor="Tan" Font-Bold="True" />
             <AlternatingRowStyle BackColor="PaleGoldenrod" />
             <Columns>
                 <asp:BoundField DataField="Id" Visible="False" />
                 <asp:BoundField DataField="Name" HeaderText="Name">
                     <HeaderStyle HorizontalAlign="Left" />
                 </asp:BoundField>
                 <asp:BoundField DataField="Description" HeaderText="Description">
                     <HeaderStyle HorizontalAlign="Left" />
                 </asp:BoundField>
             </Columns>
         </asp:GridView>
         <br />
         <span style="font-size: 10pt"><strong>User's address:</strong></span><br />
         <div style="width: 300px; height: 80px; background-color: Beige">
             <div style="margin: 5px 5px 5px 5px" id="addressBox">
             </div>
         </div>
     </div>
 </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 System.Collections.Generic;

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


      if (!Page.IsPostBack)
      {
          BuildUserList();
      }
  }

  private void BuildUserList()
  {
      IList<User> users = new List<User>();
      users.Add(new User("Xyz", "Coder"));
      users.Add(new User("Abc", "Writer"));
      users.Add(new User("Charles", "Poet"));

      // assign users to GridView
      GridView1.DataSource = users;
      GridView1.DataBind();


      // Store some sampledata
      Dictionary<string, Address> addresses = new Dictionary<string, Address>();
      addresses.Add(users[0].Id, new Address("Teststreet", "Stuttgart", "83840"));
      addresses.Add(users[1].Id, new Address("India", "Delhi", "23455"));
      addresses.Add(users[2].Id, new Address("Abc", "Bangalore", "34566"));

      Session["Addresses"] = addresses;

  }

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
          User selUser = e.Row.DataItem as User;
          e.Row.Attributes.Add("onclick", "CallMyWebService('" + selUser.Id + "')");
      }
  }

  [System.Web.Services.WebMethod]
  [System.Web.Script.Services.ScriptMethod]
  public static string GetAddressForUser(string userId)
  {
      Dictionary<string, Address> addresses = HttpContext.Current.Session["Addresses"] as Dictionary<string, Address>;

      Address address = addresses[userId];
      return address.ToString();
  }
}

Using Event Delegates in the controls nested within a GridView

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

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <table>
               <tr>
                   <td style="height: 194px">
                       <h3>
                           Using Event Delegates in the controls nested within a GridView</h3>
                       <p>
                           In this sample I use event delegates to process an event triggered by a child control
                           within a gridview</p>
                       <table>
                           <tr>
                               <td runat="server" id="tdDG3">
                               </td>
                               <td runat="server" id="tdStatus" width="400">
                               </td>
                           </tr>
                           <tr>
                               <td colspan="2">
                                   Column Number
                                   <asp:TextBox ID="txtColNo" runat="server" Text="1" MaxLength="1" Width="20"></asp:TextBox>
                                   <asp:RegularExpressionValidator ID="valRegExp" runat="server" ErrorMessage="Invalid Column Number"
                                       ControlToValidate="txtColNo" ValidationExpression="[1-2]" Display="Dynamic"></asp:RegularExpressionValidator>
                                   <asp:Button ID="btnHideDisplay" Text="Toggle the visiblity of the specified column"
                                       runat="server" OnClick="ChangeVisibility"></asp:Button>
                               </td>
                           </tr>
                       </table>
                   </td>
               </tr>
           </table>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

public partial class GridViewCustomEvent : System.Web.UI.Page
{
    protected CustomControls.CustomGridView dg;
    private void Page_Load(object sender, System.EventArgs e)
    {
        dg = new CustomControls.CustomGridView();
        dg.AutoGenerateColumns = false;
        dg.CssClass = "GridStyle2";
        dg.HeaderStyle.CssClass = "DataGrid1HeaderStyle";
        dg.DataSource = CreateDS().Tables["PersonData"];
        dg.DataBind();
        dg.Columns[0].ItemStyle.CssClass = "Col1Item";
        dg.Columns[2].ItemStyle.CssClass = "Col3Item";
        dg.Columns[3].ItemStyle.CssClass = "Col2Item";

        tdDG3.Controls.Add(dg);
        dg.chkBoxChanged += new CustomControls.CheckBoxChangedEventHandler(this.CheckBox_Clicked);
        dg.ddlIndexChanged += new CustomControls.ddlIndexChangedEventHandler(this.ddlIndex_Changed);

    }
    protected void ChangeVisibility(object sender, EventArgs e)
    {
        if (txtColNo.Text != "1" && txtColNo.Text != "2")
        {
            tdStatus.InnerHtml = "Invalid Column Number";
        }
        else
        {
            int iIndex = Convert.ToInt16(txtColNo.Text);
            dg.Columns[iIndex].Visible = !dg.Columns[iIndex].Visible;
        }
    }
    private void CheckBox_Clicked(object sender, CustomControls.CustomGV_Event_Args e)
    {

        if (((CheckBox)sender).Checked)
        {
            e.dgrow.Cells[e.SelectedCell].BackColor = System.Drawing.Color.Gainsboro;
            tdStatus.InnerHtml += "<br>You selected row " + e.dgrow.RowIndex + " and column " + e.SelectedCell;
        }
        else
        {
            e.dgrow.Cells[e.SelectedCell].BackColor = System.Drawing.Color.Ivory;
            tdStatus.InnerHtml += "<br><font color=red>You unselected row " + e.dgrow.RowIndex + " and column " + e.SelectedCell + "</font>";
        }
    }
    private void ddlIndex_Changed(object sender, CustomControls.CustomGV_Event_Args e)
    {
        tdStatus.InnerHtml += "<br>You selected " + ((DropDownList)sender).SelectedValue + "  at row " + e.dgrow.RowIndex + " and column " + e.SelectedCell;

    }
    private DataSet CreateDS()
    {
        DataSet ds = new DataSet();
        if (Session["dsEvents"] == null)
        {
            DataTable dt = new DataTable("PersonData");
            DataRow dr;
            dt.Columns.Add(new DataColumn("Person_ID", typeof(Int32)));
            dt.Columns.Add(new DataColumn("PersonName", typeof(string)));
            dt.Columns.Add(new DataColumn("Company", typeof(string)));
            for (int i = 1; i < 10; i++)
            {
                dr = dt.NewRow();
                dr[0] = i;
                dr[1] = "Person " + i;
                dr[2] = "Company " + i;
                dt.Rows.Add(dr);
            }
            DataColumn parentCol;
            parentCol = dt.Columns["Person_ID"];

            ds.Tables.Add(dt);
            DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            PrimaryKeyColumns[0] = dt.Columns["Person_Id"];
            dt.PrimaryKey = PrimaryKeyColumns;

            dt = new DataTable("Orders");
            dt.Columns.Add(new DataColumn("PrimaryKey", typeof(Int32)));
            dt.Columns.Add(new DataColumn("ForeignKey", typeof(Int32)));
            dt.Columns.Add(new DataColumn("Order", typeof(string)));
            for (int i = 1; i < 60; i++)
            {
                dr = dt.NewRow();
                dr[0] = i;
                dr[1] = 1 + i % 9;
                dr[2] = "Order # " + i;
                dt.Rows.Add(dr);
            }
            ds.Tables.Add(dt);

            DataColumn childCol;
            childCol = dt.Columns["ForeignKey"];
            DataRelation relation1;
            relation1 = new DataRelation("CustomersOrders", parentCol, childCol);
            // Add the relation to the DataSet.
            ds.Relations.Add(relation1);

            Session["dsEvents"] = ds;
        }
        else
        {
            ds = (DataSet)Session["dsEvents"];
        }
        return ds;

    }

}

namespace CustomControls
{
  
    public delegate void CheckBoxChangedEventHandler(object sender, CustomGV_Event_Args e);
    public delegate void ddlIndexChangedEventHandler(object sender, CustomGV_Event_Args e);
    public enum GVListItemType
    {
        Item = 0,
        AlternatingItem = 1,
        EditItem = 2,
        DropDownListItem = 3,
        CheckBoxListItem = 4,
        Footer = 6,
        Header = 7

    }
    public class GridViewTemplate : ITemplate
    {
        GVListItemType templateType;
        string columnName;

        public GridViewTemplate(GVListItemType type, string colname)
        {
            templateType = type;
            columnName = colname;
        }

        public void InstantiateIn(System.Web.UI.Control container)
        {
            switch (templateType)
            {
                case GVListItemType.Header:
                    Literal lc = new Literal();
                    lc.Text = "<B>" + columnName + "</B>";
                    container.Controls.Add(lc);
                    break;
                case GVListItemType.CheckBoxListItem:
                    CheckBox chkBox = new CheckBox();
                    container.Controls.Add(chkBox);
                    chkBox.DataBinding += new EventHandler(chkbox_DataBinding);

                    Label lbl = new Label();
                    container.Controls.Add(lbl);
                    lbl.DataBinding += new EventHandler(label_DataBinding);
                    break;
                case GVListItemType.DropDownListItem:
                    DropDownList ddl = new DropDownList();
                    container.Controls.Add(ddl);
                    ddl.DataTextField = columnName;
                    ddl.DataValueField = columnName;
                    ddl.DataBinding += new EventHandler(ddl_DataBinding);
                    ddl.AutoPostBack = true;
                    break;

            }
        }
        private void ddl_DataBinding(object sender, System.EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            GridViewRow container;
            container = ddl.NamingContainer as GridViewRow;
            ddl.DataSource = ((DataRowView)container.DataItem).CreateChildView("CustomersOrders");
            ddl.SelectedIndexChanged += new EventHandler(((CustomGridView)ddl.NamingContainer.NamingContainer).DropDownList_Command);


        }
        private void chkbox_DataBinding(object sender, System.EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            GridViewRow container;
            container = chk.NamingContainer as GridViewRow;

            chk.AutoPostBack = true;
            chk.CheckedChanged += new EventHandler(((CustomGridView)chk.NamingContainer.NamingContainer).CheckBox_Command);

        }

        private void label_DataBinding(object sender, System.EventArgs e)
        {
            Label lbl = (Label)sender;
            GridViewRow container;
            container = lbl.NamingContainer as GridViewRow;
            lbl.Text = DataBinder.Eval(container.DataItem, columnName) as string;
        }
    }

    public class CustomGV_Event_Args : EventArgs
    {
        private GridViewRow dataViewItem;
        private int selectedCell;
        public int SelectedCell
        {
            get
            {
                return selectedCell;
            }
        }
        public GridViewRow dgrow
        {
            get
            {
                return dataViewItem;
            }
        }
        public CustomGV_Event_Args(object sender)
        {
            string uniqueID = null;

            if (sender is CheckBox)
            {

                dataViewItem = ((CheckBox)sender).NamingContainer as GridViewRow;
                uniqueID = ((CheckBox)sender).UniqueID;

            }
            else if (sender is DropDownList)
            {
                dataViewItem = ((DropDownList)sender).NamingContainer as GridViewRow;
                uniqueID = ((DropDownList)sender).UniqueID;
            }
            for (int i = 0; i < dataViewItem.Cells.Count; i++)
            {
                if (dataViewItem.Cells[i].Controls.Count > 0)
                {
                    if (dataViewItem.Cells[i].Controls[0].UniqueID == uniqueID) selectedCell = i;
                }
            }

        }
    }


    [ToolboxData("<{0}:CustomGridView runat=server></{0}:CustomGridView>")]
    public class CustomGridView : System.Web.UI.WebControls.GridView
    {
        private BoundField bc;
      
        private TemplateField tc;

       
        public event CheckBoxChangedEventHandler chkBoxChanged;
        public event ddlIndexChangedEventHandler ddlIndexChanged;

        protected override void CreateChildControls()
        {

            bc = new BoundField();
           
            bc.DataField = "Person_ID";
            bc.HeaderText = "Person_ID";
            this.Columns.Add(bc);

            tc = new TemplateField();
            tc.HeaderTemplate = new GridViewTemplate(GVListItemType.Header, "PersonName");
            tc.ItemTemplate = new GridViewTemplate(GVListItemType.CheckBoxListItem, "PersonName");
            this.Columns.Add(tc);
            tc = new TemplateField();
            tc.HeaderTemplate = new GridViewTemplate(GVListItemType.Header, "Company");
            tc.ItemTemplate = new GridViewTemplate(GVListItemType.CheckBoxListItem, "Company");
            this.Columns.Add(tc);
            tc = new TemplateField();
            tc.HeaderTemplate = new GridViewTemplate(GVListItemType.Header, "Orders");
            tc.ItemTemplate = new GridViewTemplate(GVListItemType.DropDownListItem, "Order");
            this.Columns.Add(tc);
        }


        public void CheckBox_Command(Object sender, EventArgs e)
        {
            CustomGV_Event_Args ea = new CustomGV_Event_Args(sender);
            if (chkBoxChanged != null)
            {
                chkBoxChanged(sender, ea);
            }
        }
        public void DropDownList_Command(Object sender, EventArgs e)
        {
            CustomGV_Event_Args ea = new CustomGV_Event_Args(sender);
            if (ddlIndexChanged != null)
            {
                ddlIndexChanged(sender, ea);
            }

        }
    }
}