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... 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... 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...
Stats
Data Paging
Sql Server 2005
  1. DECLARE @PageIndex INT;
  2. DECLARE @PageSize INT;
  3. SET @PageSize = 3;
  4. SET @PageIndex = 1;
  5.  
  6. DECLARE @StartIndex INT;
  7. DECLARE @EndIndex INT;
  8. SET @StartIndex = @PageSize * (@PageIndex-1) +1;
  9. SET @EndIndex = @StartIndex + @PageSize - 1;
  10.  
  11.  
  12. WITH ProductEntires AS(
  13.     SELECT 
  14.         ROW_NUMBER() OVER (ORDER BY [UpdateDate] DESC) AS RowIndex, 
  15.         [ID], 
  16.         [ProductName], 
  17.         [ProductDescription], 
  18.         [ProductImage1], 
  19.         [ProductTitle1], 
  20.         [VotedAmount] 
  21.     FROM 
  22.         [TblProduct] 
  23. )
  24.  
  25. SELECT * 
  26. FROM ProductEntires
  27. WHERE
  28.     [RowIndex] BETWEEN @StartIndex AND @EndIndex
Temp table sample
MySQL
  1. -- Procedure "IsActionAllowed" DDL
  2.  
  3. CREATE DEFINER=`root`@`%` PROCEDURE `IsActionAllowed`(IN roleid CHAR(36), IN functionid CHAR(36))
  4. BEGIN
  5.     DECLARE rid CHAR(36);
  6.     DECLARE base_role CHAR(36);
  7.     DECLARE exist INT;
  8.  
  9.     CREATE TEMPORARY TABLE TempTable (RID CHAR(36)) TYPE=INNODB;
  10.  
  11.     INSERT INTO TempTable VALUES(roleid);
  12.     SET base_role = '';
  13.     SET rid = roleid;
  14.  
  15.     WHILE base_role IS NOT NULL DO
  16.         IF base_role <> '' THEN
  17.             INSERT INTO TempTable VALUES(base_role);
  18.         END IF;
  19.  
  20.         SELECT
  21.             tbl_roles.BASE_ON_ROLE INTO base_role
  22.         FROM
  23.             tbl_roles
  24.         WHERE
  25.             tbl_roles.ROLE_ID = rid;
  26.  
  27.         SET rid = base_role;
  28.  
  29.     END WHILE;
  30.  
  31.     SELECT
  32.         COUNT(tbl_role_permission.ROLE_ID) INTO exist
  33.     FROM
  34.         tbl_role_permission
  35.     WHERE
  36.         tbl_role_permission.ROLE_ID IN (SELECT * FROM TempTable)
  37.         AND tbl_role_permission.FUNCTION_ID = functionid;
  38.  
  39.     DROP TEMPORARY TABLE IF EXISTS TempTable;
  40.  
  41.     IF exist > 0 THEN
  42.         SELECT true AS Allowed;
  43.     ELSE
  44.         SELECT false AS Allowed;
  45.     END IF;
  46. END;
Procedure tutorial : Stored Procedure Parameters
MyUtil
  1. using System;
  2.  
  3. namespace Bruce.Lib
  4. {
  5.     public class BUtil
  6.     {
  7.         /// <summary>
  8.         /// 測試參數中是否含有null或空值
  9.         /// </summary>
  10.         /// <param name="data">任意物件</param>
  11.         /// <returns>含有null、DBNull或空值則為true,反之為false</returns>
  12.         public static bool ContainsNullOrEmpty(params object[] data)
  13.         {
  14.             foreach (object d in data)
  15.             {
  16.                 if (== null || d == DBNull.Value || string.IsNullOrEmpty(d.ToString()))
  17.                     return true;
  18.             }
  19.             return false;
  20.         }
  21.         /// <summary>
  22.         /// 將任意物件轉成字串,免去再判斷null或DBNull的處理
  23.         /// </summary>
  24.         /// <param name="data">任意物件</param>
  25.         /// <returns></returns>
  26.         public static string StringValue(object data)
  27.         {
  28.             return data == null || data == DBNull.Value ? string.Empty : Convert.ToString(data);
  29.         }
  30.         /// <summary>
  31.         /// 
  32.         /// </summary>
  33.         /// <param name="data"></param>
  34.         /// <param name="length"></param>
  35.         /// <returns></returns>
  36.         public static string Summary(object data, int length)
  37.         {
  38.             if (length < 1) throw new ArgumentException();
  39.             string str = StringValue(data);
  40.             return str.Length > length ? str.Substring(0, length) + "..." : str;
  41.         }
  42.     }
  43. }
Select row by clicking in a GridView
GridViewSelectRow.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewSelectRow.aspx.cs"
  2.     Inherits="GridViewSelectRow" EnableEventValidation="false" %>
  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>Select row by clicking in a GridView</title>
  8. </head>
  9. <body>
  10.     <form id="form1" runat="server">
  11.     <table border="1">
  12.         <tr>
  13.             <td>
  14.                 SELECTED ID
  15.             </td>
  16.             <td>
  17.                 <asp:Label ID="sID" runat="server" Text="Label"></asp:Label>
  18.             </td>
  19.         </tr>
  20.         <tr>
  21.             <td>
  22.                 SELECTED UNIQUEID
  23.             </td>
  24.             <td>
  25.                 <asp:Label ID="sUniqueID" runat="server" Text="Label"></asp:Label>
  26.             </td>
  27.         </tr>
  28.         <tr>
  29.             <td>
  30.                 SELECTED PRICE
  31.             </td>
  32.             <td>
  33.                 <asp:Label ID="sPrice" runat="server" Text="Label"></asp:Label>
  34.             </td>
  35.         </tr>
  36.         <tr>
  37.             <td>
  38.                 SELECTED AMOUNT
  39.             </td>
  40.             <td>
  41.                 <asp:Label ID="sAmount" runat="server" Text="Label"></asp:Label>
  42.             </td>
  43.         </tr>
  44.         <tr>
  45.             <td>
  46.                 SELECTED CREATEDATE
  47.             </td>
  48.             <td>
  49.                 <asp:Label ID="sCreateDate" runat="server" Text="Label"></asp:Label>
  50.             </td>
  51.         </tr>
  52.     </table>
  53.     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID,UniqueID"
  54.         DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
  55.         AllowPaging="True">
  56.         <Columns>
  57.             <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
  58.                 SortExpression="ID" />
  59.             <asp:BoundField DataField="UniqueID" HeaderText="UniqueID" ReadOnly="True" SortExpression="UniqueID" />
  60.             <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
  61.             <asp:BoundField DataField="Amount" HeaderText="Amount" SortExpression="Amount" />
  62.             <asp:BoundField DataField="CreateDate" HeaderText="CreateDate" SortExpression="CreateDate" />
  63.         </Columns>
  64.     </asp:GridView>
  65.     <div>
  66.         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%ConnectionStrings:brucedbConnectionString %>"
  67.             SelectCommand="SELECT * FROM [GV]"></asp:SqlDataSource>
  68.     </div>
  69.     </form>
  70. </body>
  71. </html>
GridViewSelectRow.aspx.cs
  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 GridViewSelectRow : System.Web.UI.Page
  15. {
  16.     protected void Page_Load(object sender, EventArgs e)
  17.     {
  18.  
  19.     }
  20.     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  21.     {
  22.         if (e.Row.RowType == DataControlRowType.DataRow)
  23.         {
  24.             e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
  25.             e.Row.Style["cursor"] = "hand";
  26.         }
  27.     }
  28.     protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
  29.     {
  30.         GridViewRow row = ((GridView)sender).SelectedRow;
  31.         this.sID.Text = row.Cells[0].Text;
  32.         this.sUniqueID.Text = row.Cells[1].Text;
  33.         this.sPrice.Text = row.Cells[2].Text;
  34.         this.sAmount.Text = row.Cells[3].Text;
  35.         this.sCreateDate.Text = row.Cells[4].Text;
  36.     }
  37. }
About ACL control.
reference : http://blog.crowe.co.nz/archive/2007/08/25/c---An-example-of-setting-NTFS-Directory--File.aspx
  1. using System.IO;
  2. using System.Security.AccessControl;
  3.  
  4. namespace Bruce.Lib
  5. {
  6.     public class DirectoryPermissions
  7.     {
  8.         private static void Main(string[] args)
  9.         {
  10.             string ADDomain = "Domain";
  11.             string ADUser = "Chris";
  12.             string Path = @"c:\temp\chris";
  13.  
  14.             if (Directory.Exists(Path) == false)
  15.                 Directory.CreateDirectory(Path);
  16.  
  17.             // Remove any inheritable permissions from the path 
  18.             RemoveInheritablePermissons(Path);
  19.  
  20.             // Add the access control entries for the path 
  21.             AddDirectorySecurity(Path, ADDomain + "\\" + ADUser, FileSystemRights.Modify,
  22.                                  InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  23.                                  PropagationFlags.None, AccessControlType.Allow);
  24.             AddDirectorySecurity(Path, ADDomain + "\\Domain Users", FileSystemRights.Delete, InheritanceFlags.None,
  25.                                  PropagationFlags.None, AccessControlType.Deny);
  26.             AddDirectorySecurity(Path, ADDomain + "\\Domain Admins", FileSystemRights.FullControl,
  27.                                  InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  28.                                  PropagationFlags.None, AccessControlType.Allow);
  29.         }
  30.  
  31.  
  32.         // Adds an ACL entry on the specified directory for the specified account. 
  33.         public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights,
  34.                                                 InheritanceFlags Inheritance, PropagationFlags Propogation,
  35.                                                 AccessControlType ControlType)
  36.         {
  37.             // Create a new DirectoryInfo object. 
  38.             DirectoryInfo dInfo = new DirectoryInfo(FileName);
  39.             // Get a DirectorySecurity object that represents the  
  40.             // current security settings. 
  41.             DirectorySecurity dSecurity = dInfo.GetAccessControl();
  42.             // Add the FileSystemAccessRule to the security settings.  
  43.             dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
  44.                                                              Rights,
  45.                                                              Inheritance,
  46.                                                              Propogation,
  47.                                                              ControlType));
  48.             // Set the new access settings. 
  49.             dInfo.SetAccessControl(dSecurity);
  50.         }
  51.  
  52.         // Removes an ACL entry on the specified directory for the specified account. 
  53.         public static void RemoveDirectorySecurity(string FileName, string Account, FileSystemRights Rights,
  54.                                                    AccessControlType ControlType)
  55.         {
  56.             // Create a new DirectoryInfo object. 
  57.             DirectoryInfo dInfo = new DirectoryInfo(FileName);
  58.             // Get a DirectorySecurity object that represents the  
  59.             // current security settings. 
  60.             DirectorySecurity dSecurity = dInfo.GetAccessControl();
  61.             // Add the FileSystemAccessRule to the security settings.  
  62.             dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
  63.                                                                 Rights,
  64.                                                                 ControlType));
  65.             // Set the new access settings. 
  66.             dInfo.SetAccessControl(dSecurity);
  67.         }
  68.  
  69.         // Removes an ACL entry on the specified directory for the specified account. 
  70.         public static void RemoveInheritablePermissons(string FileName)
  71.         {
  72.             // Create a new DirectoryInfo object. 
  73.             DirectoryInfo dInfo = new DirectoryInfo(FileName);
  74.             // Get a DirectorySecurity object that represents the  
  75.             // current security settings. 
  76.             DirectorySecurity dSecurity = dInfo.GetAccessControl();
  77.             // Add the FileSystemAccessRule to the security settings. 
  78.             const bool IsProtected = true;
  79.             const bool PreserveInheritance = false;
  80.             dSecurity.SetAccessRuleProtection(IsProtected, PreserveInheritance);
  81.             // Set the new access settings. 
  82.             dInfo.SetAccessControl(dSecurity);
  83.         }
  84.  
  85.     }
  86. }
Get the column name which is a primary key
Sql server
  1. DECLARE @TableName VARCHAR(128)
  2. SELECT @TableName = 'test_table'
  3.  
  4. SELECT c.COLUMN_NAME 
  5. FROM
  6.     INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
  7.     INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
  8. WHERE
  9.     pk.TABLE_NAME = @TableName
  10.     AND CONSTRAINT_TYPE = 'PRIMARY KEY'
  11.     AND c.TABLE_NAME = pk.TABLE_NAME
  12.     AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
Get all table's name from db
Sql server
  1. SELECT * FROM INFORMATION_SCHEMA.TABLES
Access
  1. SELECT * FROM MSYSOBJECTS
MySQL
  1. SHOW TABLES
Oracle
  1. SELECT * FROM USER_OBJECTS
Window service sample
First, create a new window service project.

For schedule service, we need to add System.Timers.Timer to toolbox, and drag it into design mode.

Then, code something.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.ServiceProcess;
  8. using System.Text;
  9. using System.IO;
  10.  
  11. namespace WindowServiceSample
  12. {
  13.     public partial class Service1 : ServiceBase
  14.     {
  15.         public Service1()
  16.         {
  17.             InitializeComponent();
  18.         }
  19.  
  20.         protected override void OnStart(string[] args)
  21.         {
  22.             // 服務啟動時執行
  23.             this.EventLog.WriteEntry(System.AppDomain.CurrentDomain.BaseDirectory);  // write current directory to event log
  24.         }
  25.  
  26.         protected override void OnStop()
  27.         {
  28.             // 服務結束時執行
  29.         }
  30.  
  31.         private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  32.         {
  33.             // 計時器, 依據設定間隔執行
  34.         }
  35.     }
  36. }
After coding, we need to add a installer for Window Service Installer.

There are two components needed to set, serviceProcessInstaller and serviceInstaller

Build the project and find the executable binary, enter the command below for installing.
  1. %windir%\Microsoft.NET\Framework\v2.0.50727\installutil WindowServiceSample.exe
There will be a new service listed in Services.

For unstalling, enter command below:
  1. %windir%\Microsoft.NET\Framework\v2.0.50727\installutil /u WindowServiceSample.exe
Permutation
  1. package bruce.math;
  2.  
  3. import java.math.BigDecimal;
  4.  
  5. public class Permutation {
  6.     public static BigDecimal H(int n, int m) throws IllegalArgumentException {
  7.         return C(+ m - 1, m);
  8.     }
  9.  
  10.     public static BigDecimal P(int n, int m) throws IllegalArgumentException {
  11.         return C(n, m).multiply(factorial(m));
  12.     }
  13.  
  14.     public static BigDecimal C(int n, int m) throws IllegalArgumentException {
  15.         if (< m)
  16.             throw new IllegalArgumentException("n must great equal than m.");
  17.         return factorial(n).divide(factorial(- m).multiply(factorial(m)));
  18.     }
  19.  
  20.     public static BigDecimal factorial(int num) throws IllegalArgumentException {
  21.         if (num < 0)
  22.             throw new IllegalArgumentException("num must great than zero.");
  23.         return num <= 1 ? new BigDecimal(1) : factorial(num - 1).multiply(new BigDecimal(num));
  24.     }
  25. }