Figures
© 2004 Microsoft Corporation. All rights reserved.
Figure 1 Date.aspx
<%@ Page Language="C#" %>

<html>
  <body>
    <h1>
      <% Response.Write (DateTime.Now.ToShortDateString ()); %>
    </h1>
  </body>
</html>
Figure 2 Global.asax
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Globalization" %>

<script language="C#" runat="server">
  void Application_BeginRequest (Object sender, EventArgs e)
  {
      try {
          if (Request.UserLanguages.Length > 0) {
              Thread.CurrentThread.CurrentCulture =
                  CultureInfo.CreateSpecificCulture
                  (Request.UserLanguages[0]);
          }
      }
      catch (ArgumentException) {
          // Do nothing if CreateSpecificCulture fails
      }
  }
</script>
Figure 5 Generating a Bitmap
public class ImageGen : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        // Create a bitmap that measures 128 pixels square
        Bitmap bitmap = new Bitmap (128, 128,
            PixelFormat.Format32bppArgb);

        // Create a Graphics object for drawing to the bitmap
        Graphics g = Graphics.FromImage (bitmap);

        // TODO: Use Graphics methods to draw the image

        // Set the response's content type to image/jpeg
        context.Response.ContentType = "image/jpeg";

        // Write the image to the HTTP response
        bitmap.Save (context.Response.OutputStream, ImageFormat.Jpeg);

        // Clean up before returning
        bitmap.Dispose ();
        g.Dispose ();
    }

    public bool IsReusable
    {
        // Returning true enables instances of this class to be
        // pooled and reused. Return false if ImageGen instances
        // should NOT be reused.
        get { return true; }
    }
}
Figure 6 PieChart.aspx
<html>
  <body>
    <form runat="server">
      <table width="100%">
        <tr>
          <td>
            <table cellpadding="8" bgcolor="gainsboro">
              <tr>
                <td>Q1</td>
                <td><asp:TextBox ID="Q1" RunAt="server" /></td>
              </tr>
              <tr>
                <td>Q2</td>
                <td><asp:TextBox ID="Q2" RunAt="server" /></td>
              </tr>
              <tr>
                <td>Q3</td>
                <td><asp:TextBox ID="Q3" RunAt="server" /></td>
              </tr>
              <tr>
                <td>Q4</td>
                <td><asp:TextBox ID="Q4" RunAt="server" /></td>
              </tr>
              <tr>
                <td></td>
                <td align="right">
                  <asp:Button Text="Show Chart" OnClick="OnShowChart"
                    RunAt="server" />
                </td>
              </tr>
            </table>
          </td>
          <td>
            <asp:Image ID="Chart" AlternateText="Pie Chart"
              RunAt="server" />
          </td>
        </tr>
      </table>
    </form>
  </body>
</html>

<script language="C#" runat="server">
  void OnShowChart (Object sender, EventArgs e)
  {
      Chart.ImageUrl = String.Format
          ("PieChart.ashx?q1={0}&q2={1}&q3={2}&q4={3}" +
           "&width=256&height=224", Q1.Text, Q3.Text, Q3.Text,
           Q4.Text);
  }
</script>
Figure 7 PieChart.ashx
<%@ WebHandler Language="C#" Class="PieChartGenerator" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;

public class PieChartGenerator : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        //
        // Extract input parameters from the query string
        //
        decimal[] vals = new decimal[4];
        vals[0] = Convert.ToDecimal (context.Request["q1"]);
        vals[1] = Convert.ToDecimal (context.Request["q2"]);
        vals[2] = Convert.ToDecimal (context.Request["q3"]);
        vals[3] = Convert.ToDecimal (context.Request["q4"]);
        int width = Convert.ToInt32 (context.Request["width"]);
        int height = Convert.ToInt32 (context.Request["height"]);

        //
        // Create a bitmap, draw a pie chart, and write it to the
        // response.
        //
        Bitmap bitmap = new Bitmap (width, height,
            PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage (bitmap);
        DrawPieChart (g, Color.White, vals, width, height);
        context.Response.ContentType = "image/gif";
        bitmap.Save (context.Response.OutputStream, ImageFormat.Gif);

        //
        // Clean up and return.
        //
        bitmap.Dispose ();
        g.Dispose ();
    }

    public bool IsReusable
    {
        get { return true; }
    }

    void DrawPieChart (Graphics g, Color bkgnd, decimal[] vals,
        int width, int height)
    {
        //
        // Erase the background.
        //
        SolidBrush br = new SolidBrush (bkgnd);
        g.FillRectangle (br, 0, 0, width, height);
        br.Dispose ();

        //
        // Create an array of brushes.
        //
        SolidBrush[] brushes = new SolidBrush[6];
        brushes[0] = new SolidBrush (Color.Red);
        brushes[1] = new SolidBrush (Color.Yellow);
        brushes[2] = new SolidBrush (Color.Blue);
        brushes[3] = new SolidBrush (Color.Cyan);
        brushes[4] = new SolidBrush (Color.Magenta);
        brushes[5] = new SolidBrush (Color.Green);

        //
        // Sum the inputs.
        //
        decimal total = 0.0m;
        foreach (decimal val in vals)
            total += val;

        //
        // Draw the chart.
        //
        float start = 0.0f;
        float end = 0.0f;
        decimal current = 0.0m;

        for (int i=0; i<vals.Length; i++) {
            current += vals[i];
            start = end;
            end = (float) (current / total) * 360.0f;
            g.FillPie (brushes[i % 6], 0.0f, 0.0f, width, height,
                start, end - start);
        }

        //
        // Clean up and return.
        //
        foreach (SolidBrush brush in brushes)
            brush.Dispose ();
    }
}
Figure 9 DumbQuotes.aspx
<%@ Import Namespace="System.IO" %>

<html>
  <body>
    <asp:Label ID="Output" RunAt="server" />
  </body>
</html>

<script language="C#" runat="server">
  void Page_Load (Object sender, EventArgs e)
  {
      ArrayList quotes = new ArrayList ();
      StreamReader reader = null;

      try {
          reader = new StreamReader (Server.MapPath ("Quotes.txt"));

          for (string line = reader.ReadLine (); line != null;
              line = reader.ReadLine ())
              quotes.Add (line);

          Random rand = new Random ();
          int index = rand.Next (0, quotes.Count - 1);
          Output.Text = (string) quotes[index];
      }
      finally {
          if (reader !=  null)
              reader.Close ();
      }
  }
</script>
Figure 11 SmartQuotes.aspx
<html>
  <body>
    <asp:Label ID="Output" RunAt="server" />
  </body>
</html>

<script language="C#" runat="server">
  void Page_Load (Object sender, EventArgs e)
  {
      ArrayList quotes = (ArrayList) Cache["Quotes"];

      if (quotes != null) {
          Random rand = new Random ();
          int index = rand.Next (0, quotes.Count - 1);
          Output.Text = (string) quotes[index];
      }
      else {
          // If quotes is null, this request arrived after the
          // ArrayList was removed from the cache and before a new
          // ArrayList was inserted. Tell the user the server is
          // busy; a page refresh should solve the problem.
          Output.Text = "Server busy";
      }
  }
</script>
Figure 12 Global.asax
<%@ Import NameSpace="System.IO" %>

<script language="C#" runat="server">
  static Cache _cache = null;
  static string _path = null;

  void Application_Start ()
  {
      _cache = Context.Cache;
      _path = Server.MapPath ("Quotes.txt");

      ArrayList quotes = ReadQuotes ();

      _cache.Insert ("Quotes", quotes, new CacheDependency (_path),
          Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
          CacheItemPriority.Default,
          new CacheItemRemovedCallback (RefreshQuotes));
  }

  static void RefreshQuotes (String key, Object item,
      CacheItemRemovedReason reason)
  {
      ArrayList quotes = ReadQuotes ();

      _cache.Insert ("Quotes", quotes, new CacheDependency (_path),
          Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
          CacheItemPriority.Default,
          new CacheItemRemovedCallback (RefreshQuotes));
  }

  static ArrayList ReadQuotes ()
  {
      ArrayList quotes = new ArrayList ();
      StreamReader reader = null;

      try {
          reader = new StreamReader (_path);
          for (string line = reader.ReadLine (); line != null;
              line = reader.ReadLine ())
              quotes.Add (line);
      }
      finally {
          if (reader != null)
              reader.Close ();
      }
      return quotes;
  }
</script>
Figure 13 ConfirmDelete.aspx
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>
  <body>
    <form runat="server">
      <asp:DataGrid ID="MyDataGrid"
        AutoGenerateColumns="false" CellPadding="2"
        BorderWidth="1" BorderColor="lightgray"
        Font-Name="Verdana" Font-Size="8pt"
        GridLines="vertical" Width="90%"
        OnItemCreated="OnAttachScript"
        OnItemCommand="OnDeleteRecord"
        RunAt="server">
        <Columns>
          <asp:ButtonColumn Text="Delete"
            HeaderStyle-HorizontalAlign="center"
            ItemStyle-HorizontalAlign="center"
            ButtonType="PushButton"
            CommandName="Delete" />
          <asp:BoundColumn HeaderText="Item ID"
            DataField="title_id" />
          <asp:BoundColumn HeaderText="Title"
            DataField="title" />
          <asp:BoundColumn HeaderText="Price"
            DataField="price" DataFormatString="{0:c}"
            HeaderStyle-HorizontalAlign="center"
            ItemStyle-HorizontalAlign="right" />
        </Columns>
        <HeaderStyle BackColor="teal" ForeColor="white"
          Font-Bold="true" />
        <ItemStyle BackColor="white" ForeColor="darkblue" />
        <AlternatingItemStyle BackColor="beige"
          ForeColor="darkblue" />
      </asp:DataGrid>
      <asp:Label ID="Output" RunAt="server" />
    </form>
  </body>
</html>

<script language="C#" runat="server">
  void Page_Load (Object sender, EventArgs e)
  {
      if (!IsPostBack) {
          SqlConnection connection = new SqlConnection
              ("server=localhost;database=pubs;uid=sa;pwd=");

          try {
              connection.Open (); 
              SqlCommand command = new SqlCommand
                  ("select * from titles where price != 0",
                  connection);
              SqlDataReader reader = command.ExecuteReader ();
              MyDataGrid.DataSource = reader;
              MyDataGrid.DataBind ();
          }
          finally {
              connection.Close ();
          }
      }
  }

  void OnAttachScript (Object sender, DataGridItemEventArgs e)
  {
      if (e.Item.ItemType == ListItemType.Item ||
          e.Item.ItemType == ListItemType.AlternatingItem) {
              WebControl button =
                  (WebControl) e.Item.Cells[0].Controls[0];
              button.Attributes.Add ("onclick",
                  "return confirm (\"Are you sure?\");");
      }
  }

  void OnDeleteRecord (Object sender, DataGridCommandEventArgs e)
  {
      if (e.CommandName == "Delete") {
          Output.Text = "Deleted \"" + e.Item.Cells[2].Text + "\"";
      }
  }
</script>
Figure 15 PowerGrid.aspx
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>
  <body>
    <form runat="server">
      <center>
        <asp:DataGrid RunAt="server"
          ID="PowerGrid" AutoGenerateColumns="false"
          BorderWidth="1" BorderColor="lightgray"
          CellPadding="2" CellSpacing="0"
          Font-Name="Verdana" Font-Size="8pt"
          GridLines="vertical" Width="90%"
          AllowPaging="true" AllowSorting="true"
          PageSize="16" OnPageIndexChanged="OnNewPage"
          OnSortCommand="OnSort">

          <Columns>
            <asp:BoundColumn
              HeaderText="ID"
              DataField="ProductID"
              HeaderStyle-HorizontalAlign="center"
              ItemStyle-HorizontalAlign="center"
              SortExpression="ProductID ASC" />
            <asp:BoundColumn
              HeaderText="Product Name"
              DataField="ProductName"
              HeaderStyle-HorizontalAlign="center"
              SortExpression="ProductName ASC"/>
            <asp:BoundColumn
              HeaderText="Price"
              DataField="UnitPrice"
              DataFormatString="{0:c}"
              HeaderStyle-HorizontalAlign="center"
              ItemStyle-HorizontalAlign="right"
              SortExpression="UnitPrice ASC" />
            <asp:BoundColumn
              HeaderText="Unit"
              DataField="QuantityPerUnit"
              HeaderStyle-HorizontalAlign="center"
              SortExpression="QuantityPerUnit ASC"/>
          </Columns>

          <HeaderStyle BackColor="teal" ForeColor="white"
            Font-Bold="true" />
          <ItemStyle BackColor="white" ForeColor="darkblue" />
          <AlternatingItemStyle BackColor="beige"
            ForeColor="darkblue" />
          <PagerStyle PrevPageText="Previous" NextPageText="Next" />
        </asp:DataGrid>
      </center>
    </form>
  </body>
</html>

<script language="C#" runat="server">
  string connstr = "server=localhost;database=northwind;uid=sa;pwd=";
  string query = "select * from products";

  void Page_Load (Object sender, EventArgs e)
  {
      if (!IsPostBack) {
          SqlDataAdapter adapter = new SqlDataAdapter (query, connstr);
          DataSet ds = new DataSet ();
          adapter.Fill (ds);
          PowerGrid.DataSource = ds.Tables[0].DefaultView;
          PowerGrid.DataBind ();
      }
  }

  void OnSort (Object sender, DataGridSortCommandEventArgs e) 
  {
      SqlDataAdapter adapter = new SqlDataAdapter (query, connstr);
      DataSet ds = new DataSet ();
      adapter.Fill (ds);

      DataView view = new DataView (ds.Tables[0]);
      view.Sort = e.SortExpression;
      ViewState["SortExpression"] = view.Sort;

      PowerGrid.DataSource = view;
      PowerGrid.DataBind ();
  }

  void OnNewPage (Object sender, DataGridPageChangedEventArgs e) 
  {
      PowerGrid.CurrentPageIndex = e.NewPageIndex;

      SqlDataAdapter adapter = new SqlDataAdapter (query, connstr);
      DataSet ds = new DataSet ();
      adapter.Fill (ds);

      DataView view = new DataView (ds.Tables[0]);
      string exp = (string) ViewState["SortExpression"];
      if (exp != null)
          view.Sort = exp;

      PowerGrid.DataSource = view;
      PowerGrid.DataBind ();
  }
</script>
Page view tracker