Popular Posts
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago. // Enable SSL... 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... 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
  1. /*
  2.  * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
  3.  *
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  *
  8.  *   - Redistributions of source code must retain the above copyright
  9.  *     notice, this list of conditions and the following disclaimer.
  10.  *
  11.  *   - Redistributions in binary form must reproduce the above copyright
  12.  *     notice, this list of conditions and the following disclaimer in the
  13.  *     documentation and/or other materials provided with the distribution.
  14.  *
  15.  *   - Neither the name of Sun Microsystems nor the names of its
  16.  *     contributors may be used to endorse or promote products derived
  17.  *     from this software without specific prior written permission.
  18.  *
  19.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  20.  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  21.  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  23.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26.  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27.  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28.  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30.  */
  31.  
  32. import java.io.BufferedReader;
  33. import java.io.File;
  34. import java.io.FileInputStream;
  35. import java.io.FileOutputStream;
  36. import java.io.InputStream;
  37. import java.io.InputStreamReader;
  38. import java.io.OutputStream;
  39. import java.security.KeyStore;
  40. import java.security.MessageDigest;
  41. import java.security.cert.CertificateException;
  42. import java.security.cert.X509Certificate;
  43.  
  44. import javax.net.ssl.SSLContext;
  45. import javax.net.ssl.SSLException;
  46. import javax.net.ssl.SSLSocket;
  47. import javax.net.ssl.SSLSocketFactory;
  48. import javax.net.ssl.TrustManager;
  49. import javax.net.ssl.TrustManagerFactory;
  50. import javax.net.ssl.X509TrustManager;
  51.  
  52. public class InstallCert {
  53.  
  54.     public static void main(String[] args) throws Exception {
  55.         String host;
  56.         int port;
  57.         char[] passphrase;
  58.         if ((args.length == 1) || (args.length == 2)) {
  59.             String[] c = args[0].split(":");
  60.             host = c[0];
  61.             port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
  62.             String p = (args.length == 1) ? "changeit" : args[1];
  63.             passphrase = p.toCharArray();
  64.         } else {
  65.             System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
  66.             return;
  67.         }
  68.  
  69.         File file = new File("jssecacerts");
  70.         if (file.isFile() == false) {
  71.             char SEP = File.separatorChar;
  72.             File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
  73.             file = new File(dir, "jssecacerts");
  74.             if (file.isFile() == false) {
  75.                 file = new File(dir, "cacerts");
  76.             }
  77.         }
  78.         System.out.println("Loading KeyStore " + file + "...");
  79.         InputStream in = new FileInputStream(file);
  80.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  81.         ks.load(in, passphrase);
  82.         in.close();
  83.  
  84.         SSLContext context = SSLContext.getInstance("TLS");
  85.         TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  86.         tmf.init(ks);
  87.         X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
  88.         SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  89.         context.init(null, new TrustManager[] { tm }, null);
  90.         SSLSocketFactory factory = context.getSocketFactory();
  91.  
  92.         System.out.println("Opening connection to " + host + ":" + port + "...");
  93.         SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
  94.         socket.setSoTimeout(10000);
  95.         try {
  96.             System.out.println("Starting SSL handshake...");
  97.             socket.startHandshake();
  98.             socket.close();
  99.             System.out.println();
  100.             System.out.println("No errors, certificate is already trusted");
  101.         } catch (SSLException e) {
  102.             System.out.println();
  103.             e.printStackTrace(System.out);
  104.         }
  105.  
  106.         X509Certificate[] chain = tm.chain;
  107.         if (chain == null) {
  108.             System.out.println("Could not obtain server certificate chain");
  109.             return;
  110.         }
  111.  
  112.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  113.  
  114.         System.out.println();
  115.         System.out.println("Server sent " + chain.length + " certificate(s):");
  116.         System.out.println();
  117.         MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  118.         MessageDigest md5 = MessageDigest.getInstance("MD5");
  119.         for (int i = 0; i < chain.length; i++) {
  120.             X509Certificate cert = chain[i];
  121.             System.out.println(" " + (+ 1) + " Subject " + cert.getSubjectDN());
  122.             System.out.println("   Issuer  " + cert.getIssuerDN());
  123.             sha1.update(cert.getEncoded());
  124.             System.out.println("   sha1    " + toHexString(sha1.digest()));
  125.             md5.update(cert.getEncoded());
  126.             System.out.println("   md5     " + toHexString(md5.digest()));
  127.             System.out.println();
  128.         }
  129.  
  130.         System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
  131.         String line = reader.readLine().trim();
  132.         int k;
  133.         try {
  134.             k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
  135.         } catch (NumberFormatException e) {
  136.             System.out.println("KeyStore not changed");
  137.             return;
  138.         }
  139.  
  140.         X509Certificate cert = chain[k];
  141.         String alias = host + "-" + (+ 1);
  142.         ks.setCertificateEntry(alias, cert);
  143.  
  144.         OutputStream out = new FileOutputStream("jssecacerts");
  145.         ks.store(out, passphrase);
  146.         out.close();
  147.  
  148.         System.out.println();
  149.         System.out.println(cert);
  150.         System.out.println();
  151.         System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
  152.     }
  153.  
  154.     private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
  155.  
  156.     private static String toHexString(byte[] bytes) {
  157.         StringBuilder sb = new StringBuilder(bytes.length * 3);
  158.         for (int b : bytes) {
  159.             b &= 0xff;
  160.             sb.append(HEXDIGITS[>> 4]);
  161.             sb.append(HEXDIGITS[& 15]);
  162.             sb.append(' ');
  163.         }
  164.         return sb.toString();
  165.     }
  166.  
  167.     private static class SavingTrustManager implements X509TrustManager {
  168.  
  169.         private final X509TrustManager tm;
  170.         private X509Certificate[] chain;
  171.  
  172.         SavingTrustManager(X509TrustManager tm) {
  173.             this.tm = tm;
  174.         }
  175.  
  176.         public X509Certificate[] getAcceptedIssuers() {
  177.             throw new UnsupportedOperationException();
  178.         }
  179.  
  180.         public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  181.             throw new UnsupportedOperationException();
  182.         }
  183.  
  184.         public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  185.             this.chain = chain;
  186.             tm.checkServerTrusted(chain, authType);
  187.         }
  188.     }
  189.  
  190. }
First, create the certificate file.
  1. java InstallCert www.domain.com
After generate the certificate file, code below :
  1. System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
  2. Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  3. System.setProperty("javax.net.ssl.trustStore", certificate);  // certificate is the file path
  4. 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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Binding with a member.aspx.cs"
  2.     Inherits="Binding_with_a_member" %>
  3.  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7.     <title>Binding with page member</title>
  8. </head>
  9. <body>
  10.     <form id="form1" runat="server">
  11.     <div>
  12.         <asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource1">
  13.             <ItemTemplate>
  14.                 <div style="text-align: center; font-size: xx-large; color: Red;">
  15.                     <asp:Label ID="Label1" runat="server" Text='<%# GUID %>'></asp:Label>
  16.                 </div>
  17.                 <div style="text-align: center; font-size: xx-large; color: Blue;">
  18.                     <asp:Label ID="Label2" runat="server" Text='<%# RandomNumber %>'></asp:Label>
  19.                 </div>
  20.                 <div style="text-align: center; font-size: xx-large; color: Green;">
  21.                     <asp:Label ID="Label3" runat="server" Text='<%# DateTime.Now %>'></asp:Label>
  22.                 </div>
  23.             </ItemTemplate>
  24.         </asp:FormView>
  25.     </div>
  26.     <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%ConnectionStrings:brucedbConnectionString %>"
  27.         SelectCommand="SELECT * FROM [GV]"></asp:SqlDataSource>
  28.     </form>
  29. </body>
  30. </html>
  1. using System;
  2. using System.Collections;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Security;
  8. using System.Web.UI;
  9. using System.Web.UI.HtmlControls;
  10. using System.Web.UI.WebControls;
  11. using System.Web.UI.WebControls.WebParts;
  12. using System.Xml.Linq;
  13.  
  14. public partial class Binding_with_a_member : System.Web.UI.Page
  15. {
  16.     protected string GUID;
  17.     protected int RandomNumber;
  18.     protected void Page_Load(object sender, EventArgs e)
  19.     {
  20.         GUID = Guid.NewGuid().ToString();
  21.         RandomNumber = new Random().Next(100, 10000);
  22.     }
  23. }
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?
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewMischief.aspx.cs"
  2.     Inherits="GridViewMischief" %>
  3.  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7.     <title>GridView mischief</title>
  8. </head>
  9. <body>
  10.     <form id="form1" runat="server">
  11.     <div>
  12.         <asp:GridView ID="mischiefGridView" runat="server" AllowPaging="True" AutoGenerateColumns="False"
  13.             DataKeyNames="ID" DataSourceID="mischief" CellPadding="4" ForeColor="#333333"
  14.             GridLines="None" BorderWidth="0" Width="100%">
  15.             <RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />
  16.             <Columns>
  17.                 <asp:BoundField DataField="ID" HeaderText="編號" InsertVisible="False" ReadOnly="True"
  18.                     SortExpression="ID" />
  19.                 <asp:BoundField DataField="UniqueID" HeaderText="序號" SortExpression="UniqueID" />
  20.                 <asp:BoundField DataField="Price" HeaderText="價格" SortExpression="Price" />
  21.                 <asp:BoundField DataField="Amount" HeaderText="數量" SortExpression="Amount" />
  22.                 <asp:BoundField DataField="CreateDate" HeaderText="日期" SortExpression="CreateDate" />
  23.                 <asp:CommandField ShowDeleteButton="True" HeaderText="刪除" />
  24.                 <asp:TemplateField ShowHeader="False" HeaderText="編輯">
  25.                     <EditItemTemplate>
  26.                         <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
  27.                             Text="更新"></asp:LinkButton>
  28.                         &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
  29.                             Text="取消"></asp:LinkButton>
  30.                     </EditItemTemplate>
  31.                     <ItemTemplate>
  32.                         <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
  33.                             Text="編輯"></asp:LinkButton>
  34.                         </td></tr>
  35.                         <tr>
  36.                             <td colspan="7">
  37.                                 <hr />
  38.                     </ItemTemplate>
  39.                 </asp:TemplateField>
  40.             </Columns>
  41.             <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  42.             <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  43.             <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  44.             <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  45.             <EditRowStyle BackColor="#2461BF" />
  46.             <AlternatingRowStyle BackColor="#DCDCDC" />
  47.         </asp:GridView>
  48.         <asp:SqlDataSource ID="mischief" runat="server" ConnectionString="<%ConnectionStrings:brucedbConnectionString %>"
  49.             SelectCommand="SELECT * FROM [GV]" DeleteCommand="DELETE FROM [GV] WHERE [ID] = @ID"
  50.             InsertCommand="INSERT INTO [GV] ([UniqueID], [Price], [Amount], [CreateDate]) VALUES (@UniqueID, @Price, @Amount, @CreateDate)"
  51.             UpdateCommand="UPDATE [GV] SET [UniqueID] = @UniqueID, [Price] = @Price, [Amount] = @Amount, [CreateDate] = @CreateDate WHERE [ID] = @ID">
  52.             <DeleteParameters>
  53.                 <asp:Parameter Name="ID" Type="Int32" />
  54.             </DeleteParameters>
  55.             <UpdateParameters>
  56.                 <asp:Parameter Name="UniqueID" Type="String" />
  57.                 <asp:Parameter Name="Price" Type="Int32" />
  58.                 <asp:Parameter Name="Amount" Type="Int32" />
  59.                 <asp:Parameter DbType="Date" Name="CreateDate" />
  60.                 <asp:Parameter Name="ID" Type="Int32" />
  61.             </UpdateParameters>
  62.             <InsertParameters>
  63.                 <asp:Parameter Name="UniqueID" Type="String" />
  64.                 <asp:Parameter Name="Price" Type="Int32" />
  65.                 <asp:Parameter Name="Amount" Type="Int32" />
  66.                 <asp:Parameter DbType="Date" Name="CreateDate" />
  67.             </InsertParameters>
  68.         </asp:SqlDataSource>
  69.     </div>
  70.     </form>
  71. </body>
  72. </html>
Set Textbox value when TextMode set to Password
  1. <asp:TextBox ID="tbPassword" runat="server" Columns="16" TextMode="Password"></asp:TextBox>
  1. 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.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace RemotingInterface
  7. {
  8.     /// <summary>
  9.     /// Remoting object interface
  10.     /// </summary>
  11.     public interface IRemotingObj
  12.     {
  13.         string Log(string message);
  14.     }
  15. }
2. Create a new project RemotingServer, and create a remoting object for work.
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using RemotingInterface;
  5.  
  6. namespace RemotingServer
  7. {
  8.     /// <summary>
  9.     /// Remoting object
  10.     /// </summary>
  11.     class RemotingObject : MarshalByRefObject, IRemotingObj
  12.     {
  13.         private string _FilePath = @"C:\remoting.txt";
  14.         /// <summary>
  15.         /// Log object created infomation.
  16.         /// </summary>
  17.         public RemotingObject()
  18.         {
  19.             string strMsg = "Object created.";
  20.             Console.WriteLine(strMsg);
  21.             File.AppendAllText(
  22.                 _FilePath,
  23.                 string.Format("{0}{2}{1}{2}", DateTime.Now, strMsg, Environment.NewLine),
  24.                 Encoding.UTF8);
  25.         }
  26.         /// <summary>
  27.         /// Log recived message and display on console.
  28.         /// </summary>
  29.         /// <param name="message"></param>
  30.         /// <returns></returns>
  31.         public string Log(string message)
  32.         {
  33.             DateTime dateNow = DateTime.Now;
  34.             Console.WriteLine(string.Format("{0} received : ", dateNow));
  35.             Console.WriteLine(message);
  36.             File.AppendAllText(
  37.                 _FilePath,
  38.                 string.Format("{0}{2}{1}{2}", dateNow, message, Environment.NewLine),
  39.                 Encoding.UTF8);
  40.             return string.Format("{0} Logged.", dateNow);
  41.         }
  42.     }
  43. }
3. Register service and start it.
  1. using System;
  2. using System.Runtime.Remoting;
  3. using System.Runtime.Remoting.Channels;
  4. using System.Runtime.Remoting.Channels.Http;
  5.  
  6. namespace RemotingServer
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             // 建立通道
  13.             //TcpChannel tcpChannel = new TcpChannel(8888);
  14.             HttpChannel httpChannel = new HttpChannel(8889);
  15.  
  16.             // 註冊監聽
  17.             //ChannelServices.RegisterChannel(tcpChannel, false);
  18.             ChannelServices.RegisterChannel(httpChannel, false);
  19.  
  20.             // 註冊服務
  21.             RemotingConfiguration.RegisterWellKnownServiceType(
  22.                 typeof(RemotingServer.RemotingObject),
  23.                 "RemotingSample",
  24.                 WellKnownObjectMode.Singleton);
  25.  
  26.             Console.Read();
  27.         }
  28.     }
  29. }
4. Create a new project RemotingClient for client testing.
  1. using System;
  2. using System.Runtime.Remoting.Channels;
  3. using System.Runtime.Remoting.Channels.Http;
  4. using RemotingInterface;
  5.  
  6. namespace RemotingClient
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             HttpChannel httpChannel = new HttpChannel();
  13.             ChannelServices.RegisterChannel(httpChannel, false);
  14.  
  15.             IRemotingObj remotingObj =
  16.                 Activator.GetObject(
  17.                 typeof(RemotingInterface.IRemotingObj),
  18.                 "http://127.0.0.1:8889/RemotingSample") as IRemotingObj;
  19.  
  20.             if (remotingObj == null)
  21.             {
  22.                 Console.WriteLine("remoting object is null.");
  23.                 Console.ReadLine();
  24.             }
  25.             else
  26.             {
  27.                 while (true)
  28.                 {
  29.                     try
  30.                     {
  31.                         string strMsg = Console.ReadLine();
  32.                         if (strMsg == "finish") return;
  33.                         string strReturnMsg = remotingObj.Log(strMsg);
  34.                         Console.WriteLine(strReturnMsg);
  35.                     }
  36.                     catch (Exception e)
  37.                     {
  38.                         Console.WriteLine(e.Message);
  39.                     }
  40.                 }
  41.             }
  42.         }
  43.     }
  44. }
Read image from database and write to file
  1. <%@ WebHandler Language="C#" Class="ImageVender" %>
  2.  
  3. using System;
  4. using System.Web;
  5. using System.Data.SqlClient;
  6. using System.Configuration;
  7. using System.IO;
  8. using System.Drawing;
  9.  
  10. public class ImageVender : IHttpHandler
  11. {
  12.     private HttpContext context;
  13.     private string folderPath;
  14.     private string table = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("ImageAlbum"));
  15.  
  16.     public void ProcessRequest(HttpContext context)
  17.     {
  18.         folderPath = string.Format("{0}{1}", context.Request.Url.AbsolutePath.Replace("ImageVender.ashx", ""), table);
  19.  
  20.         this.context = context;
  21.         if (string.IsNullOrEmpty(context.Request.QueryString["id"]))
  22.         {
  23.             //context.Response.StatusCode = 404;
  24.             context.Response.ContentType = "text/plain";
  25.             context.Response.Write("Can't find the picture.");
  26.             context.Response.End();
  27.         }
  28.         else
  29.         {
  30.  
  31.             bool resized = !string.IsNullOrEmpty(context.Request.QueryString["r"]);
  32.             string url = FindImage(context.Request.QueryString["id"], resized);
  33.             if (url == string.Empty)
  34.             {
  35.                 LoadImageData();
  36.                 context.Response.Redirect(FindImage(context.Request.QueryString["id"], resized));
  37.             }
  38.             else
  39.             {
  40.                 if (context.Request.Headers["ImageOperation"] == "RmoveImageFile")
  41.                 {
  42.                     try
  43.                     {
  44.                         string file = context.Server.MapPath(FindImage(context.Request.QueryString["id"], true));
  45.                         if (File.Exists(file))
  46.                         {
  47.                             File.SetAttributes(file, FileAttributes.Normal);
  48.                             File.Delete(file);
  49.                         }
  50.                     }
  51.                     catch { }
  52.                     try
  53.                     {
  54.                         string file = context.Server.MapPath(FindImage(context.Request.QueryString["id"], false));
  55.                         if (File.Exists(file))
  56.                         {
  57.                             File.SetAttributes(file, FileAttributes.Normal);
  58.                             File.Delete(file);
  59.                         }
  60.                     }
  61.                     catch { }
  62.                     //LoadImageData();
  63.                     //context.Response.Redirect(FindImage(context.Request.QueryString["id"], resized));
  64.                 }
  65.                 else
  66.                 {
  67.                     context.Response.Redirect(url);
  68.                 }
  69.             }
  70.         }
  71.     }
  72.  
  73.     private string FindImage(string id, bool resized)
  74.     {
  75.         string path = string.Format("{0}/{1}{2}.", folderPath, (resized ? "r" : ""), id);
  76.  
  77.         if (File.Exists(context.Server.MapPath(path + "jpg"))) return path + "jpg";
  78.         if (File.Exists(context.Server.MapPath(path + "bmp"))) return path + "bmp";
  79.         if (File.Exists(context.Server.MapPath(path + "gif"))) return path + "gif";
  80.         if (File.Exists(context.Server.MapPath(path + "png"))) return path + "png";
  81.         return string.Empty; ;
  82.     }
  83.  
  84.     private void LoadImageData()
  85.     {
  86.         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[VarHelper.ConnStrLocal].ConnectionString))
  87.         {
  88.             SqlCommand cmd = new SqlCommand("SELECT [MimeType], [Image], [UpdateTime] FROM [ImageAlbum] WITH (NOLOCK) WHERE [ImageID] = @ImageID", conn);
  89.             cmd.Parameters.Add("@ImageID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"];
  90.  
  91.             conn.Open();
  92.             SqlDataReader reader = cmd.ExecuteReader();
  93.             if (reader.HasRows)
  94.             {
  95.                 byte[] data = null;
  96.                 string contentType = string.Empty;
  97.                 DateTime updateTime = DateTime.Now;
  98.                 while (reader.Read())
  99.                 {
  100.                     data = (byte[])reader["Image"];
  101.                     contentType = (string)reader["MimeType"];
  102.                     updateTime = (DateTime)reader["UpdateTime"];
  103.                 }
  104.  
  105.                 WriteImageFile(context.Server.MapPath(folderPath), ConcatFileName(context.Request.QueryString["id"], contentType), data);
  106.  
  107.                 //context.Response.ContentType = contentType;
  108.                 //context.Response.BinaryWrite(data);
  109.                 //context.Response.End();
  110.  
  111.             }
  112.             else
  113.             {
  114.                 context.Response.StatusCode = 404;
  115.             }
  116.             conn.Close();
  117.         }
  118.     }
  119.  
  120.     private string ConcatFileName(string id, string mimeType)
  121.     {
  122.         switch (mimeType)
  123.         {
  124.             case "image/x-png":
  125.                 return string.Format("{0}.png", id);
  126.             case "image/pjpeg":
  127.                 return string.Format("{0}.jpg", id);
  128.             case "image/gif":
  129.                 return string.Format("{0}.gif", id);
  130.             case "image/bmp":
  131.                 return string.Format("{0}.bmp", id);
  132.             default:
  133.                 return string.Empty;
  134.         }
  135.     }
  136.  
  137.     private void WriteImageFile(string path, string filename, byte[] data)
  138.     {
  139.         //string folder = context.Server.MapPath(path);
  140.         if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  141.  
  142.         string file = string.Format("{0}\\{1}", path, filename);
  143.         File.WriteAllBytes(file, data);
  144.  
  145.         Image source = Image.FromFile(file);
  146.         if (source.Width > 150 || source.Height > 150)
  147.         {
  148.             double resizeWidth = 150.0 / source.Width * 100;
  149.             double resizeHeight = 150.0 / source.Height * 100;
  150.             Image resized = null;
  151.             if (resizeWidth > resizeHeight)
  152.             {
  153.                 resized = ImageResizer.ScaleByPercent(source, (int)resizeHeight);
  154.             }
  155.             else
  156.             {
  157.                 resized = ImageResizer.ScaleByPercent(source, (int)resizeWidth);
  158.             }
  159.             resized.Save(string.Format("{0}\\r{1}", path, filename));
  160.         }
  161.         else
  162.         {
  163.             source.Save(string.Format("{0}\\r{1}", path, filename));
  164.         }
  165.     }
  166.  
  167.     public bool IsReusable
  168.     {
  169.         get
  170.         {
  171.             return false;
  172.         }
  173.     }
  174.  
  175. }
Read image from database and write into response
  1. <%@ WebHandler Language="C#" Class="Image" %>
  2.  
  3. using System;
  4. using System.Web;
  5. using System.Data.SqlClient;
  6. using System.Configuration;
  7. public class Image : IHttpHandler
  8. {
  9.  
  10.     public void ProcessRequest(HttpContext context)
  11.     {
  12.         if (string.IsNullOrEmpty(context.Request.QueryString["id"]))
  13.         {
  14.             context.Response.StatusCode = "404";
  15.             context.Response.End();
  16.         }
  17.         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[VarHelper.ConnStrLocal].ConnectionString))
  18.         {
  19.             SqlCommand cmd = new SqlCommand("SELECT [MimeType], [Image] FROM [ImageAlbum] WHERE [ImageID] = @ImageID", conn);
  20.             cmd.Parameters.Add("@ImageID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"];
  21.  
  22.             conn.Open();
  23.             SqlDataReader reader = cmd.ExecuteReader();
  24.             if (reader.HasRows)
  25.             {
  26.                 byte[] data = null;
  27.                 string contentType = string.Empty;
  28.                 while (reader.Read())
  29.                 {
  30.                     data = (byte[])reader["Image"];
  31.                     contentType = (string)reader["MimeType"];
  32.                 }
  33.                 context.Response.ContentType = contentType;
  34.                 context.Response.BinaryWrite(data);
  35.                 context.Response.End();
  36.             }
  37.             else
  38.             {
  39.                 context.Response.StatusCode = "404";
  40.                 context.Response.End();
  41.             }
  42.             conn.Close();
  43.         }
  44.     }
  45.  
  46.     public bool IsReusable
  47.     {
  48.         get
  49.         {
  50.             return false;
  51.         }
  52.     }
  53.  
  54. }
Resize image using C#
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Drawing;
  6. using System.Drawing.Imaging;
  7. using System.Drawing.Drawing2D;
  8.  
  9.  
  10. class ImageResizer
  11. {
  12.     public static Image ScaleByPercent(Image imgPhoto, int Percent)
  13.     {
  14.         float nPercent = ((float)Percent / 100);
  15.  
  16.         int sourceWidth = imgPhoto.Width;
  17.         int sourceHeight = imgPhoto.Height;
  18.         int sourceX = 0;
  19.         int sourceY = 0;
  20.  
  21.         int destX = 0;
  22.         int destY = 0;
  23.         int destWidth = (int)(sourceWidth * nPercent);
  24.         int destHeight = (int)(sourceHeight * nPercent);
  25.  
  26.         Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
  27.                                  PixelFormat.Format24bppRgb);
  28.         bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
  29.                                 imgPhoto.VerticalResolution);
  30.  
  31.         Graphics grPhoto = Graphics.FromImage(bmPhoto);
  32.         grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
  33.  
  34.         grPhoto.DrawImage(imgPhoto,
  35.             new Rectangle(destX, destY, destWidth, destHeight),
  36.             new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
  37.             GraphicsUnit.Pixel);
  38.  
  39.         grPhoto.Dispose();
  40.         return bmPhoto;
  41.     }
  42.  
  43.     public static Image ScaleByFixedSize(Image imgPhoto, int Width, int Height)
  44.     {
  45.         int sourceWidth = imgPhoto.Width;
  46.         int sourceHeight = imgPhoto.Height;
  47.         int sourceX = 0;
  48.         int sourceY = 0;
  49.         int destX = 0;
  50.         int destY = 0;
  51.  
  52.         float nPercent = 0;
  53.         float nPercentW = 0;
  54.         float nPercentH = 0;
  55.  
  56.         nPercentW = ((float)Width / (float)sourceWidth);
  57.         nPercentH = ((float)Height / (float)sourceHeight);
  58.         if (nPercentH < nPercentW)
  59.         {
  60.             nPercent = nPercentH;
  61.             destX = System.Convert.ToInt16((Width -
  62.                           (sourceWidth * nPercent)) / 2);
  63.         }
  64.         else
  65.         {
  66.             nPercent = nPercentW;
  67.             destY = System.Convert.ToInt16((Height -
  68.                           (sourceHeight * nPercent)) / 2);
  69.         }
  70.  
  71.         int destWidth = (int)(sourceWidth * nPercent);
  72.         int destHeight = (int)(sourceHeight * nPercent);
  73.  
  74.         Bitmap bmPhoto = new Bitmap(Width, Height,
  75.                           PixelFormat.Format24bppRgb);
  76.         bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
  77.                          imgPhoto.VerticalResolution);
  78.  
  79.         Graphics grPhoto = Graphics.FromImage(bmPhoto);
  80.         grPhoto.Clear(Color.Red);
  81.         grPhoto.InterpolationMode =
  82.                 InterpolationMode.HighQualityBicubic;
  83.  
  84.         grPhoto.DrawImage(imgPhoto,
  85.             new Rectangle(destX, destY, destWidth, destHeight),
  86.             new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
  87.             GraphicsUnit.Pixel);
  88.  
  89.         grPhoto.Dispose();
  90.         return bmPhoto;
  91.     }
  92.  
  93.     public static Image Crop(Image imgPhoto, int Width,
  94.                          int Height, AnchorPosition Anchor)
  95.     {
  96.         int sourceWidth = imgPhoto.Width;
  97.         int sourceHeight = imgPhoto.Height;
  98.         int sourceX = 0;
  99.         int sourceY = 0;
  100.         int destX = 0;
  101.         int destY = 0;
  102.  
  103.         float nPercent = 0;
  104.         float nPercentW = 0;
  105.         float nPercentH = 0;
  106.  
  107.         nPercentW = ((float)Width / (float)sourceWidth);
  108.         nPercentH = ((float)Height / (float)sourceHeight);
  109.  
  110.         if (nPercentH < nPercentW)
  111.         {
  112.             nPercent = nPercentW;
  113.             switch (Anchor)
  114.             {
  115.                 case AnchorPosition.Top:
  116.                     destY = 0;
  117.                     break;
  118.                 case AnchorPosition.Bottom:
  119.                     destY = (int)
  120.                         (Height - (sourceHeight * nPercent));
  121.                     break;
  122.                 default:
  123.                     destY = (int)
  124.                         ((Height - (sourceHeight * nPercent)) / 2);
  125.                     break;
  126.             }
  127.         }
  128.         else
  129.         {
  130.             nPercent = nPercentH;
  131.             switch (Anchor)
  132.             {
  133.                 case AnchorPosition.Left:
  134.                     destX = 0;
  135.                     break;
  136.                 case AnchorPosition.Right:
  137.                     destX = (int)
  138.                       (Width - (sourceWidth * nPercent));
  139.                     break;
  140.                 default:
  141.                     destX = (int)
  142.                       ((Width - (sourceWidth * nPercent)) / 2);
  143.                     break;
  144.             }
  145.         }
  146.  
  147.         int destWidth = (int)(sourceWidth * nPercent);
  148.         int destHeight = (int)(sourceHeight * nPercent);
  149.  
  150.         Bitmap bmPhoto = new Bitmap(Width,
  151.                 Height, PixelFormat.Format24bppRgb);
  152.         bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
  153.                 imgPhoto.VerticalResolution);
  154.  
  155.         Graphics grPhoto = Graphics.FromImage(bmPhoto);
  156.         grPhoto.InterpolationMode =
  157.                 InterpolationMode.HighQualityBicubic;
  158.  
  159.         grPhoto.DrawImage(imgPhoto,
  160.             new Rectangle(destX, destY, destWidth, destHeight),
  161.             new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
  162.             GraphicsUnit.Pixel);
  163.  
  164.         grPhoto.Dispose();
  165.         return bmPhoto;
  166.     }
  167. }
  168.  
  169. public enum AnchorPosition
  170. {
  171.     Top = 0,
  172.     Bottom = 1,
  173.     Center = 2,
  174.     Left = 3,
  175.     Right = 4
  176. }
A simple map
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2.  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5.     <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  6.     <title>電子地圖</title>
  7.  
  8.     <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=mykey"
  9.         type="text/javascript"></script>
  10.  
  11.     <script type="text/javascript">
  12.      //<![CDATA[
  13.     var map = false;
  14.     var geocoder = new GClientGeocoder(); //解譯程式
  15.     var address = "中山北路2段52號";
  16.     //geocoder.getLatLng(address, showMark);
  17.     function showMark(point) {
  18.         if (!point) {
  19.             alert("Not found.");
  20.         } else {
  21.             map.setCenter(point, 16);
  22.             var marker = new GMarker(point);
  23.             map.addOverlay(marker);
  24.             marker.openInfoWindowHtml("<table border=\"0\" style=\"margin-top:10px;\"><tr><td>查詢位置</td><td>"+address+"</td></tr><tr><td>座標</td><td>"+point+"</td></tr></table>");
  25.         }
  26.     }
  27.     function init(){
  28.         if(GBrowserIsCompatible()){
  29.             map = new GMap2(document.getElementById("map"));
  30.             map.setCenter(new GLatLng(25.029075,121.520034), 15);
  31.             map.addControl(new GLargeMapControl());
  32.             map.addControl(new GMapTypeControl());
  33.         }
  34.     }
  35.      //]]>
  36.     </script>
  37.  
  38. </head>
  39. <body onload="init();">
  40.     <center>
  41.         <div style="width: 963px;text-align:left;">
  42.             <input id="searcht" type="text" /><input type="button" value="搜尋" onclick="address=document.getElementById('searcht').value;geocoder.getLatLng(address, showMark);"/>
  43.             <div id="map" style="width: 100%; height: 600px">
  44.             </div>
  45.         </div>
  46.     </center>
  47. </body>
  48. </html>
Block text input
  1. <input type="text" onkeydown="return false;" />
  1. <textarea onkeypress="event.returnValue=this.value.length<1500;"></textarea>
CSS drop shadow
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  3. <head>
  4.     <title>CSS drop shadow</title>
  5.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  6.     <style type="text/css">
  7.         #shadow-container
  8.         {
  9.             position: relative;
  10.             left: 3px;
  11.             top: 3px;
  12.             margin-right: 3px;
  13.             margin-bottom: 3px;
  14.         }
  15.         #shadow-container .shadow2, #shadow-container .shadow3, #shadow-container .container
  16.         {
  17.             position: relative;
  18.             left: -1px;
  19.             top: -1px;
  20.         }
  21.         #shadow-container .shadow1
  22.         {
  23.             background: #F1F0F1;
  24.         }
  25.         #shadow-container .shadow2
  26.         {
  27.             background: #DBDADB;
  28.         }
  29.         #shadow-container .shadow3
  30.         {
  31.             background: #B8B6B8;
  32.         }
  33.         #shadow-container .container
  34.         {
  35.             background: #ffffff;
  36.             border: 1px solid #848284;
  37.             padding: 10px;
  38.         }
  39.     </style>
  40. </head>
  41. <body>
  42.     <div id="shadow-container">
  43.         <div class="shadow1">
  44.             <div class="shadow2">
  45.                 <div class="shadow3">
  46.                     <div class="container">
  47.                         Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
  48.                         Ipsum has been the industry's standard dummy text ever since the 1500s, when an
  49.                         unknown printer took a galley of type and scrambled it to make a type specimen book.
  50.                         It has survived not only five centuries, but also the leap into electronic typesetting,
  51.                         remaining essentially unchanged. It was popularised in the 1960s with the release
  52.                         of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
  53.                         publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  54.                     </div>
  55.                 </div>
  56.             </div>
  57.         </div>
  58.     </div>
  59. </body>
  60. </html>