Popular Posts
Stats
Test polymorphism in reflection method invoke
package y11.m04;

import java.lang.reflect.Method;

public class d28t01 {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // Test polymorphism in reflection
        Object invoker = new Invoker();
        Class clazz = invoker.getClass();

        Dialer p1 = new Phone("12345");
        Phone p2 = new Phone("234567");
        CellPhone p3 = new CellPhone("345678");

        // cause java.lang.NosuchMethodException
        try {
            Method m1 = clazz.getDeclaredMethod("use", p1.getClass());
            m1.invoke(invoker, p1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Method m2 = clazz.getDeclaredMethod("use", p2.getClass());
            m2.invoke(invoker, p1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Method m3 = clazz.getDeclaredMethod("use", p3.getClass());
            m3.invoke(invoker, p1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Method[] ms = clazz.getDeclaredMethods();
        for (Method m : ms) {
            if (m.getName().equals("use")) {
                Class[] paramTypes = m.getParameterTypes();
                if (paramTypes.length == 1 && paramTypes[0].isAssignableFrom(p1.getClass())) {
                    m.invoke(invoker, p1);
                }
            }

            if (m.getName().equals("use")) {
                Class[] paramTypes = m.getParameterTypes();
                if (paramTypes.length == 1 && paramTypes[0].isAssignableFrom(p2.getClass())) {
                    m.invoke(invoker, p2);
                }
            }

            if (m.getName().equals("use")) {
                Class[] paramTypes = m.getParameterTypes();
                if (paramTypes.length == 1 && paramTypes[0].isAssignableFrom(p3.getClass())) {
                    m.invoke(invoker, p3);
                }
            }
        }
    }
}

class Invoker {
    public void use(Dialer dialer) {
        if (dialer != null)
            dialer.call();
    }
}

interface Dialer {
    void call();
}

class Phone implements Dialer {
    public String number;

    public Phone(String number) {
        this.number = number;
    }

    public void call() {
        System.out.printf("Call %s%n", number);
    }
}

class CellPhone extends Phone {

    public CellPhone(String number) {
        super(number);
    }

    @Override
    public void call() {
        System.out.printf("Dial %s%n", number);
    }
}
Share folder info (netapi32)
class MainConsole
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    struct SHARE_INFO_2
    {
        [MarshalAs(UnmanagedType.LPWStr)]
        public string shi2_netname;
        public uint shi2_type;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string shi2_remark;
        public uint shi2_permissions;
        public uint shi2_max_uses;
        public uint shi2_current_uses;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string shi2_path;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string shi2_passwd;
    }

    static string FormatMessage(int errCode)
    {
        switch (errCode)
        {
            case ERROR_ACCESS_DENIED: return "The user does not have access to the requested information.";
            case ERROR_INVALID_LEVEL: return "The value specified for the level parameter is invalid.";
            case ERROR_INVALID_PARAMETER: return "The specified parameter is invalid.";
            case ERROR_MORE_DATA: return "More entries are available. Specify a large enough buffer to receive all entries.";
            case ERROR_NOT_ENOUGH_MEMORY: return "Insufficient memory is available.";
            case NERR_BufTooSmall: return "The supplied buffer is too small.";
            case NERR_NetNameNotFound: return "The share name does not exist.";
        };

        return null;
    }

    [DllImport("Netapi32", CharSet = CharSet.Auto)]
    static extern int NetApiBufferFree(IntPtr Buffer);

    [DllImport("Netapi32", CharSet = CharSet.Auto)]
    static extern int NetShareGetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string netname, int level, ref IntPtr bufptr);

    /// <summary>
    /// Retrieves the local path for the given server and share name.
    /// </summary>
    /// <remarks>serverName must start with \\</remarks>
    static string NetShareGetPath(string serverName, string netName)
    {
        string path = null;
        IntPtr ptr = IntPtr.Zero;

        int errCode = NetShareGetInfo(serverName, netName, 2, ref ptr);
        if (errCode == NERR_Success)
        {
            SHARE_INFO_2 shareInfo = (SHARE_INFO_2)Marshal.PtrToStructure(ptr, typeof(SHARE_INFO_2));

            var members = from m in shareInfo.GetType().GetFields()
                          select m;

            foreach (var m in members)
            {
                Console.WriteLine("{0}={1}", m.Name, m.GetValue(shareInfo));
            }


            path = shareInfo.shi2_path;
            NetApiBufferFree(ptr);
        }
        else
            Console.WriteLine(FormatMessage(errCode));

        return path;
    }

    /// <summary>
    /// The Main method is the entry point of the program, where the program control starts and
    /// ends.
    /// </summary>
    /// <param name="args"></param>
    /// <returns></returns>
    [STAThread]
    static int Main(string[] args)
    {
        Console.WriteLine("path=" + NetShareGetPath(@"\\s3t21", "檔案測試區"));

        Console.Read();
        return 0;
    }

    const int ERROR_ACCESS_DENIED = 5;
    const int ERROR_INVALID_LEVEL = 124; // unimplemented level for info
    const int ERROR_INVALID_PARAMETER = 87;
    const int ERROR_MORE_DATA = 234;
    const int ERROR_NOT_ENOUGH_MEMORY = 8;
    const int NERR_BufTooSmall = 2123; // The API return buffer is too small.
    const int NERR_NetNameNotFound = 2310; // This shared resource does not exist.
    const int NERR_Success = 0;

} // class MainConsole
http://pinvoke.net/default.aspx/netapi32.NetShareGetInfo
Get share folders from wmi
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from win32_share");
foreach (ManagementObject share in searcher.Get())
{
    Console.WriteLine("==============");
    ManagementBaseObject baseObj = share as ManagementBaseObject;

    PropertyDataCollection.PropertyDataEnumerator en = share.Properties.GetEnumerator();
    while (en.MoveNext())
    {
        Console.WriteLine(en.Current.Name + "=" + en.Current.Value);
    }
}
Web based file manager
//KeyNumber : 102(int)
//ProductName : ad(string)
//ProductVersion : ad1.0.2.1011010(string)
//LicenseCount : 9999(int)
//UserCount : 9999(int)
Cryptor cryptor = new Cryptor();
string key = HexEncoding.ToString(cryptor.EncryptString("102:ad:ad1.0.2.1011010:9999:9999"));
Tick
Start tick
Java Javascript .net
Tick = 0 (GMT+0) 1970/01/01 00:00:00 1970/01/01 00:00:00 1601/01/01 00:00:00
sec/tick 1000 1000 10000000
Convertion
tick=0\to tick Java Javascript .net
Java x 0 621356256000000000
Javascript 0 x 621356256000000000
.net -11644473600000 -11644473600000 x
// Convert c# date to javascript
var ticks = (DateTime.Now.Ticks - 621356256000000000) / 10000;
// Convert javascript date to c#
var ticks = (((new Date()).getTime() * 10000) + 621355968000000000);
runas
RUNAS 使用方法:

RUNAS [ [/noprofile | /profile] [/env] [/netonly] ]
        /user: program

RUNAS [ [/noprofile | /profile] [/env] [/netonly] ]
        /smartcard [/user:] program

   /noprofile        指定使用者的設定檔不該載入。
                     這會導致應用程式載入速度更快,
                     但可能引起一些應用程式運作失常。
   /profile          指定應該載入使用者的設定檔。
                     這是預設值。
   /env              使用目前的環境,不用使用者設定的環境。
   /netonly          如果指定的憑證是供遠端存取時才使用。

   /savecred         使用之前由使用者儲存的認證。
                     此選項在 Windows XP Home Edition 上無法使用
                     而且會被略過。
   /smartcard        當智慧卡提供了認證時使用。

   /user              格式如下 USER@DOMAIN 或 DOMAIN\USER
   program         EXE 的命令列。範例如下

範例:
> runas /noprofile /user:mymachine\administrator cmd
> runas /profile /env /user:mydomain\admin "mmc %windir%\system32\dsa.msc"
> runas /env /user:user@domain.microsoft.com "notepad \"my file.txt\""

注意:  只有在提示時,才輸入使用者密碼。
注意:  USER@DOMAIN 與 /netonly 不相容。
注意:  /profile 與 /netonly 不相容。
jQuery : post/get using data() as param object
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Recursive call when post request</title>
<script type="text/javascript" src="jquery-1.5.1.js"></script>
<script type="text/javascript">
    $(function() {
        var count = 0;
        $('input:button').click(function() {
            // identity
            count++;
            var tick = count;
            // post url
            var url = '${contextPath}/';
            // post param
            var param = $(this).data();
            console.log(param);
            $('<div>(' + tick + ') Post to : ' + url + '</div>').appendTo(document.body);
            $.post(url, param, function(data) {
                $('<div style="color:blue;">(' + tick + ') Ajax works successfully.</div>').appendTo(document.body);
            });
        });
    });
</script>
</head>
<body>
<input type="button" value="click to post" data-action="test" data-name="bruce" data-age="31" />
</body>
</html>
ボタンをクリックすると、data()のオブジェクトがハンドルを値を持っているため、postするときにハンドルは再び執行することになる。つまり、クリック事件は繰り返しする。この現象を避けるには、ハンドル/イベントを削除しなければならない。
jQuery validte : regex rule
$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var check = false;
        var re = new RegExp(regexp);
        return this.optional(element) || re.test(value);
    },
    "Please check your input."
);
$("textbox").rules("add", { regex: "^[a-zA-Z'.\s]{1,40}$" })
Data URI schema
work.bmp URL: Data URI:
<img src="data:image/bmp;base64,Qk02BAAAAAAAADYAAAAoAAAAEAAAABAAAAABACAAAAAAAAAAAAASCwAAEgsAAAAAAAAAAAAAAAAACwAAACIAAAAtAAAALQAAAC0AAAAtAAAALQAAAC0AAAAtAAAALQAAAC0AAAAtAAAALQAAAC0AAAAiAAAACyFHYZwkTmvyJE5r8iROa/IkTmvyJE5r8iROa/IkTmvyJE5r8iROa/IkTmvyJE5r8iROa/IkTmvyJE5r8iFHYZwmUG3yUY6y/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/1GOsv8mUG3yKFJv8lGOsv9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9RjrL/KFJv8ipVcvJRjrL/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/UY6y/ypVcvItWHXyUY6y/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/1GOsv8tWHXyMFt58lGOsv9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9NfqT/TX6k/01+pP9RjrL/MFt58jRfffJRjrL/TX6k/01+pP9NfqT/TX6k/01+pP8kTmv/JE5r/0t7of9NfqT/TX6k/01+pP9NfqT/UY6y/zRfffIlT2z+JE5r/yROa/8kTmv/JE5r/yROa/8kTmv/JE5r/yROa/8kTmv/JE5r/yRO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/Ji88LxC9fBtJmuOgMzMxOKHJ8AC8Ppi4+/sPz5g9vvlgaaeF0A0sv0h4IwAOmlOBCZQFFBvgHAaAQlBnIBOCF9+f571c4Dl8PIMeDbz7+rQDmOG5rQuUnU/xWIXwIEGADy0nItvNe4lQAAAABJRU5ErkJggg==" />
Data URI schema
Statement.executeBatch() always returns an array of value -2
The elements in the array returned by the method executeBatch may be one of the following:
  1. A number greater than or equal to zero -- indicates that the command was processed successfully and is an update count giving the number of rows in the database that were affected by the command's execution
  2. A value of -2 -- indicates that the command was processed successfully but that the number of rows affected is unknown
    If one of the commands in a batch update fails to execute properly, this method throws a BatchUpdateException, and a JDBC driver may or may not continue to process the remaining commands in the batch. However, the driver's behavior must be consistent with a particular DBMS, either always continuing to process commands or never continuing to process commands. If the driver continues processing after a failure, the array returned by the method BatchUpdateException.getUpdateCounts will contain as many elements as there are commands in the batch, and at least one of the elements will be the following:
  3. A value of -3 -- indicates that the command failed to execute successfully and occurs only if a driver continues to process commands after a command fails
reference : executeBatch