Popular Posts
Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Word break tag : <wbr/> (HTML5) The  HTML  <wbr>  tag  is  used  defines  a  potential  line  break  point  if  needed.  This  stands  for  Word  BReak. This  is  u... Build an OpenVPN server on android device Preparation An android device, in this case, Sony xperia Z is used Root permission required Linux Deploy for deploy i...
Blog Archive
Stats
Set certificate for ssl
Reference : http://blogs.sun.com/andreas/entry/no_more_unable_to_find
InstallCert.java
/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class InstallCert {

    public static void main(String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
            return;
        }

        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            char SEP = File.separatorChar;
            File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }
        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
        String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }

        X509Certificate cert = chain[k];
        String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);

        OutputStream out = new FileOutputStream("jssecacerts");
        ks.store(out, passphrase);
        out.close();

        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }

}
First, create the certificate file.
java InstallCert www.domain.com
After generate the certificate file, code below :
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
System.setProperty("javax.net.ssl.trustStore", certificate);  // certificate is the file path
System.setProperty("javax.net.ssl.trustStorePassword", "");
Binding with page member
Usually we'll bind controls with data, like SqlDataSource or XMLDataSource. But I found that I could bind member in a container, too. Now, It's convenient to me binding members withing a container for display some messages.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Binding with a member.aspx.cs"
    Inherits="Binding_with_a_member" %>

<!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>Binding with page member</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource1">
            <ItemTemplate>
                <div style="text-align: center; font-size: xx-large; color: Red;">
                    <asp:Label ID="Label1" runat="server" Text='<%# GUID %>'></asp:Label>
                </div>
                <div style="text-align: center; font-size: xx-large; color: Blue;">
                    <asp:Label ID="Label2" runat="server" Text='<%# RandomNumber %>'></asp:Label>
                </div>
                <div style="text-align: center; font-size: xx-large; color: Green;">
                    <asp:Label ID="Label3" runat="server" Text='<%# DateTime.Now %>'></asp:Label>
                </div>
            </ItemTemplate>
        </asp:FormView>
    </div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:brucedbConnectionString %>"
        SelectCommand="SELECT * FROM [GV]"></asp:SqlDataSource>
    </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 Binding_with_a_member : System.Web.UI.Page
{
    protected string GUID;
    protected int RandomNumber;
    protected void Page_Load(object sender, EventArgs e)
    {
        GUID = Guid.NewGuid().ToString();
        RandomNumber = new Random().Next(100, 10000);
    }
}
GridView mischief
There was a requirement for append a row after every data row in GridView. In begining I tried to get current row and want to append a new row after it. But it's hard to achieve this. And finally, I found a mischief way to append a new row and think : WHY CAN I HIT UPON TO GET IT?
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewMischief.aspx.cs"
    Inherits="GridViewMischief" %>

<!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>GridView mischief</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="mischiefGridView" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            DataKeyNames="ID" DataSourceID="mischief" CellPadding="4" ForeColor="#333333"
            GridLines="None" BorderWidth="0" Width="100%">
            <RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="編號" InsertVisible="False" ReadOnly="True"
                    SortExpression="ID" />
                <asp:BoundField DataField="UniqueID" HeaderText="序號" SortExpression="UniqueID" />
                <asp:BoundField DataField="Price" HeaderText="價格" SortExpression="Price" />
                <asp:BoundField DataField="Amount" HeaderText="數量" SortExpression="Amount" />
                <asp:BoundField DataField="CreateDate" HeaderText="日期" SortExpression="CreateDate" />
                <asp:CommandField ShowDeleteButton="True" HeaderText="刪除" />
                <asp:TemplateField ShowHeader="False" HeaderText="編輯">
                    <EditItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                            Text="更新"></asp:LinkButton>
                        &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                            Text="取消"></asp:LinkButton>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                            Text="編輯"></asp:LinkButton>
                        </td></tr>
                        <tr>
                            <td colspan="7">
                                <hr />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="#DCDCDC" />
        </asp:GridView>
        <asp:SqlDataSource ID="mischief" runat="server" ConnectionString="<%$ ConnectionStrings:brucedbConnectionString %>"
            SelectCommand="SELECT * FROM [GV]" DeleteCommand="DELETE FROM [GV] WHERE [ID] = @ID"
            InsertCommand="INSERT INTO [GV] ([UniqueID], [Price], [Amount], [CreateDate]) VALUES (@UniqueID, @Price, @Amount, @CreateDate)"
            UpdateCommand="UPDATE [GV] SET [UniqueID] = @UniqueID, [Price] = @Price, [Amount] = @Amount, [CreateDate] = @CreateDate WHERE [ID] = @ID">
            <DeleteParameters>
                <asp:Parameter Name="ID" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="UniqueID" Type="String" />
                <asp:Parameter Name="Price" Type="Int32" />
                <asp:Parameter Name="Amount" Type="Int32" />
                <asp:Parameter DbType="Date" Name="CreateDate" />
                <asp:Parameter Name="ID" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="UniqueID" Type="String" />
                <asp:Parameter Name="Price" Type="Int32" />
                <asp:Parameter Name="Amount" Type="Int32" />
                <asp:Parameter DbType="Date" Name="CreateDate" />
            </InsertParameters>
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>
Set Textbox value when TextMode set to Password
<asp:TextBox ID="tbPassword" runat="server" Columns="16" TextMode="Password"></asp:TextBox>
tbPassword.Attributes.Add("value", defaultTextValue);
Activate IIS GIZP compress
1. Set metabase editable for editing.

2. Add a new extension for gzip.

3. Edit the file c:\windows\system32\inetsrv\MetaBase.xml
Add file type for gzip at HcScriptFileExtensions attribute.
Set compress level at HcDynamicCompressionLevel attribute.

.net remoting
1. Create a new project RemotingInterface, and create a new Interface.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RemotingInterface
{
    /// <summary>
    /// Remoting object interface
    /// </summary>
    public interface IRemotingObj
    {
        string Log(string message);
    }
}
2. Create a new project RemotingServer, and create a remoting object for work.
using System;
using System.IO;
using System.Text;
using RemotingInterface;

namespace RemotingServer
{
    /// <summary>
    /// Remoting object
    /// </summary>
    class RemotingObject : MarshalByRefObject, IRemotingObj
    {
        private string _FilePath = @"C:\remoting.txt";
        /// <summary>
        /// Log object created infomation.
        /// </summary>
        public RemotingObject()
        {
            string strMsg = "Object created.";
            Console.WriteLine(strMsg);
            File.AppendAllText(
                _FilePath,
                string.Format("{0}{2}{1}{2}", DateTime.Now, strMsg, Environment.NewLine),
                Encoding.UTF8);
        }
        /// <summary>
        /// Log recived message and display on console.
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public string Log(string message)
        {
            DateTime dateNow = DateTime.Now;
            Console.WriteLine(string.Format("{0} received : ", dateNow));
            Console.WriteLine(message);
            File.AppendAllText(
                _FilePath,
                string.Format("{0}{2}{1}{2}", dateNow, message, Environment.NewLine),
                Encoding.UTF8);
            return string.Format("{0} Logged.", dateNow);
        }
    }
}
3. Register service and start it.
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

namespace RemotingServer
{
    class Program
    {
        static void Main(string[] args)
        {
            // 建立通道
            //TcpChannel tcpChannel = new TcpChannel(8888);
            HttpChannel httpChannel = new HttpChannel(8889);

            // 註冊監聽
            //ChannelServices.RegisterChannel(tcpChannel, false);
            ChannelServices.RegisterChannel(httpChannel, false);

            // 註冊服務
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(RemotingServer.RemotingObject),
                "RemotingSample",
                WellKnownObjectMode.Singleton);

            Console.Read();
        }
    }
}
4. Create a new project RemotingClient for client testing.
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using RemotingInterface;

namespace RemotingClient
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpChannel httpChannel = new HttpChannel();
            ChannelServices.RegisterChannel(httpChannel, false);

            IRemotingObj remotingObj =
                Activator.GetObject(
                typeof(RemotingInterface.IRemotingObj),
                "http://127.0.0.1:8889/RemotingSample") as IRemotingObj;

            if (remotingObj == null)
            {
                Console.WriteLine("remoting object is null.");
                Console.ReadLine();
            }
            else
            {
                while (true)
                {
                    try
                    {
                        string strMsg = Console.ReadLine();
                        if (strMsg == "finish") return;
                        string strReturnMsg = remotingObj.Log(strMsg);
                        Console.WriteLine(strReturnMsg);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
    }
}
Read image from database and write to file
<%@ WebHandler Language="C#" Class="ImageVender" %>

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

public class ImageVender : IHttpHandler
{
    private HttpContext context;
    private string folderPath;
    private string table = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("ImageAlbum"));

    public void ProcessRequest(HttpContext context)
    {
        folderPath = string.Format("{0}{1}", context.Request.Url.AbsolutePath.Replace("ImageVender.ashx", ""), table);

        this.context = context;
        if (string.IsNullOrEmpty(context.Request.QueryString["id"]))
        {
            //context.Response.StatusCode = 404;
            context.Response.ContentType = "text/plain";
            context.Response.Write("Can't find the picture.");
            context.Response.End();
        }
        else
        {

            bool resized = !string.IsNullOrEmpty(context.Request.QueryString["r"]);
            string url = FindImage(context.Request.QueryString["id"], resized);
            if (url == string.Empty)
            {
                LoadImageData();
                context.Response.Redirect(FindImage(context.Request.QueryString["id"], resized));
            }
            else
            {
                if (context.Request.Headers["ImageOperation"] == "RmoveImageFile")
                {
                    try
                    {
                        string file = context.Server.MapPath(FindImage(context.Request.QueryString["id"], true));
                        if (File.Exists(file))
                        {
                            File.SetAttributes(file, FileAttributes.Normal);
                            File.Delete(file);
                        }
                    }
                    catch { }
                    try
                    {
                        string file = context.Server.MapPath(FindImage(context.Request.QueryString["id"], false));
                        if (File.Exists(file))
                        {
                            File.SetAttributes(file, FileAttributes.Normal);
                            File.Delete(file);
                        }
                    }
                    catch { }
                    //LoadImageData();
                    //context.Response.Redirect(FindImage(context.Request.QueryString["id"], resized));
                }
                else
                {
                    context.Response.Redirect(url);
                }
            }
        }
    }

    private string FindImage(string id, bool resized)
    {
        string path = string.Format("{0}/{1}{2}.", folderPath, (resized ? "r" : ""), id);

        if (File.Exists(context.Server.MapPath(path + "jpg"))) return path + "jpg";
        if (File.Exists(context.Server.MapPath(path + "bmp"))) return path + "bmp";
        if (File.Exists(context.Server.MapPath(path + "gif"))) return path + "gif";
        if (File.Exists(context.Server.MapPath(path + "png"))) return path + "png";
        return string.Empty; ;
    }

    private void LoadImageData()
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[VarHelper.ConnStrLocal].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand("SELECT [MimeType], [Image], [UpdateTime] FROM [ImageAlbum] WITH (NOLOCK) WHERE [ImageID] = @ImageID", conn);
            cmd.Parameters.Add("@ImageID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"];

            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                byte[] data = null;
                string contentType = string.Empty;
                DateTime updateTime = DateTime.Now;
                while (reader.Read())
                {
                    data = (byte[])reader["Image"];
                    contentType = (string)reader["MimeType"];
                    updateTime = (DateTime)reader["UpdateTime"];
                }

                WriteImageFile(context.Server.MapPath(folderPath), ConcatFileName(context.Request.QueryString["id"], contentType), data);

                //context.Response.ContentType = contentType;
                //context.Response.BinaryWrite(data);
                //context.Response.End();

            }
            else
            {
                context.Response.StatusCode = 404;
            }
            conn.Close();
        }
    }

    private string ConcatFileName(string id, string mimeType)
    {
        switch (mimeType)
        {
            case "image/x-png":
                return string.Format("{0}.png", id);
            case "image/pjpeg":
                return string.Format("{0}.jpg", id);
            case "image/gif":
                return string.Format("{0}.gif", id);
            case "image/bmp":
                return string.Format("{0}.bmp", id);
            default:
                return string.Empty;
        }
    }

    private void WriteImageFile(string path, string filename, byte[] data)
    {
        //string folder = context.Server.MapPath(path);
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

        string file = string.Format("{0}\\{1}", path, filename);
        File.WriteAllBytes(file, data);

        Image source = Image.FromFile(file);
        if (source.Width > 150 || source.Height > 150)
        {
            double resizeWidth = 150.0 / source.Width * 100;
            double resizeHeight = 150.0 / source.Height * 100;
            Image resized = null;
            if (resizeWidth > resizeHeight)
            {
                resized = ImageResizer.ScaleByPercent(source, (int)resizeHeight);
            }
            else
            {
                resized = ImageResizer.ScaleByPercent(source, (int)resizeWidth);
            }
            resized.Save(string.Format("{0}\\r{1}", path, filename));
        }
        else
        {
            source.Save(string.Format("{0}\\r{1}", path, filename));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
Read image from database and write into response
<%@ WebHandler Language="C#" Class="Image" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
public class Image : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        if (string.IsNullOrEmpty(context.Request.QueryString["id"]))
        {
            context.Response.StatusCode = "404";
            context.Response.End();
        }
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[VarHelper.ConnStrLocal].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand("SELECT [MimeType], [Image] FROM [ImageAlbum] WHERE [ImageID] = @ImageID", conn);
            cmd.Parameters.Add("@ImageID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"];

            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                byte[] data = null;
                string contentType = string.Empty;
                while (reader.Read())
                {
                    data = (byte[])reader["Image"];
                    contentType = (string)reader["MimeType"];
                }
                context.Response.ContentType = contentType;
                context.Response.BinaryWrite(data);
                context.Response.End();
            }
            else
            {
                context.Response.StatusCode = "404";
                context.Response.End();
            }
            conn.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
Resize image using C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;


class ImageResizer
{
    public static Image ScaleByPercent(Image imgPhoto, int Percent)
    {
        float nPercent = ((float)Percent / 100);

        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;

        int destX = 0;
        int destY = 0;
        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
                                 PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                                imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }

    public static Image ScaleByFixedSize(Image imgPhoto, int Width, int Height)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);
        if (nPercentH < nPercentW)
        {
            nPercent = nPercentH;
            destX = System.Convert.ToInt16((Width -
                          (sourceWidth * nPercent)) / 2);
        }
        else
        {
            nPercent = nPercentW;
            destY = System.Convert.ToInt16((Height -
                          (sourceHeight * nPercent)) / 2);
        }

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap bmPhoto = new Bitmap(Width, Height,
                          PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                         imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.Clear(Color.Red);
        grPhoto.InterpolationMode =
                InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }

    public static Image Crop(Image imgPhoto, int Width,
                         int Height, AnchorPosition Anchor)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);

        if (nPercentH < nPercentW)
        {
            nPercent = nPercentW;
            switch (Anchor)
            {
                case AnchorPosition.Top:
                    destY = 0;
                    break;
                case AnchorPosition.Bottom:
                    destY = (int)
                        (Height - (sourceHeight * nPercent));
                    break;
                default:
                    destY = (int)
                        ((Height - (sourceHeight * nPercent)) / 2);
                    break;
            }
        }
        else
        {
            nPercent = nPercentH;
            switch (Anchor)
            {
                case AnchorPosition.Left:
                    destX = 0;
                    break;
                case AnchorPosition.Right:
                    destX = (int)
                      (Width - (sourceWidth * nPercent));
                    break;
                default:
                    destX = (int)
                      ((Width - (sourceWidth * nPercent)) / 2);
                    break;
            }
        }

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap bmPhoto = new Bitmap(Width,
                Height, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode =
                InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }
}

public enum AnchorPosition
{
    Top = 0,
    Bottom = 1,
    Center = 2,
    Left = 3,
    Right = 4
}
A simple map
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>電子地圖</title>

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

    <script type="text/javascript">
     //<![CDATA[
    var map = false;
    var geocoder = new GClientGeocoder(); //解譯程式
    var address = "中山北路2段52號";
    //geocoder.getLatLng(address, showMark);
    function showMark(point) {
        if (!point) {
            alert("Not found.");
        } else {
            map.setCenter(point, 16);
            var marker = new GMarker(point);
            map.addOverlay(marker);
            marker.openInfoWindowHtml("<table border=\"0\" style=\"margin-top:10px;\"><tr><td>查詢位置</td><td>"+address+"</td></tr><tr><td>座標</td><td>"+point+"</td></tr></table>");
        }
    }
    function init(){
        if(GBrowserIsCompatible()){
            map = new GMap2(document.getElementById("map"));
            map.setCenter(new GLatLng(25.029075,121.520034), 15);
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
        }
    }
     //]]>
    </script>

</head>
<body onload="init();">
    <center>
        <div style="width: 963px;text-align:left;">
            <input id="searcht" type="text" /><input type="button" value="搜尋" onclick="address=document.getElementById('searcht').value;geocoder.getLatLng(address, showMark);"/>
            <div id="map" style="width: 100%; height: 600px">
            </div>
        </div>
    </center>
</body>
</html>
Block text input
<input type="text" onkeydown="return false;" />
<textarea onkeypress="event.returnValue=this.value.length<1500;"></textarea>
CSS drop shadow
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>CSS drop shadow</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <style type="text/css">
        #shadow-container
        {
            position: relative;
            left: 3px;
            top: 3px;
            margin-right: 3px;
            margin-bottom: 3px;
        }
        #shadow-container .shadow2, #shadow-container .shadow3, #shadow-container .container
        {
            position: relative;
            left: -1px;
            top: -1px;
        }
        #shadow-container .shadow1
        {
            background: #F1F0F1;
        }
        #shadow-container .shadow2
        {
            background: #DBDADB;
        }
        #shadow-container .shadow3
        {
            background: #B8B6B8;
        }
        #shadow-container .container
        {
            background: #ffffff;
            border: 1px solid #848284;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div id="shadow-container">
        <div class="shadow1">
            <div class="shadow2">
                <div class="shadow3">
                    <div class="container">
                        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
                        Ipsum has been the industry's standard dummy text ever since the 1500s, when an
                        unknown printer took a galley of type and scrambled it to make a type specimen book.
                        It has survived not only five centuries, but also the leap into electronic typesetting,
                        remaining essentially unchanged. It was popularised in the 1960s with the release
                        of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
                        publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>