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... Simple Web snapshot import java.util.Date; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.graphics.GC; import org.e... Tired of Hibernate? Try JDBI in your code JDBI Quick sample ICategoryDAO.java : create a data access interface (implement is not required) package com.prhythm.erotic.task.data....
Blog Archive
Stats
Response wrapper
ResponseWrapper.cs
using System;
using System.Data;
using System.Configuration;
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;
using System.IO;
using System.Text.RegularExpressions;

/// <summary>
/// ResponseWrapper 的摘要描述
/// </summary>
public class ResponseWrapper : Stream
{
    private Stream _stream;

    public ResponseWrapper(Stream stream)
    {
        this._stream = stream;
    }
    protected Stream BaseStream { get { return this._stream; } }
    public override bool CanRead { get { return false; } }
    public override bool CanSeek { get { return false; } }
    public override bool CanWrite { get { return this._stream.CanWrite; } }
    public override long Length { get { throw new NotSupportedException(); } }
    public override long Position
    {
        get { throw new NotSupportedException(); }
        set { throw new NotSupportedException(); }
    }

    public override long Seek(long offset, System.IO.SeekOrigin direction)
    {
        throw new NotSupportedException();
    }

    public override void SetLength(long length)
    {
        throw new NotSupportedException();
    }

    public override void Close()
    {
        this._stream.Close();
    }

    public override void Flush()
    {
        this._stream.Flush();
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        throw new NotSupportedException();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        string outputData = System.Text.Encoding.UTF8.GetString(buffer);

        outputData = Regex.Replace(outputData, ">\\s+<", "><", RegexOptions.Multiline);  // replace all white space between tags
        //outputData = Regex.Replace(outputData, "\\s\\s+", " ", RegexOptions.Singleline);  // replace all white space to single one

        byte[] outData = System.Text.Encoding.UTF8.GetBytes(outputData);
        this._stream.Write(outData, 0, outData.GetLength(0));

    }
}
Global.asax
<%@ Application Language="C#" %>

<script RunAt="server">

    void Application_Start(object sender, EventArgs e)
    {
        // 應用程式啟動時執行的程式碼

    }

    void Application_End(object sender, EventArgs e)
    {
        //  應用程式關閉時執行的程式碼

    }

    void Application_Error(object sender, EventArgs e)
    {
        // 發生未處理錯誤時執行的程式碼

    }

    void Session_Start(object sender, EventArgs e)
    {
        // 啟動新工作階段時執行的程式碼

    }

    void Session_End(object sender, EventArgs e)
    {
        // 工作階段結束時執行的程式碼。 
        // 注意: 只有在 Web.config 檔將 sessionstate 模式設定為 InProc 時,
        // 才會引發 Session_End 事件。如果將工作階段模式設定為 StateServer 
        // 或 SQLServer,就不會引發這個事件。

    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (this.Response.ContentType == "text/html" // 限定輸出類型
            && this.Request.Url.AbsolutePath.EndsWith(".aspx") // 限定請求的url
            && this.Request.HttpMethod == "GET") // 限定httpmethod
            this.Response.Filter = new ResponseWrapper(this.Response.Filter);
    }
       
</script>
Translating 1.3
<html>
<head>
    <title>Translating 1.1</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <style type="text/css">
    strong a{padding-left:7px; padding-right:7px; border:1px outset; cursor:pointer;}
    </style>
    <script type="text/javascript">
    var TL = {
        executingTime : false,
        TSQLReverseWord : ["@@IDENTITY","ENCRYPTION","ORDER","ADD","END","OUTER","ALL","ERRLVL","OVER","ALTER","ESCAPE","PERCENT","AND","EXCEPT","PLAN","ANY","EXEC","PRECISION","AS","EXECUTE","PRIMARY","ASC","EXISTS","PRINT","AUTHORIZATION","EXIT","PROC","AVG","EXPRESSION","PROCEDURE","BACKUP","FETCH","PUBLIC","BEGIN","FILE","RAISERROR","BETWEEN","FILLFACTOR","READ","BREAK","FOR","READTEXT","BROWSE","FOREIGN","RECONFIGURE","BULK","FREETEXT","REFERENCES","BY","FREETEXTTABLE","REPLICATION","CASCADE","FROM","RESTORE","CASE","FULL","RESTRICT","CHECK","FUNCTION","RETURN","CHECKPOINT","GOTO","REVOKE","CLOSE","GRANT","RIGHT","CLUSTERED","GROUP","ROLLBACK","COALESCE","HAVING","ROWCOUNT","COLLATE","HOLDLOCK","ROWGUIDCOL","COLUMN","IDENTITY","RULE","COMMIT","IDENTITY_INSERT","SAVE","COMPUTE","IDENTITYCOL","SCHEMA","CONSTRAINT","IF","SELECT","CONTAINS","IN","SESSION_USER","CONTAINSTABLE","INDEX","SET","CONTINUE","INNER","SETUSER","CONVERT","INSERT","SHUTDOWN","COUNT","INTERSECT","SOME","CREATE","INTO","STATISTICS","CROSS","IS","SUM","CURRENT","JOIN","SYSTEM_USER","CURRENT_DATE","KEY","TABLE","CURRENT_TIME","KILL","TEXTSIZE","CURRENT_TIMESTAMP","LEFT","THEN","CURRENT_USER","LIKE","TO","CURSOR","LINENO","TOP","DATABASE","LOAD","TRAN","DATABASEPASSWORD","MAX","TRANSACTION","DATEADD","MIN","TRIGGER","DATEDIFF","NATIONAL","TRUNCATE","DATENAME","NOCHECK","TSEQUAL","DATEPART","NONCLUSTERED","UNION","DBCC","NOT","UNIQUE","DEALLOCATE","NULL","UPDATE","DECLARE","NULLIF","UPDATETEXT","DEFAULT","OF","USE","DELETE","OFF","USER","DENY","OFFSETS","VALUES","DESC","ON","VARYING","DISK","OPEN","VIEW","DISTINCT","OPENDATASOURCE","WAITFOR","DISTRIBUTED","OPENQUERY","WHEN","DOUBLE","OPENROWSET","WHERE","DROP","OPENXML","WHILE","DUMP","OPTION","WITH","ELSE","OR","WRITETEXT"],
        keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
        changeTab : function(obj){
            var strongs = document.getElementsByTagName("strong");
            for(var i = 0; i < strongs.length; i++){
                strongs[i].firstChild.style.backgroundColor = "transparent";
            }
            obj.style.backgroundColor = "lightblue";
            
            var panels = document.getElementById("panels");
            for(var i = 0; i < panels.childNodes.length; i++){
                if(panels.childNodes[i].nodeType == 1 && panels.childNodes[i].tagName == "DIV"){
                    panels.childNodes[i].style.display = panels.childNodes[i].getAttribute("panel") == obj.getAttribute("tab") ? "block" : "none";
                }
            }
        },
        time : function(end){
            if(end){
                if(this.executingTime){
                    var now = new Date();
                    var ms = now.getTime() - this.executingTime.getTime();
                    var time = Math.floor((ms/60000.0)%60) >= 1 ? Math.floor((ms/60000.0)%60) + " minute(s)" : "";
                    time += Math.floor((ms/1000.0)%60) >= 1 ? Math.floor((ms/1000.0)%60) + " second(s) " : (time.length > 0 ? " 0 second " : "");
                    time += ms%1000 + " miliseconds";
                    document.getElementById("timer").innerHTML = time;
                }else{
                    document.getElementById("timer").innerHTML = "Error time slip.";
                }
            }else{
                this.executingTime = new Date();
            }
        },
        clear : function(){
            document.getElementById("InputArea").value = "";
            document.getElementById("OutputArea").value = "";
        },
        CopyToClipboard : function(){
            if (window.clipboardData){
                window.clipboardData.setData("Text", document.getElementById("OutputArea").value);
            }else if (window.netscape){
                netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
                var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) return;
                var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) return;
                trans.addDataFlavor('text/unicode');
                var str = new Object();
                var len = new Object();
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                var copytext=document.getElementById("OutputArea").value;
                str.data=copytext;
                trans.setTransferData("text/unicode",str,copytext.length*2);
                var clipid=Components.interfaces.nsIClipboard;
                if (!clip) return false;
                clip.setData(trans,null,clipid.kGlobalClipboard);
            }else{
                return false;
            }
            return false;
        },
        blogger : function(reverse){
            this.time(false);
            if(reverse){
                var input = document.getElementById("InputArea").value;
                var chars = [{s:"\t",r:"&nbsp;&nbsp;&nbsp;&nbsp;"},{s:" ",r:"&nbsp;"},{s:"<",r:"&lt;"},{s:">",r:"&gt;"},{s:"&",r:"&amp;"}];
                var temp = input;
                for(var i in chars){
                    while((input = input.replace(chars[i].r, chars[i].s)) != temp) temp = input;
                }
                document.getElementById("OutputArea").value = input;
            }else{
                var input = document.getElementById("InputArea").value.split("");
                var chars = [{s:"&",r:"&amp;"},{s:" ",r:"&nbsp;"},{s:"\t",r:"&nbsp;&nbsp;&nbsp;&nbsp;"},{s:"<",r:"&lt;"},{s:">",r:"&gt;"}];
                for(var i = 0; i < input.length; i++){
                    for(var j in chars) input[i] = input[i].replace(chars[j].s, chars[j].r);
                }
                document.getElementById("OutputArea").value = input.join("");            
            }
            this.time(true);
        },
        sql : function(){
            this.time(false);
            var input = document.getElementById("InputArea").value;
            var wd =false;
            var mg = false;
            this.TSQLReverseWord = this.TSQLReverseWord.sort();
            for(var i in this.TSQLReverseWord){
                wd = this.TSQLReverseWord[i];
                var pattern = new RegExp("[\\D\\W]?(" + wd + ")[\\D\\W]?", "i");
                mg = input.match(pattern);
                if(mg){
                    for(var j = 0; j < mg.length; j++){
                        input = input.replace(mg[j].toString(), mg[j].toString().toUpperCase());
                    }
                }
            }
            document.getElementById("OutputArea").value = input;
            this.time(true);
        },
        url : function(reverse){
            this.time(false);
            if(reverse){
                document.getElementById("OutputArea").value = decodeURI(document.getElementById("InputArea").value);
            }else{
                document.getElementById("OutputArea").value = encodeURI(document.getElementById("InputArea").value);
            }
            this.time(true);
        },
        base64 : function(reverse){
            this.time(false);
            var input = document.getElementById("InputArea").value;
            if(reverse){
                debugger;
                var output = "";
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;

                // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

                do {
                    enc1 = this.keyStr.indexOf(input.charAt(i++));
                    enc2 = this.keyStr.indexOf(input.charAt(i++));
                    enc3 = this.keyStr.indexOf(input.charAt(i++));
                    enc4 = this.keyStr.indexOf(input.charAt(i++));

                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;

                    output = output + String.fromCharCode(chr1);

                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }
                } while (i < input.length);
                document.getElementById("OutputArea").value = this._utf8_decode(output);
            }else{
                input = this._utf8_encode(input);
                var output = "";
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;

                do {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);

                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;

                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }

                    output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + 
                    this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4);
                } while (i < input.length);
                document.getElementById("OutputArea").value = output;
            }
            this.time(true);
        },
        _utf8_encode : function (string) {
            string = string.replace(/\r\n/g,"\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
            }
            return utftext;
        },
        _utf8_decode : function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;
            while ( i < utftext.length ) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i+1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i+1);
                    c3 = utftext.charCodeAt(i+2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        },
        ncr : function(reverse){
            this.time(false);
            if(reverse){
                var input = document.getElementById("InputArea").value;
                var ncr = input.match(/&#x([\da-fA-F]+);/g);
                var unicode = false;
                for(var i = 0; i < ncr.length; i++){
                    unicode = ncr[i].toString().replace(/&#x([\da-fA-F]+);/, '$1');
                    input = input.replace(ncr[i].toString(), String.fromCharCode(parseInt(unicode, 16)));
                }
                document.getElementById("OutputArea").value = input;
            }else{
                var input = document.getElementById("InputArea").value.split("");
                for(var i = 0; i < input.length; i++){
                    if(input[i].charCodeAt(0) < 128) continue;
                    input[i] = "&#x" + input[i].charCodeAt(0).toString(16) + ";";
                }
                document.getElementById("OutputArea").value = input.join("");
            }
            this.time(true);
        },
        properties : function(reverse){
            this.time(false);
            if(reverse){
                var input = document.getElementById("InputArea").value;
                var prop = input.match(/[\\]u([\da-fA-F]+)/g);
                var unicode = false;
                for(var i = 0; i < prop.length; i++){
                    unicode = prop[i].toString().replace(/[\\]u([\da-fA-F]+)/, '$1');
                    input = input.replace(prop[i].toString(), String.fromCharCode(parseInt(unicode, 16)));
                }
                document.getElementById("OutputArea").value = input;
            }else{
                var lines = document.getElementById("InputArea").value.split("\n");
                //alert(lines.length);
                var out = "";
                var chars = [];
                for(var n in lines){
                    //alert(line);
                    chars = lines[n].split("");
                    if(chars[0] != "#" && chars[0] != "!")  // continue;  // for comment
                    for(var i = 0; i < chars.length; i++){
                        if(chars[i].charCodeAt(0) < 128) continue;
                        chars[i] = chars[i].charCodeAt(0) > 127 ? "\\u" + chars[i].charCodeAt(0).toString(16) : chars[i];
                    }
                    out += chars.join("");
                }
                
                document.getElementById("OutputArea").value = out;
            }
            this.time(true);
        },
        srt : function(){
            this.time(false);
            var hh, mm, ss, micro;
            var input = document.getElementById("InputArea").value.split("\n");
            var addtime = document.getElementById("addtime").value;
            try{
                microseconds = parseInt(microseconds);
            }catch(e){
                alert(e);
                return;
            }
            var arrow = " --> ";
            var times;
            for(i = 0; i < content.length; i++){
                if(content[i].indexOf(arrow) > -1){
                    times = content[i].split(arrow);

                    // =====開始時間=====
                    times[0] = this.moveTimeStamp(times[0], microseconds);

                    // =====結束時間=====
                    times[1] = this.moveTimeStamp(times[1], microseconds);

                    content[i] = times.join(arrow);
                }
            }
            document.getElementById("OutputArea").value = input.join("\n");
            this.time(true);
        },
        moveTimeStamp : function(time, microseconds){
            hhTemp = time.substring(0,2);
            mmTemp = time.substring(3,5);
            ssTemp = time.substring(6,8);
            microTemp = time.substring(9,12);
            
            // 去掉字首的 0 (原因 : 在parseInt時會出錯)
            hhTemp = hhTemp.substring(0,1) == "0" ? hhTemp.substring(1, hhTemp.length) : hhTemp;
            mmTemp = mmTemp.substring(0,1) == "0" ? mmTemp.substring(1, mmTemp.length) : mmTemp;
            ssTemp = ssTemp.substring(0,1) == "0" ? ssTemp.substring(1, ssTemp.length) : ssTemp;
            while(microTemp.substring(0,1) == "0" && microTemp.length > 1){
                microTemp = microTemp.substring(1, microTemp.length);
            }
            
            hhTemp = parseInt(hhTemp);
            mmTemp = parseInt(mmTemp);
            ssTemp = parseInt(ssTemp);
            microTemp = parseInt(microTemp);
            //換成 timeStamp計算
            timeStamp = microTemp + ssTemp * 1000 + mmTemp * 60 * 1000 + hhTemp * 60 * 60 * 1000;
            
            // 加上位移時間
            timeStamp += microseconds;
            
            microTemp = timeStamp % 1000;
            ssTemp = Math.floor((timeStamp % 60000) / 1000);
            mmTemp = Math.floor((timeStamp % 3600000) / 60000);
            hhTemp = Math.floor((timeStamp % 216000000) / 3600000);

            // 轉為字串
            hhTemp = ("" + hhTemp).length == 1 ? ("0" + hhTemp) : ("" + hhTemp);
            mmTemp = ("" + mmTemp).length == 1 ? ("0" + mmTemp) : ("" + mmTemp);
            ssTemp = ("" + ssTemp).length == 1 ? ("0" + ssTemp) : ("" + ssTemp);
            while(("" + microTemp).length < 3){
                microTemp = "0" + microTemp;
            }
            
            // 寫回資料
            return hhTemp + ":" + mmTemp + ":" + ssTemp + "," + microTemp;
        }
    };
    var JSONFormater = {
        indentType: "\t",
        source: false,
        output: "",
        format: function() {
            if (document.getElementById("InputArea").value.length == 0) {
                alert("Empty source.");
                return;
            }
            try {
                eval("JSONFormater.source = " + document.getElementById("InputArea").value + ";");
            } catch (e) {
                alert("Invalid JSON data.");
                return;
            }
            this.indentType = this.selectedIndent();
            this.iteratorChilds(this.source, 0, false);
            this.clearTails();
            document.getElementById("OutputArea").value = this.output;
            this.output = "";
        },
        hasMembers: function(obj) {
            for (var m in obj) return true;
            return false;
        },
        isArray: function(obj) {
            return obj.constructor == Array;
        },
        isString: function(obj) {
            return obj.constructor == String;
        },
        iteratorChilds: function(obj, indent, isMember) {

            if (this.isArray(obj)) {
                this.output += "[\n";
                for (var i = 0; i < obj.length; i++) {
                    this.iteratorChilds(obj[i], indent + 1, false);
                }
                this.clearTails();
                this.output += this.currentIndent(indent);
                this.output += "],\n";
            } else if (this.hasMembers(obj)) {
                if (!isMember) this.output += this.currentIndent(indent);
                this.output += "{\n";
                for (var e in obj) {
                    this.output += this.currentIndent(indent + 1);
                    this.output += (this.isString(e) ? "\"" + e + "\"" : e) + ": ";
                    this.iteratorChilds(obj[e], indent + 1, true);
                }
                this.clearTails();
                this.output += this.currentIndent(indent);
                this.output += "},\n";
            } else {
                if (!isMember) this.output += this.currentIndent(indent);
                this.output += this.isString(obj) ? "\"" + obj + "\"" : obj;
                this.output += ",\n";
            }
        },
        currentIndent: function(ident) {
            var it = "";
            for (var i = 0; i < ident; i++) {
                it += this.indentType;
            }
            return it;
        },
        clearTails: function() {
            if (this.output.length > 2) this.output = this.output.substring(0, this.output.length - 2) + "\n";
        },
        selectedIndent: function() {
            switch (document.getElementById("indentType").value) {
                case "1":
                    return "\t";
                case "2":
                    return "  ";
                case "3":
                    return "   ";
                case "4":
                    return "    ";
                case "8":
                    return "        ";
            }
        }
    };
    window.onresize = function(){
        document.getElementById("InputArea").style.height = (document.body.offsetHeight-140)/2;
        document.getElementById("OutputArea").style.height = (document.body.offsetHeight-140)/2;
    };
    </script>
</head>
<body onload="window.onresize();">
<form>
    <div>
        <strong><a onclick="TL.changeTab(this);" tab="1" style="background-color:lightblue;">Bloger</a></strong>
        <strong><a onclick="TL.changeTab(this);" tab="8">Json Formater</a></strong>
        <strong><a onclick="TL.changeTab(this);" tab="2">SQL</a></strong>
        <strong><a onclick="TL.changeTab(this);" tab="3">URL</a></strong>
        <strong><a onclick="TL.changeTab(this);" tab="4">BASE64</a></strong>
        <strong><a onclick="TL.changeTab(this);" tab="5">NCR</a></strong>
        <strong><a onclick="TL.changeTab(this);" tab="6">Java properties</a></strong>
        <strong><a onclick="TL.changeTab(this);" tab="7">SRT</a></strong>
    </div>
    <div>
        <textarea id="InputArea" rows="7" style="width:100%;"></textarea>
    </div>
    <div>
        <textarea id="OutputArea" rows="7" style="width:100%;background-color:#eeeeee;" readonly="true"></textarea>
    </div>
    <div id="panels">
        <div panel="1">
            <h4>for Blogger post.</h4>
            <input type="button" value="Translate" onclick="TL.blogger();" />
            <input type="button" value="Restore" onclick="TL.blogger(true);" />
            <input type="button" value="Clear" onclick="TL.clear();" />
            <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
        </div>
        <div panel="8" style="display:none;">
            <h4>Json Formater</h4>
            <input type="button" value="format" onclick="JSONFormater.format();" />
            <select id="indentType">
                <option value="1" selected="selected">indent with a tab character</option>
                <option value="2">indent with 2 spaces</option>
                <option value="3">indent with 3 spaces</option>
                <option value="4">indent with 4 spaces</option>
                <option value="8">indent with 8 spaces</option>
            </select>
            <input type="button" value="Clear" onclick="TL.clear();" />
            <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
        </div>
        <div panel="2" style="display:none;">
            <h4>for SQL statement.</h4>
            <input type="button" value="Translate" onclick="TL.sql();" />
            <input type="button" value="Clear" onclick="TL.clear();" />
            <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
        </div>
        <div panel="3" style="display:none;">
            <h4>for URL encode/decode.</h4>
            <input type="button" value="Translate" onclick="TL.url();" />
            <input type="button" value="Restore" onclick="TL.url(true);" />
            <input type="button" value="Clear" onclick="TL.clear();" />
            <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
        </div>
        <div panel="4" style="display:none;">
            <h4>for BASE64 encode/decode.</h4>
            <input type="button" value="Translate" onclick="TL.base64();" />
            <input type="button" value="Restore" onclick="TL.base64(true);" />
            <input type="button" value="Clear" onclick="TL.clear();" />
            <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
        </div>
        <div panel="5" style="display:none;">
            <h4>Numeric Character Reference (letter code less than 128 won't be translated.)</h4>
            <input type="button" value="Translate" onclick="TL.ncr();" />
            <input type="button" value="Restore" onclick="TL.ncr(true);" />
            <input type="button" value="Clear" onclick="TL.clear();" />
            <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
        </div>
        <div panel="6" style="display:none;">
            <h4>for Java properties file</h4>
            <input type="button" value="Translate" onclick="TL.properties();" />
            <input type="button" value="Restore" onclick="TL.properties(true);" />
            <input type="button" value="Clear" onclick="TL.clear();" />
            <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
        </div>
        <div panel="7" style="display:none;">
            <h4>time control</h4>
            <input type="text" id="addtime" />
            <input type="button" value="Translate" />
            <input type="button" value="Clear" onclick="TL.clear();" />
            <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
        </div>
        <p id="timer">
        </p>
    </div>
</form>
</body>
</html>
foreach bug in i.e.

There is a curious probelm between for and foreach.
When I get a collection by 'document.getElementsByTagName', and iterate it's items.
In i.e., javascript will get undefined object created by server code when using foreach. why?

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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>Test foreach</title>

    <script type="text/javascript" language="javascript">
    function newRow(){
        var container = document.getElementById("container");
        var input = document.createElement("input");
        var div = document.createElement("div");
        
        input.type = "text";
        input.name = "foption";
        input.value = (new Date()).toGMTString();
        
        div.appendChild(input);
        container.appendChild(div);
    }
    function foreachResult(){
        var result = document.getElementById("result");
        var inputs = document.getElementsByTagName("input");
        var div = false;
        while(result.firstChild) result.removeChild(result.firstChild);
        
        for(var i in inputs){
            if(!inputs[i] || inputs[i].name != "foption") continue;
            div = document.createElement("div");
            div.appendChild(document.createTextNode(inputs[i] ? inputs[i].value : "undefined inputs?"));
            result.appendChild(div);
        }
    }
    function forResult(){
        var result = document.getElementById("result");
        var inputs = document.getElementsByTagName("input");
        var div = false;
        while(result.firstChild) result.removeChild(result.firstChild);
        
        for(var i = 0; i < inputs.length; i++){
            if(!inputs[i] || inputs[i].name != "foption") continue;
            div = document.createElement("div");
            div.appendChild(document.createTextNode(inputs[i] ? inputs[i].value : "undefined inputs?"));
            result.appendChild(div);
        }
    }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </cc1:ToolkitScriptManager>
    <table border="1">
        <tr>
            <td>
                <div id="container">
                    <input type="button" onclick="newRow();" value="加入textbox" /><br />
                    <input type="button" onclick="foreachResult();" value="用利foreach列出name為foption的textbox" /><br />
                    <input type="button" onclick="forResult();" value="用利for列出name為foption的textbox" />
                    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
                </div>
            </td>
            <td style="width: 300px; vertical-align: top;">
                <div id="result">
                    &nbsp;
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
Default.aspx.cs
using System;
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;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 15; i++)
        {
            sb.AppendFormat("<div><input type=\"text\" name=\"foption\" value=\"{0}\" /></div>", i);
        }
        Literal1.Text = sb.ToString();
    }
}
Get primary key after insert statement
sql server
MySQL
INSERT INTO Table(Column1, Column2, Column3) VALUES(Value1, Value2, Value3);
SELECT @@IDENTITY
CAPTCHA
ImageValidator.ashx
<%@ WebHandler Language="C#" Class="ImageValidator" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;

public class ImageValidator : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        // character for validating
        string[] code = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        string strRd = string.Empty;

        Random random = new Random(unchecked((int)DateTime.Now.Ticks));
        Bitmap bmp = new Bitmap(80, 25);  // create empty image
        Graphics graphic = Graphics.FromImage(bmp);
        Font font = new Font("Verdana", 14, FontStyle.Italic);

        for (int i = 0; i < 5; i++)       // random a validate string
        {
            strRd += code[random.Next(35)];
        }

        graphic.Clear(Color.White);    //設定背景顏色
        for (int i = 1; i <= 10; i++)
        {
            graphic.DrawLine(GetPen(i), random.Next(80), 0, random.Next(80), 30); // ↘
        }

        graphic.DrawString(strRd, font, Brushes.Black, 0, 0);
        for (int i = 0; i <= 50; i++)            //亂數產生霧點,擾亂機器人辨別 
        {
            int RandPixelX = random.Next(0, 80);
            int RandPixelY = random.Next(0, 25);
            bmp.SetPixel(RandPixelX, RandPixelY, Color.Blue);
        }


        context.Session["ValidateCode"] = strRd;        //將驗證碼存入Session以便稍後進行驗證 
        //context.Response.Cookies.Add(new HttpCookie("ValidateCode", strRd)); //將驗證碼存入cookie以便稍後進行驗證
        bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
    }

    #region getPen 取得筆刷的設定顏色
    protected Pen GetPen(int i)
    {
        Pen PenLine = new Pen(Brushes.Red, 1);//實體化筆刷並設定顏色、大小(畫X,Y軸用)
        switch (i)
        {
            case 1:
                PenLine = new Pen(Brushes.Red, 1);
                break;
            case 2:

                PenLine = new Pen(Brushes.BlueViolet, 1);
                break;
            case 3:
                PenLine = new Pen(Brushes.GreenYellow, 1);
                break;
            case 4:
                PenLine = new Pen(Brushes.Gold, 1);
                break;
            case 5:
                PenLine = new Pen(Brushes.MediumBlue, 1);
                break;
            case 6:
                PenLine = new Pen(Brushes.MintCream, 1);
                break;
            case 7:
                PenLine = new Pen(Brushes.Pink, 1);
                break;
            case 8:
                PenLine = new Pen(Brushes.Purple, 1);
                break;
            case 9:
                PenLine = new Pen(Brushes.HotPink, 1);
                break;
            case 10:
                PenLine = new Pen(Brushes.Chocolate, 1);
                break;
        } return PenLine;
    }
    #endregion

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>未命名頁面</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" runat="server" ImageUrl="~/ImageValidator.ashx" />
    </div>
    </form>
</body>
</html>
Generate KeyStore and signed applet
in command line:
keytool -genkey -keystore myKeystore -alias myself 
//建立你的public key 
 
keytool -selfcert -alias myself -keystore myKeystore 
//由你的pubilc key 建立一個 private key 
 
jarsigner -keystore myKeystore test.jar myself 
//將你的jar檔用你的private key來簽章 
Paging
Sql server
Assume:
@PageSize is the row counts displayed on page
@CurrentPage is the page number
SELECT TOP @PageSize * FROM Table WHERE ID NOT IN
    (SELECT TOP @PageSize*@CurrentPage ID FROM Table ORDER BY ID DESC)
ORDER BY ID DESC
Oracle
Assume:
@MaxRowNum means the max row to query
@MinRowNum means the min row to query
SELECT * FROM 
    (SELECT rownum, * FROM
        (SELECT * FROM Table WHERE SomeColumn = Something ORDER BY SomeColumns)
    WHERE rownum <= @MaxRowNum)
WHERE rownum >= @MinRowNum
↑better performance on visit first serval pages
SELECT * FROM Table WHERE rowind IN
    (SELECT rid FROM
        (SELECT rownum rno, rowid rid FROM
            (SELECT rowid FROM Table WHERE SomeColumn = Something ORDER BY SomeColumns)
        WHERE rownum <= @MaxRowNum)
    WHERE rno >= @MinRowNum)
↑better performance on higher page numbers
SELECT * FROM 
    (SELECT owner, table_name, row_number() OVER(ORDER BY table_name) rownumber FROM dba_tables)
WHERE rownumber >= @MinRowNum AND rownumber <= @MaxRowNum
Read exif using metadata extraction
metadata extraction version : 2.3.1
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;

import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifDirectory;
import com.drew.metadata.exif.ExifReader;

public class EXIFReader {

    public static void printExif(String fileName) throws FileNotFoundException {
        File f = new File(fileName);
        try {
            ExifReader er = new ExifReader(f);
            Metadata exif = er.extract();
            Iterator itr = exif.getDirectoryIterator();
            while (itr.hasNext()) {
                Directory directory = (Directory) itr.next();

                System.out.println("EXIF版本:" + directory.getString(ExifDirectory.TAG_EXIF_VERSION));
                System.out.println("相機品牌:" + directory.getString(ExifDirectory.TAG_MAKE));
                System.out.println("像機號碼:" + directory.getString(ExifDirectory.TAG_MODEL));
                System.out.println("光 圈 值:" + directory.getString(ExifDirectory.TAG_FNUMBER));
                System.out.println("快 門:" + directory.getString(ExifDirectory.TAG_EXPOSURE_TIME));
                System.out.println("感 光 度:" + directory.getString(ExifDirectory.TAG_ISO_EQUIVALENT));
                System.out.println("軟 件:" + directory.getString(ExifDirectory.TAG_SOFTWARE));
                System.out.println("原始拍攝時間:" + directory.getString(ExifDirectory.TAG_DATETIME_ORIGINAL));
                System.out.println("數字化時間:" + directory.getString(ExifDirectory.TAG_DATETIME_DIGITIZED));
                System.out.println("方 向:" + directory.getString(ExifDirectory.TAG_ORIENTATION));
                System.out.println("圖片寬度:" + directory.getString(ExifDirectory.TAG_EXIF_IMAGE_WIDTH));
                System.out.println("圖片高度:" + directory.getString(ExifDirectory.TAG_EXIF_IMAGE_HEIGHT));
                System.out.println("水平分辨率:" + directory.getString(ExifDirectory.TAG_X_RESOLUTION));
                System.out.println("垂直分辨率:" + directory.getString(ExifDirectory.TAG_Y_RESOLUTION));
                System.out.println("垂直分辨率:" + directory.getString(ExifDirectory.TAG_EXPOSURE_BIAS));
                break;
            }
        } catch (JpegProcessingException e) {
            System.err.println("not jpeg file");
        }
    }
}
LOB column read/write in Oracle
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.jdbc.driver.OracleResultSet;
import oracle.sql.CLOB;

public class OracleLobType {

    public static void insertLOB() throws ClassNotFoundException, SQLException, IOException {

        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection("ConnectionString");

        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "";

        conn.setAutoCommit(false);
        sql = "INSERT INTO Table(id, clobColumn) VALUES(?, empty_clob())";
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, 1);
        pstmt.executeUpdate();
        pstmt.close();

        pstmt = null;
        sql = "SELECT clobColumn FROM Table WHERE id = 1 FOR UPDATE";
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();

        CLOB clobValue = null;
        while (rs.next()) {
            clobValue = (CLOB) rs.getClob("clobColumn");
        }
        Writer wr = clobValue.getCharacterOutputStream();
        wr.write("clob data");
        wr.flush();
        wr.close();

        rs.close();
        pstmt.close();
        conn.commit();
        conn.close();

    }

    public static void getLOG() throws ClassNotFoundException, SQLException {

        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection("ConnectionString");

        String sql = "";
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        sql = "SELECT clobColumn FROM Table WHERE id = 1";
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();

        CLOB clobValue = null;
        while (rs.next()) {
            OracleResultSet ors = (OracleResultSet) rs;
            clobValue = (CLOB) ors.getCLOB("clobColumn");
        }

        String value = "";
        if (clobValue != null && clobValue.length() > 0)
            // clobValue.stringValue();
            value = clobValue.getSubString(1, (int) clobValue.length());

        rs.close();
        pstmt.close();
        conn.close();

    }
}