Archive for the ‘coding snippet’ Category

Double Checked Locking

Wednesday, April 16th, 2008

今日係 newsgroup 見到個 singleton 問題:
// 版本 A

    public static synchronized Socket getInstance ( )
        throws IOException {    

        if ( instance == null || instance.isClosed ( ) ) {
            instance = new SingleSocket ( ) ;
        }

        return instance ;
    }

// 版本 B Double-check Locking

    public static Socket getInstance ( )
        throws IOException {

        if ( instance == null || instance.isClosed ( ) ) {
            synchronized ( instance ) {
            if ( instance == null || instance.isClosed ( ) ) {
                instance = new SingleSocket ( ) ;
            }
            }
        }
        return instance ;
    }

經過唔同人既 comment, 原來版本 B 係唔 work 的, 詳情請見 Ref: Double Checked Locking

Default Button and Default Focus in Master Page.

Thursday, January 17th, 2008

自從轉左用 ASP.net 2.0 既 Master Page 之後, 個 form 出左出面, 所以以為無得用 Form Set Default Focus 同 Default Button, 阿敏今日 send 左個 site 比我, 入面考用 Page.Form 黎 Set Default Focus 同 Default Button, 要注意既係用 Default Button 既 UniqueID 同埋 Default Focus 既 ClientID

Page.Form.DefaultFocus = TextBox1.ClientID
Page.Form.DefaultButton = Button1.UniqueID

ListTransformer

Friday, November 23rd, 2007

呢排寫緊好多比較 Generic 既 class, 希望可以 improve reusable, 所以係 Code Project 度問左呢個 class, 主要係將一個 object List 變左一個 generic List, 咁就可以方便 d.

public class ListTranformer
{
    public static List<D> Transform<D>(System.Collections.IList list)
    {
        List lst = new List();
        foreach (D element in list)
        {
            lst.Add(element);
        }
        return lst;
    }
}

Implement Timeout in C#

Wednesday, October 24th, 2007

最近要幫個 hardware 寫返個 timeout, 主要既目的唔想佢 hold 咁耐, 好似 hang 左咁, 所以就係網上搵左呢個較好既方法.
其實主要係用左 Delegate, define 個 delegate 同target function 同樣 return type 同 parameter, 之後將果個 function 放係 delegate 個 constructor 果度, private 左之前果個 function, 將外部既 code call 新既 method (Execute), Set 埋個 Timeout 可以自己做個 TimeoutException~~

delegate int WorkDelegate(string arg);

public int Execute(string arg)
{
        WorkDelegate d = new WorkDelegate(TargetFunction);
        IAsyncResult res = d.BeginInvoke(arg, null, null);

        if (res.IsCompleted == false)
        {
                //Timeout when execute more than 10 sec
                res.AsyncWaitHandle.WaitOne(10000, false);
                if (res.IsCompleted == false)
                {
                        throw new TimeoutException("Timeout");
                }
        }
        return d.EndInvoke((AsyncResult)res);
}

Identity Transformation Stylesheet

Wednesday, September 12th, 2007

Here is the identity transformation style-sheet, which is a XSLT for transform a XML in same content.