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
Response wrapper
ResponseWrapper.cs
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.HtmlControls;
  9. using System.Web.UI.WebControls;
  10. using System.Web.UI.WebControls.WebParts;
  11. using System.Xml.Linq;
  12. using System.IO;
  13. using System.Text.RegularExpressions;
  14.  
  15. /// <summary>
  16. /// ResponseWrapper 的摘要描述
  17. /// </summary>
  18. public class ResponseWrapper : Stream
  19. {
  20.     private Stream _stream;
  21.  
  22.     public ResponseWrapper(Stream stream)
  23.     {
  24.         this._stream = stream;
  25.     }
  26.     protected Stream BaseStream { get { return this._stream; } }
  27.     public override bool CanRead { get { return false; } }
  28.     public override bool CanSeek { get { return false; } }
  29.     public override bool CanWrite { get { return this._stream.CanWrite; } }
  30.     public override long Length { get { throw new NotSupportedException(); } }
  31.     public override long Position
  32.     {
  33.         get { throw new NotSupportedException(); }
  34.         set { throw new NotSupportedException(); }
  35.     }
  36.  
  37.     public override long Seek(long offset, System.IO.SeekOrigin direction)
  38.     {
  39.         throw new NotSupportedException();
  40.     }
  41.  
  42.     public override void SetLength(long length)
  43.     {
  44.         throw new NotSupportedException();
  45.     }
  46.  
  47.     public override void Close()
  48.     {
  49.         this._stream.Close();
  50.     }
  51.  
  52.     public override void Flush()
  53.     {
  54.         this._stream.Flush();
  55.     }
  56.  
  57.     public override int Read(byte[] buffer, int offset, int count)
  58.     {
  59.         throw new NotSupportedException();
  60.     }
  61.  
  62.     public override void Write(byte[] buffer, int offset, int count)
  63.     {
  64.         string outputData = System.Text.Encoding.UTF8.GetString(buffer);
  65.  
  66.         outputData = Regex.Replace(outputData, ">\\s+<", "><", RegexOptions.Multiline);  // replace all white space between tags
  67.         //outputData = Regex.Replace(outputData, "\\s\\s+", " ", RegexOptions.Singleline);  // replace all white space to single one
  68.  
  69.         byte[] outData = System.Text.Encoding.UTF8.GetBytes(outputData);
  70.         this._stream.Write(outData, 0, outData.GetLength(0));
  71.  
  72.     }
  73. }
Global.asax
  1. <%@ Application Language="C#" %>
  2.  
  3. <script RunAt="server">
  4.  
  5.     void Application_Start(object sender, EventArgs e)
  6.     {
  7.         // 應用程式啟動時執行的程式碼
  8.  
  9.     }
  10.  
  11.     void Application_End(object sender, EventArgs e)
  12.     {
  13.         //  應用程式關閉時執行的程式碼
  14.  
  15.     }
  16.  
  17.     void Application_Error(object sender, EventArgs e)
  18.     {
  19.         // 發生未處理錯誤時執行的程式碼
  20.  
  21.     }
  22.  
  23.     void Session_Start(object sender, EventArgs e)
  24.     {
  25.         // 啟動新工作階段時執行的程式碼
  26.  
  27.     }
  28.  
  29.     void Session_End(object sender, EventArgs e)
  30.     {
  31.         // 工作階段結束時執行的程式碼。 
  32.         // 注意: 只有在 Web.config 檔將 sessionstate 模式設定為 InProc 時,
  33.         // 才會引發 Session_End 事件。如果將工作階段模式設定為 StateServer 
  34.         // 或 SQLServer,就不會引發這個事件。
  35.  
  36.     }
  37.  
  38.     protected void Application_BeginRequest(object sender, EventArgs e)
  39.     {
  40.         if (this.Response.ContentType == "text/html" // 限定輸出類型
  41.             && this.Request.Url.AbsolutePath.EndsWith(".aspx") // 限定請求的url
  42.             && this.Request.HttpMethod == "GET") // 限定httpmethod
  43.             this.Response.Filter = new ResponseWrapper(this.Response.Filter);
  44.     }
  45.        
  46. </script>
Translating 1.3
  1. <html>
  2. <head>
  3.     <title>Translating 1.1</title>
  4.     <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  5.     <style type="text/css">
  6.     strong a{padding-left:7px; padding-right:7px; border:1px outset; cursor:pointer;}
  7.     </style>
  8.     <script type="text/javascript">
  9.     var TL = {
  10.         executingTime : false,
  11.         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"],
  12.         keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  13.         changeTab : function(obj){
  14.             var strongs = document.getElementsByTagName("strong");
  15.             for(var i = 0; i < strongs.length; i++){
  16.                 strongs[i].firstChild.style.backgroundColor = "transparent";
  17.             }
  18.             obj.style.backgroundColor = "lightblue";
  19.             
  20.             var panels = document.getElementById("panels");
  21.             for(var i = 0; i < panels.childNodes.length; i++){
  22.                 if(panels.childNodes[i].nodeType == 1 && panels.childNodes[i].tagName == "DIV"){
  23.                     panels.childNodes[i].style.display = panels.childNodes[i].getAttribute("panel") == obj.getAttribute("tab") ? "block" : "none";
  24.                 }
  25.             }
  26.         },
  27.         time : function(end){
  28.             if(end){
  29.                 if(this.executingTime){
  30.                     var now = new Date();
  31.                     var ms = now.getTime() - this.executingTime.getTime();
  32.                     var time = Math.floor((ms/60000.0)%60) >= 1 ? Math.floor((ms/60000.0)%60) + " minute(s)" : "";
  33.                     time += Math.floor((ms/1000.0)%60) >= 1 ? Math.floor((ms/1000.0)%60) + " second(s) " : (time.length > 0 ? " 0 second " : "");
  34.                     time += ms%1000 + " miliseconds";
  35.                     document.getElementById("timer").innerHTML = time;
  36.                 }else{
  37.                     document.getElementById("timer").innerHTML = "Error time slip.";
  38.                 }
  39.             }else{
  40.                 this.executingTime = new Date();
  41.             }
  42.         },
  43.         clear : function(){
  44.             document.getElementById("InputArea").value = "";
  45.             document.getElementById("OutputArea").value = "";
  46.         },
  47.         CopyToClipboard : function(){
  48.             if (window.clipboardData){
  49.                 window.clipboardData.setData("Text", document.getElementById("OutputArea").value);
  50.             }else if (window.netscape){
  51.                 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
  52.                 var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
  53.                 if (!clip) return;
  54.                 var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
  55.                 if (!trans) return;
  56.                 trans.addDataFlavor('text/unicode');
  57.                 var str = new Object();
  58.                 var len = new Object();
  59.                 var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
  60.                 var copytext=document.getElementById("OutputArea").value;
  61.                 str.data=copytext;
  62.                 trans.setTransferData("text/unicode",str,copytext.length*2);
  63.                 var clipid=Components.interfaces.nsIClipboard;
  64.                 if (!clip) return false;
  65.                 clip.setData(trans,null,clipid.kGlobalClipboard);
  66.             }else{
  67.                 return false;
  68.             }
  69.             return false;
  70.         },
  71.         blogger : function(reverse){
  72.             this.time(false);
  73.             if(reverse){
  74.                 var input = document.getElementById("InputArea").value;
  75.                 var chars = [{s:"\t",r:"&nbsp;&nbsp;&nbsp;&nbsp;"},{s:" ",r:"&nbsp;"},{s:"<",r:"&lt;"},{s:">",r:"&gt;"},{s:"&",r:"&amp;"}];
  76.                 var temp = input;
  77.                 for(var i in chars){
  78.                     while((input = input.replace(chars[i].r, chars[i].s)) != temp) temp = input;
  79.                 }
  80.                 document.getElementById("OutputArea").value = input;
  81.             }else{
  82.                 var input = document.getElementById("InputArea").value.split("");
  83.                 var chars = [{s:"&",r:"&amp;"},{s:" ",r:"&nbsp;"},{s:"\t",r:"&nbsp;&nbsp;&nbsp;&nbsp;"},{s:"<",r:"&lt;"},{s:">",r:"&gt;"}];
  84.                 for(var i = 0; i < input.length; i++){
  85.                     for(var j in chars) input[i] = input[i].replace(chars[j].s, chars[j].r);
  86.                 }
  87.                 document.getElementById("OutputArea").value = input.join("");            
  88.             }
  89.             this.time(true);
  90.         },
  91.         sql : function(){
  92.             this.time(false);
  93.             var input = document.getElementById("InputArea").value;
  94.             var wd =false;
  95.             var mg = false;
  96.             this.TSQLReverseWord = this.TSQLReverseWord.sort();
  97.             for(var i in this.TSQLReverseWord){
  98.                 wd = this.TSQLReverseWord[i];
  99.                 var pattern = new RegExp("[\\D\\W]?(" + wd + ")[\\D\\W]?", "i");
  100.                 mg = input.match(pattern);
  101.                 if(mg){
  102.                     for(var j = 0; j < mg.length; j++){
  103.                         input = input.replace(mg[j].toString(), mg[j].toString().toUpperCase());
  104.                     }
  105.                 }
  106.             }
  107.             document.getElementById("OutputArea").value = input;
  108.             this.time(true);
  109.         },
  110.         url : function(reverse){
  111.             this.time(false);
  112.             if(reverse){
  113.                 document.getElementById("OutputArea").value = decodeURI(document.getElementById("InputArea").value);
  114.             }else{
  115.                 document.getElementById("OutputArea").value = encodeURI(document.getElementById("InputArea").value);
  116.             }
  117.             this.time(true);
  118.         },
  119.         base64 : function(reverse){
  120.             this.time(false);
  121.             var input = document.getElementById("InputArea").value;
  122.             if(reverse){
  123.                 debugger;
  124.                 var output = "";
  125.                 var chr1, chr2, chr3;
  126.                 var enc1, enc2, enc3, enc4;
  127.                 var i = 0;
  128.  
  129.                 // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  130.                 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  131.  
  132.                 do {
  133.                     enc1 = this.keyStr.indexOf(input.charAt(i++));
  134.                     enc2 = this.keyStr.indexOf(input.charAt(i++));
  135.                     enc3 = this.keyStr.indexOf(input.charAt(i++));
  136.                     enc4 = this.keyStr.indexOf(input.charAt(i++));
  137.  
  138.                     chr1 = (enc1 << 2) | (enc2 >> 4);
  139.                     chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  140.                     chr3 = ((enc3 & 3) << 6) | enc4;
  141.  
  142.                     output = output + String.fromCharCode(chr1);
  143.  
  144.                     if (enc3 != 64) {
  145.                         output = output + String.fromCharCode(chr2);
  146.                     }
  147.                     if (enc4 != 64) {
  148.                         output = output + String.fromCharCode(chr3);
  149.                     }
  150.                 } while (< input.length);
  151.                 document.getElementById("OutputArea").value = this._utf8_decode(output);
  152.             }else{
  153.                 input = this._utf8_encode(input);
  154.                 var output = "";
  155.                 var chr1, chr2, chr3;
  156.                 var enc1, enc2, enc3, enc4;
  157.                 var i = 0;
  158.  
  159.                 do {
  160.                     chr1 = input.charCodeAt(i++);
  161.                     chr2 = input.charCodeAt(i++);
  162.                     chr3 = input.charCodeAt(i++);
  163.  
  164.                     enc1 = chr1 >> 2;
  165.                     enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  166.                     enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  167.                     enc4 = chr3 & 63;
  168.  
  169.                     if (isNaN(chr2)) {
  170.                         enc3 = enc4 = 64;
  171.                     } else if (isNaN(chr3)) {
  172.                         enc4 = 64;
  173.                     }
  174.  
  175.                     output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + 
  176.                     this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4);
  177.                 } while (< input.length);
  178.                 document.getElementById("OutputArea").value = output;
  179.             }
  180.             this.time(true);
  181.         },
  182.         _utf8_encode : function (string) {
  183.             string = string.replace(/\r\n/g,"\n");
  184.             var utftext = "";
  185.             for (var n = 0; n < string.length; n++) {
  186.                 var c = string.charCodeAt(n);
  187.                 if (< 128) {
  188.                     utftext += String.fromCharCode(c);
  189.                 } else if((> 127) && (< 2048)) {
  190.                     utftext += String.fromCharCode((>> 6) | 192);
  191.                     utftext += String.fromCharCode((& 63) | 128);
  192.                 } else {
  193.                     utftext += String.fromCharCode((>> 12) | 224);
  194.                     utftext += String.fromCharCode(((>> 6) & 63) | 128);
  195.                     utftext += String.fromCharCode((& 63) | 128);
  196.                 }
  197.             }
  198.             return utftext;
  199.         },
  200.         _utf8_decode : function (utftext) {
  201.             var string = "";
  202.             var i = 0;
  203.             var c = c1 = c2 = 0;
  204.             while ( i < utftext.length ) {
  205.                 c = utftext.charCodeAt(i);
  206.                 if (< 128) {
  207.                     string += String.fromCharCode(c);
  208.                     i++;
  209.                 } else if((> 191) && (< 224)) {
  210.                     c2 = utftext.charCodeAt(i+1);
  211.                     string += String.fromCharCode(((& 31) << 6) | (c2 & 63));
  212.                     i += 2;
  213.                 } else {
  214.                     c2 = utftext.charCodeAt(i+1);
  215.                     c3 = utftext.charCodeAt(i+2);
  216.                     string += String.fromCharCode(((& 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  217.                     i += 3;
  218.                 }
  219.             }
  220.             return string;
  221.         },
  222.         ncr : function(reverse){
  223.             this.time(false);
  224.             if(reverse){
  225.                 var input = document.getElementById("InputArea").value;
  226.                 var ncr = input.match(/&#x([\da-fA-F]+);/g);
  227.                 var unicode = false;
  228.                 for(var i = 0; i < ncr.length; i++){
  229.                     unicode = ncr[i].toString().replace(/&#x([\da-fA-F]+);/, '$1');
  230.                     input = input.replace(ncr[i].toString(), String.fromCharCode(parseInt(unicode, 16)));
  231.                 }
  232.                 document.getElementById("OutputArea").value = input;
  233.             }else{
  234.                 var input = document.getElementById("InputArea").value.split("");
  235.                 for(var i = 0; i < input.length; i++){
  236.                     if(input[i].charCodeAt(0) < 128) continue;
  237.                     input[i] = "&#x" + input[i].charCodeAt(0).toString(16) + ";";
  238.                 }
  239.                 document.getElementById("OutputArea").value = input.join("");
  240.             }
  241.             this.time(true);
  242.         },
  243.         properties : function(reverse){
  244.             this.time(false);
  245.             if(reverse){
  246.                 var input = document.getElementById("InputArea").value;
  247.                 var prop = input.match(/[\\]u([\da-fA-F]+)/g);
  248.                 var unicode = false;
  249.                 for(var i = 0; i < prop.length; i++){
  250.                     unicode = prop[i].toString().replace(/[\\]u([\da-fA-F]+)/, '$1');
  251.                     input = input.replace(prop[i].toString(), String.fromCharCode(parseInt(unicode, 16)));
  252.                 }
  253.                 document.getElementById("OutputArea").value = input;
  254.             }else{
  255.                 var lines = document.getElementById("InputArea").value.split("\n");
  256.                 //alert(lines.length);
  257.                 var out = "";
  258.                 var chars = [];
  259.                 for(var n in lines){
  260.                     //alert(line);
  261.                     chars = lines[n].split("");
  262.                     if(chars[0] != "#" && chars[0] != "!")  // continue;  // for comment
  263.                     for(var i = 0; i < chars.length; i++){
  264.                         if(chars[i].charCodeAt(0) < 128) continue;
  265.                         chars[i] = chars[i].charCodeAt(0) > 127 ? "\\u" + chars[i].charCodeAt(0).toString(16) : chars[i];
  266.                     }
  267.                     out += chars.join("");
  268.                 }
  269.                 
  270.                 document.getElementById("OutputArea").value = out;
  271.             }
  272.             this.time(true);
  273.         },
  274.         srt : function(){
  275.             this.time(false);
  276.             var hh, mm, ss, micro;
  277.             var input = document.getElementById("InputArea").value.split("\n");
  278.             var addtime = document.getElementById("addtime").value;
  279.             try{
  280.                 microseconds = parseInt(microseconds);
  281.             }catch(e){
  282.                 alert(e);
  283.                 return;
  284.             }
  285.             var arrow = " --> ";
  286.             var times;
  287.             for(= 0; i < content.length; i++){
  288.                 if(content[i].indexOf(arrow) > -1){
  289.                     times = content[i].split(arrow);
  290.  
  291.                     // =====開始時間=====
  292.                     times[0] = this.moveTimeStamp(times[0], microseconds);
  293.  
  294.                     // =====結束時間=====
  295.                     times[1] = this.moveTimeStamp(times[1], microseconds);
  296.  
  297.                     content[i] = times.join(arrow);
  298.                 }
  299.             }
  300.             document.getElementById("OutputArea").value = input.join("\n");
  301.             this.time(true);
  302.         },
  303.         moveTimeStamp : function(time, microseconds){
  304.             hhTemp = time.substring(0,2);
  305.             mmTemp = time.substring(3,5);
  306.             ssTemp = time.substring(6,8);
  307.             microTemp = time.substring(9,12);
  308.             
  309.             // 去掉字首的 0 (原因 : 在parseInt時會出錯)
  310.             hhTemp = hhTemp.substring(0,1) == "0" ? hhTemp.substring(1, hhTemp.length) : hhTemp;
  311.             mmTemp = mmTemp.substring(0,1) == "0" ? mmTemp.substring(1, mmTemp.length) : mmTemp;
  312.             ssTemp = ssTemp.substring(0,1) == "0" ? ssTemp.substring(1, ssTemp.length) : ssTemp;
  313.             while(microTemp.substring(0,1) == "0" && microTemp.length > 1){
  314.                 microTemp = microTemp.substring(1, microTemp.length);
  315.             }
  316.             
  317.             hhTemp = parseInt(hhTemp);
  318.             mmTemp = parseInt(mmTemp);
  319.             ssTemp = parseInt(ssTemp);
  320.             microTemp = parseInt(microTemp);
  321.             //換成 timeStamp計算
  322.             timeStamp = microTemp + ssTemp * 1000 + mmTemp * 60 * 1000 + hhTemp * 60 * 60 * 1000;
  323.             
  324.             // 加上位移時間
  325.             timeStamp += microseconds;
  326.             
  327.             microTemp = timeStamp % 1000;
  328.             ssTemp = Math.floor((timeStamp % 60000) / 1000);
  329.             mmTemp = Math.floor((timeStamp % 3600000) / 60000);
  330.             hhTemp = Math.floor((timeStamp % 216000000) / 3600000);
  331.  
  332.             // 轉為字串
  333.             hhTemp = ("" + hhTemp).length == 1 ? ("0" + hhTemp) : ("" + hhTemp);
  334.             mmTemp = ("" + mmTemp).length == 1 ? ("0" + mmTemp) : ("" + mmTemp);
  335.             ssTemp = ("" + ssTemp).length == 1 ? ("0" + ssTemp) : ("" + ssTemp);
  336.             while(("" + microTemp).length < 3){
  337.                 microTemp = "0" + microTemp;
  338.             }
  339.             
  340.             // 寫回資料
  341.             return hhTemp + ":" + mmTemp + ":" + ssTemp + "," + microTemp;
  342.         }
  343.     };
  344.     var JSONFormater = {
  345.         indentType: "\t",
  346.         source: false,
  347.         output: "",
  348.         format: function() {
  349.             if (document.getElementById("InputArea").value.length == 0) {
  350.                 alert("Empty source.");
  351.                 return;
  352.             }
  353.             try {
  354.                 eval("JSONFormater.source = " + document.getElementById("InputArea").value + ";");
  355.             } catch (e) {
  356.                 alert("Invalid JSON data.");
  357.                 return;
  358.             }
  359.             this.indentType = this.selectedIndent();
  360.             this.iteratorChilds(this.source, 0, false);
  361.             this.clearTails();
  362.             document.getElementById("OutputArea").value = this.output;
  363.             this.output = "";
  364.         },
  365.         hasMembers: function(obj) {
  366.             for (var m in obj) return true;
  367.             return false;
  368.         },
  369.         isArray: function(obj) {
  370.             return obj.constructor == Array;
  371.         },
  372.         isString: function(obj) {
  373.             return obj.constructor == String;
  374.         },
  375.         iteratorChilds: function(obj, indent, isMember) {
  376.  
  377.             if (this.isArray(obj)) {
  378.                 this.output += "[\n";
  379.                 for (var i = 0; i < obj.length; i++) {
  380.                     this.iteratorChilds(obj[i], indent + 1, false);
  381.                 }
  382.                 this.clearTails();
  383.                 this.output += this.currentIndent(indent);
  384.                 this.output += "],\n";
  385.             } else if (this.hasMembers(obj)) {
  386.                 if (!isMember) this.output += this.currentIndent(indent);
  387.                 this.output += "{\n";
  388.                 for (var e in obj) {
  389.                     this.output += this.currentIndent(indent + 1);
  390.                     this.output += (this.isString(e) ? "\"" + e + "\"" : e) + ": ";
  391.                     this.iteratorChilds(obj[e], indent + 1, true);
  392.                 }
  393.                 this.clearTails();
  394.                 this.output += this.currentIndent(indent);
  395.                 this.output += "},\n";
  396.             } else {
  397.                 if (!isMember) this.output += this.currentIndent(indent);
  398.                 this.output += this.isString(obj) ? "\"" + obj + "\"" : obj;
  399.                 this.output += ",\n";
  400.             }
  401.         },
  402.         currentIndent: function(ident) {
  403.             var it = "";
  404.             for (var i = 0; i < ident; i++) {
  405.                 it += this.indentType;
  406.             }
  407.             return it;
  408.         },
  409.         clearTails: function() {
  410.             if (this.output.length > 2) this.output = this.output.substring(0, this.output.length - 2) + "\n";
  411.         },
  412.         selectedIndent: function() {
  413.             switch (document.getElementById("indentType").value) {
  414.                 case "1":
  415.                     return "\t";
  416.                 case "2":
  417.                     return "  ";
  418.                 case "3":
  419.                     return "   ";
  420.                 case "4":
  421.                     return "    ";
  422.                 case "8":
  423.                     return "        ";
  424.             }
  425.         }
  426.     };
  427.     window.onresize = function(){
  428.         document.getElementById("InputArea").style.height = (document.body.offsetHeight-140)/2;
  429.         document.getElementById("OutputArea").style.height = (document.body.offsetHeight-140)/2;
  430.     };
  431.     </script>
  432. </head>
  433. <body onload="window.onresize();">
  434. <form>
  435.     <div>
  436.         <strong><a onclick="TL.changeTab(this);" tab="1" style="background-color:lightblue;">Bloger</a></strong>
  437.         <strong><a onclick="TL.changeTab(this);" tab="8">Json Formater</a></strong>
  438.         <strong><a onclick="TL.changeTab(this);" tab="2">SQL</a></strong>
  439.         <strong><a onclick="TL.changeTab(this);" tab="3">URL</a></strong>
  440.         <strong><a onclick="TL.changeTab(this);" tab="4">BASE64</a></strong>
  441.         <strong><a onclick="TL.changeTab(this);" tab="5">NCR</a></strong>
  442.         <strong><a onclick="TL.changeTab(this);" tab="6">Java properties</a></strong>
  443.         <strong><a onclick="TL.changeTab(this);" tab="7">SRT</a></strong>
  444.     </div>
  445.     <div>
  446.         <textarea id="InputArea" rows="7" style="width:100%;"></textarea>
  447.     </div>
  448.     <div>
  449.         <textarea id="OutputArea" rows="7" style="width:100%;background-color:#eeeeee;" readonly="true"></textarea>
  450.     </div>
  451.     <div id="panels">
  452.         <div panel="1">
  453.             <h4>for Blogger post.</h4>
  454.             <input type="button" value="Translate" onclick="TL.blogger();" />
  455.             <input type="button" value="Restore" onclick="TL.blogger(true);" />
  456.             <input type="button" value="Clear" onclick="TL.clear();" />
  457.             <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
  458.         </div>
  459.         <div panel="8" style="display:none;">
  460.             <h4>Json Formater</h4>
  461.             <input type="button" value="format" onclick="JSONFormater.format();" />
  462.             <select id="indentType">
  463.                 <option value="1" selected="selected">indent with a tab character</option>
  464.                 <option value="2">indent with 2 spaces</option>
  465.                 <option value="3">indent with 3 spaces</option>
  466.                 <option value="4">indent with 4 spaces</option>
  467.                 <option value="8">indent with 8 spaces</option>
  468.             </select>
  469.             <input type="button" value="Clear" onclick="TL.clear();" />
  470.             <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
  471.         </div>
  472.         <div panel="2" style="display:none;">
  473.             <h4>for SQL statement.</h4>
  474.             <input type="button" value="Translate" onclick="TL.sql();" />
  475.             <input type="button" value="Clear" onclick="TL.clear();" />
  476.             <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
  477.         </div>
  478.         <div panel="3" style="display:none;">
  479.             <h4>for URL encode/decode.</h4>
  480.             <input type="button" value="Translate" onclick="TL.url();" />
  481.             <input type="button" value="Restore" onclick="TL.url(true);" />
  482.             <input type="button" value="Clear" onclick="TL.clear();" />
  483.             <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
  484.         </div>
  485.         <div panel="4" style="display:none;">
  486.             <h4>for BASE64 encode/decode.</h4>
  487.             <input type="button" value="Translate" onclick="TL.base64();" />
  488.             <input type="button" value="Restore" onclick="TL.base64(true);" />
  489.             <input type="button" value="Clear" onclick="TL.clear();" />
  490.             <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
  491.         </div>
  492.         <div panel="5" style="display:none;">
  493.             <h4>Numeric Character Reference (letter code less than 128 won't be translated.)</h4>
  494.             <input type="button" value="Translate" onclick="TL.ncr();" />
  495.             <input type="button" value="Restore" onclick="TL.ncr(true);" />
  496.             <input type="button" value="Clear" onclick="TL.clear();" />
  497.             <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
  498.         </div>
  499.         <div panel="6" style="display:none;">
  500.             <h4>for Java properties file</h4>
  501.             <input type="button" value="Translate" onclick="TL.properties();" />
  502.             <input type="button" value="Restore" onclick="TL.properties(true);" />
  503.             <input type="button" value="Clear" onclick="TL.clear();" />
  504.             <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
  505.         </div>
  506.         <div panel="7" style="display:none;">
  507.             <h4>time control</h4>
  508.             <input type="text" id="addtime" />
  509.             <input type="button" value="Translate" />
  510.             <input type="button" value="Clear" onclick="TL.clear();" />
  511.             <input type="button" value="Copy" onclick="TL.CopyToClipboard();" />
  512.         </div>
  513.         <p id="timer">
  514.         </p>
  515.     </div>
  516. </form>
  517. </body>
  518. </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
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2.  
  3. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
  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>Test foreach</title>
  8.  
  9.     <script type="text/javascript" language="javascript">
  10.     function newRow(){
  11.         var container = document.getElementById("container");
  12.         var input = document.createElement("input");
  13.         var div = document.createElement("div");
  14.         
  15.         input.type = "text";
  16.         input.name = "foption";
  17.         input.value = (new Date()).toGMTString();
  18.         
  19.         div.appendChild(input);
  20.         container.appendChild(div);
  21.     }
  22.     function foreachResult(){
  23.         var result = document.getElementById("result");
  24.         var inputs = document.getElementsByTagName("input");
  25.         var div = false;
  26.         while(result.firstChild) result.removeChild(result.firstChild);
  27.         
  28.         for(var i in inputs){
  29.             if(!inputs[i] || inputs[i].name != "foption") continue;
  30.             div = document.createElement("div");
  31.             div.appendChild(document.createTextNode(inputs[i] ? inputs[i].value : "undefined inputs?"));
  32.             result.appendChild(div);
  33.         }
  34.     }
  35.     function forResult(){
  36.         var result = document.getElementById("result");
  37.         var inputs = document.getElementsByTagName("input");
  38.         var div = false;
  39.         while(result.firstChild) result.removeChild(result.firstChild);
  40.         
  41.         for(var i = 0; i < inputs.length; i++){
  42.             if(!inputs[i] || inputs[i].name != "foption") continue;
  43.             div = document.createElement("div");
  44.             div.appendChild(document.createTextNode(inputs[i] ? inputs[i].value : "undefined inputs?"));
  45.             result.appendChild(div);
  46.         }
  47.     }
  48.     </script>
  49.  
  50. </head>
  51. <body>
  52.     <form id="form1" runat="server">
  53.     <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
  54.     </cc1:ToolkitScriptManager>
  55.     <table border="1">
  56.         <tr>
  57.             <td>
  58.                 <div id="container">
  59.                     <input type="button" onclick="newRow();" value="加入textbox" /><br />
  60.                     <input type="button" onclick="foreachResult();" value="用利foreach列出name為foption的textbox" /><br />
  61.                     <input type="button" onclick="forResult();" value="用利for列出name為foption的textbox" />
  62.                     <asp:Literal ID="Literal1" runat="server"></asp:Literal>
  63.                 </div>
  64.             </td>
  65.             <td style="width: 300px; vertical-align: top;">
  66.                 <div id="result">
  67.                     &nbsp;
  68.                 </div>
  69.             </td>
  70.         </tr>
  71.     </table>
  72.     </form>
  73. </body>
  74. </html>
Default.aspx.cs
  1. using System;
  2. using System.Configuration;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.HtmlControls;
  9. using System.Web.UI.WebControls;
  10. using System.Web.UI.WebControls.WebParts;
  11. using System.Xml.Linq;
  12. using System.Text;
  13.  
  14. public partial class _Default : System.Web.UI.Page
  15. {
  16.     protected void Page_Load(object sender, EventArgs e)
  17.     {
  18.         StringBuilder sb = new StringBuilder();
  19.         for (int i = 0; i < 15; i++)
  20.         {
  21.             sb.AppendFormat("<div><input type=\"text\" name=\"foption\" value=\"{0}\" /></div>", i);
  22.         }
  23.         Literal1.Text = sb.ToString();
  24.     }
  25. }
Get primary key after insert statement
sql server
MySQL
  1. INSERT INTO Table(Column1, Column2, Column3) VALUES(Value1, Value2, Value3);
  2. SELECT @@IDENTITY
CAPTCHA
ImageValidator.ashx
  1. <%@ WebHandler Language="C#" Class="ImageValidator" %>
  2.  
  3. using System;
  4. using System.Web;
  5. using System.Drawing;
  6. using System.Web.SessionState;
  7.  
  8. public class ImageValidator : IHttpHandler, IRequiresSessionState
  9. {
  10.  
  11.     public void ProcessRequest(HttpContext context)
  12.     {
  13.         // character for validating
  14.         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" };
  15.         string strRd = string.Empty;
  16.  
  17.         Random random = new Random(unchecked((int)DateTime.Now.Ticks));
  18.         Bitmap bmp = new Bitmap(80, 25);  // create empty image
  19.         Graphics graphic = Graphics.FromImage(bmp);
  20.         Font font = new Font("Verdana", 14, FontStyle.Italic);
  21.  
  22.         for (int i = 0; i < 5; i++)       // random a validate string
  23.         {
  24.             strRd += code[random.Next(35)];
  25.         }
  26.  
  27.         graphic.Clear(Color.White);    //設定背景顏色
  28.         for (int i = 1; i <= 10; i++)
  29.         {
  30.             graphic.DrawLine(GetPen(i), random.Next(80), 0, random.Next(80), 30); // ↘
  31.         }
  32.  
  33.         graphic.DrawString(strRd, font, Brushes.Black, 0, 0);
  34.         for (int i = 0; i <= 50; i++)            //亂數產生霧點,擾亂機器人辨別 
  35.         {
  36.             int RandPixelX = random.Next(0, 80);
  37.             int RandPixelY = random.Next(0, 25);
  38.             bmp.SetPixel(RandPixelX, RandPixelY, Color.Blue);
  39.         }
  40.  
  41.  
  42.         context.Session["ValidateCode"] = strRd;        //將驗證碼存入Session以便稍後進行驗證 
  43.         //context.Response.Cookies.Add(new HttpCookie("ValidateCode", strRd)); //將驗證碼存入cookie以便稍後進行驗證
  44.         bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
  45.     }
  46.  
  47.     #region getPen 取得筆刷的設定顏色
  48.     protected Pen GetPen(int i)
  49.     {
  50.         Pen PenLine = new Pen(Brushes.Red, 1);//實體化筆刷並設定顏色、大小(畫X,Y軸用)
  51.         switch (i)
  52.         {
  53.             case 1:
  54.                 PenLine = new Pen(Brushes.Red, 1);
  55.                 break;
  56.             case 2:
  57.  
  58.                 PenLine = new Pen(Brushes.BlueViolet, 1);
  59.                 break;
  60.             case 3:
  61.                 PenLine = new Pen(Brushes.GreenYellow, 1);
  62.                 break;
  63.             case 4:
  64.                 PenLine = new Pen(Brushes.Gold, 1);
  65.                 break;
  66.             case 5:
  67.                 PenLine = new Pen(Brushes.MediumBlue, 1);
  68.                 break;
  69.             case 6:
  70.                 PenLine = new Pen(Brushes.MintCream, 1);
  71.                 break;
  72.             case 7:
  73.                 PenLine = new Pen(Brushes.Pink, 1);
  74.                 break;
  75.             case 8:
  76.                 PenLine = new Pen(Brushes.Purple, 1);
  77.                 break;
  78.             case 9:
  79.                 PenLine = new Pen(Brushes.HotPink, 1);
  80.                 break;
  81.             case 10:
  82.                 PenLine = new Pen(Brushes.Chocolate, 1);
  83.                 break;
  84.         } return PenLine;
  85.     }
  86.     #endregion
  87.  
  88.     public bool IsReusable
  89.     {
  90.         get
  91.         {
  92.             return false;
  93.         }
  94.     }
  95.  
  96. }
Default.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7.     <title>未命名頁面</title>
  8. </head>
  9. <body>
  10.     <form id="form1" runat="server">
  11.     <div>
  12.         <asp:Image ID="Image1" runat="server" ImageUrl="~/ImageValidator.ashx" />
  13.     </div>
  14.     </form>
  15. </body>
  16. </html>
Generate KeyStore and signed applet
in command line:
  1. keytool -genkey -keystore myKeystore -alias myself
  2. //建立你的public key
  3. keytool -selfcert -alias myself -keystore myKeystore
  4. //由你的pubilc key 建立一個 private key
  5. jarsigner -keystore myKeystore test.jar myself
  6. //將你的jar檔用你的private key來簽章
Paging
Sql server
Assume:
@PageSize is the row counts displayed on page
@CurrentPage is the page number
  1. SELECT TOP @PageSize * FROM Table WHERE ID NOT IN
  2.     (SELECT TOP @PageSize*@CurrentPage ID FROM Table ORDER BY ID DESC)
  3. ORDER BY ID DESC
Oracle
Assume:
@MaxRowNum means the max row to query
@MinRowNum means the min row to query
  1. SELECT * FROM 
  2.     (SELECT rownum, * FROM
  3.         (SELECT * FROM Table WHERE SomeColumn = Something ORDER BY SomeColumns)
  4.     WHERE rownum <= @MaxRowNum)
  5. WHERE rownum >= @MinRowNum
↑better performance on visit first serval pages
  1. SELECT * FROM Table WHERE rowind IN
  2.     (SELECT rid FROM
  3.         (SELECT rownum rno, rowid rid FROM
  4.             (SELECT rowid FROM Table WHERE SomeColumn = Something ORDER BY SomeColumns)
  5.         WHERE rownum <= @MaxRowNum)
  6.     WHERE rno >= @MinRowNum)
↑better performance on higher page numbers
  1. SELECT * FROM 
  2.     (SELECT owner, table_name, row_number() OVER(ORDER BY table_name) rownumber FROM dba_tables)
  3. WHERE rownumber >= @MinRowNum AND rownumber <= @MaxRowNum
Read exif using metadata extraction
metadata extraction version : 2.3.1
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Iterator;
  4.  
  5. import com.drew.imaging.jpeg.JpegProcessingException;
  6. import com.drew.metadata.Directory;
  7. import com.drew.metadata.Metadata;
  8. import com.drew.metadata.exif.ExifDirectory;
  9. import com.drew.metadata.exif.ExifReader;
  10.  
  11. public class EXIFReader {
  12.  
  13.     public static void printExif(String fileName) throws FileNotFoundException {
  14.         File f = new File(fileName);
  15.         try {
  16.             ExifReader er = new ExifReader(f);
  17.             Metadata exif = er.extract();
  18.             Iterator itr = exif.getDirectoryIterator();
  19.             while (itr.hasNext()) {
  20.                 Directory directory = (Directory) itr.next();
  21.  
  22.                 System.out.println("EXIF版本:" + directory.getString(ExifDirectory.TAG_EXIF_VERSION));
  23.                 System.out.println("相機品牌:" + directory.getString(ExifDirectory.TAG_MAKE));
  24.                 System.out.println("像機號碼:" + directory.getString(ExifDirectory.TAG_MODEL));
  25.                 System.out.println("光 圈 值:" + directory.getString(ExifDirectory.TAG_FNUMBER));
  26.                 System.out.println("快 門:" + directory.getString(ExifDirectory.TAG_EXPOSURE_TIME));
  27.                 System.out.println("感 光 度:" + directory.getString(ExifDirectory.TAG_ISO_EQUIVALENT));
  28.                 System.out.println("軟 件:" + directory.getString(ExifDirectory.TAG_SOFTWARE));
  29.                 System.out.println("原始拍攝時間:" + directory.getString(ExifDirectory.TAG_DATETIME_ORIGINAL));
  30.                 System.out.println("數字化時間:" + directory.getString(ExifDirectory.TAG_DATETIME_DIGITIZED));
  31.                 System.out.println("方 向:" + directory.getString(ExifDirectory.TAG_ORIENTATION));
  32.                 System.out.println("圖片寬度:" + directory.getString(ExifDirectory.TAG_EXIF_IMAGE_WIDTH));
  33.                 System.out.println("圖片高度:" + directory.getString(ExifDirectory.TAG_EXIF_IMAGE_HEIGHT));
  34.                 System.out.println("水平分辨率:" + directory.getString(ExifDirectory.TAG_X_RESOLUTION));
  35.                 System.out.println("垂直分辨率:" + directory.getString(ExifDirectory.TAG_Y_RESOLUTION));
  36.                 System.out.println("垂直分辨率:" + directory.getString(ExifDirectory.TAG_EXPOSURE_BIAS));
  37.                 break;
  38.             }
  39.         } catch (JpegProcessingException e) {
  40.             System.err.println("not jpeg file");
  41.         }
  42.     }
  43. }
LOB column read/write in Oracle
  1. import java.io.IOException;
  2. import java.io.Writer;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8.  
  9. import oracle.jdbc.driver.OracleResultSet;
  10. import oracle.sql.CLOB;
  11.  
  12. public class OracleLobType {
  13.  
  14.     public static void insertLOB() throws ClassNotFoundException, SQLException, IOException {
  15.  
  16.         Class.forName("oracle.jdbc.driver.OracleDriver");
  17.         Connection conn = DriverManager.getConnection("ConnectionString");
  18.  
  19.         PreparedStatement pstmt = null;
  20.         ResultSet rs = null;
  21.         String sql = "";
  22.  
  23.         conn.setAutoCommit(false);
  24.         sql = "INSERT INTO Table(id, clobColumn) VALUES(?, empty_clob())";
  25.         pstmt = conn.prepareStatement(sql);
  26.         pstmt.setInt(1, 1);
  27.         pstmt.executeUpdate();
  28.         pstmt.close();
  29.  
  30.         pstmt = null;
  31.         sql = "SELECT clobColumn FROM Table WHERE id = 1 FOR UPDATE";
  32.         pstmt = conn.prepareStatement(sql);
  33.         rs = pstmt.executeQuery();
  34.  
  35.         CLOB clobValue = null;
  36.         while (rs.next()) {
  37.             clobValue = (CLOB) rs.getClob("clobColumn");
  38.         }
  39.         Writer wr = clobValue.getCharacterOutputStream();
  40.         wr.write("clob data");
  41.         wr.flush();
  42.         wr.close();
  43.  
  44.         rs.close();
  45.         pstmt.close();
  46.         conn.commit();
  47.         conn.close();
  48.  
  49.     }
  50.  
  51.     public static void getLOG() throws ClassNotFoundException, SQLException {
  52.  
  53.         Class.forName("oracle.jdbc.driver.OracleDriver");
  54.         Connection conn = DriverManager.getConnection("ConnectionString");
  55.  
  56.         String sql = "";
  57.         PreparedStatement pstmt = null;
  58.         ResultSet rs = null;
  59.  
  60.         sql = "SELECT clobColumn FROM Table WHERE id = 1";
  61.         pstmt = conn.prepareStatement(sql);
  62.         rs = pstmt.executeQuery();
  63.  
  64.         CLOB clobValue = null;
  65.         while (rs.next()) {
  66.             OracleResultSet ors = (OracleResultSet) rs;
  67.             clobValue = (CLOB) ors.getCLOB("clobColumn");
  68.         }
  69.  
  70.         String value = "";
  71.         if (clobValue != null && clobValue.length() > 0)
  72.             // clobValue.stringValue();
  73.             value = clobValue.getSubString(1, (int) clobValue.length());
  74.  
  75.         rs.close();
  76.         pstmt.close();
  77.         conn.close();
  78.  
  79.     }
  80. }