Implementing the IHttpHandler Interface : HTTP Handlers « Development « ASP.NET Tutorial

ASP.NET Tutorial
1. ASP.Net Instroduction
2. Language Basics
3. ASP.net Controls
4. HTML Controls
5. Page Lifecycle
6. Response
7. Collections
8. Validation
9. Development
10. File Directory
11. Sessions
12. Cookie
13. Cache
14. Custom Controls
15. Profile
16. Configuration
17. LINQ
18. ADO.net Database
19. Data Binding
20. Ajax
21. Authentication Authorization
22. I18N
23. Mobile
24. WebPart
25. XML
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
ASP.NET Tutorial » Development » HTTP Handlers 
9. 24. 4. Implementing the IHttpHandler Interface
File: App_Code\ImageHandler.cs

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace MyNamespace
{
    public class ImageHandler : IHttpHandler
    {
        const string connectionStringName = "Images";

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Buffer = false;
            string fileName = VirtualPathUtility.GetFileName(context.Request.Path);

            string conString = WebConfigurationManager.ConnectionStrings [connectionStringName].ConnectionString;
            SqlConnection con = new SqlConnection(conString);
            SqlCommand cmd = new SqlCommand("SELECT Image FROM Images WHERE FileName=@FileName", con);
            cmd.Parameters.AddWithValue("@fileName", fileName);
            using (con)
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior. SequentialAccess);
                if (reader.Read())
                {
                    int bufferSize = 8040;
                    byte[] chunk = new byte[bufferSize];
                    long retCount;
                    long startIndex = 0;
                    retCount = reader.GetBytes(0, startIndex, chunk, 0, bufferSize);
                    while (retCount == bufferSize)
                    {
                        context.Response.BinaryWrite(chunk);

                        startIndex += bufferSize;
                        retCount = reader.GetBytes(0, startIndex, chunk, 0, bufferSize);
                    }
                    byte[] actualChunk = new Byte[retCount - 1];
                    Buffer.BlockCopy(chunk, 0, actualChunk, 0(int)retCount - 1);
                    context.Response.BinaryWrite(actualChunk);
                }
            }

        }

        public bool IsReusable
        {
            get return true}
        }
    }
}

            


Register the class in the web configuration file. 
File: Web.Config

<configuration>
  <connectionStrings>
    <add name="Images"
      connectionString="Data Source=.\SQLExpress;Integrated
           Security=True;AttachDBFileName=|DataDirectory|ImagesDB.mdf;
           User Instance=True"/>
  </connectionStrings>
    <system.web>

      <httpHandlers>
        <add path="*.gif" verb="*"
           type="MyNamespace.ImageHandler" validate="false" />
        <add path="*.jpeg" verb="*"
           type="MyNamespace.ImageHandler" validate="false" />
        <add path="*.jpg" verb="*"
           type="MyNamespace.ImageHandler" validate="false" />
      </httpHandlers>

    </system.web>
</configuration>

Displaying images with the ImageHandler.

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (upFile.HasFile)
        {
                srcImages.Insert();
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Image Upload</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblFile"
        Text="Image File:"
        AssociatedControlID="upFile"
        Runat="server" />
    <asp:FileUpload
        id="upFile"
        Runat="server" />
    <asp:Button
        id="btnAdd"
        Text="Add Image"
        OnClick="btnAdd_Click"
        Runat="server" />
    <hr />

    <asp:GridView
        id="grdImages"        
        DataSourceID="srcImages"
        AutoGenerateColumns="false"
        ShowHeader="false"
        GridLines="None"
        Runat="server">
        <Columns>
        <asp:ImageField
            DataImageUrlField="FileName"
            DataAlternateTextField="FileName" />
        </Columns>
    </asp:GridView>

    <asp:SqlDataSource
        id="srcImages"
        ConnectionString="<%$ ConnectionStrings:Images %>"
        SelectCommand="SELECT FileName FROM Images"
        InsertCommand="INSERT Images (FileName,Image) VALUES (@FileName,@FileBytes)"
        Runat="server">
        <InsertParameters>
            <asp:ControlParameter Name="FileName" ControlID="upFile" PropertyName="FileName" />
            <asp:ControlParameter Name="FileBytes" ControlID="upFile" PropertyName="FileBytes" />
        </InsertParameters>
    </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>
9. 24. HTTP Handlers
9. 24. 1. Creating HTTP Handlers
9. 24. 2. Creating a Generic Handler
9. 24. 3. HelloWorld HttpHandler (VB)
9. 24. 4. Implementing the IHttpHandler Interface
9. 24. 5. RSS Handler
9. 24. 6. Creating a Custom HTTP Handler
9. 24. 7. Log user in HttpModule
9. 24. 8. Source viewer Http Handler
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.