2007-01-29

A boring MSDN webcast

Note: This artical is written in Chinese.


今天看了微软开发合作部的“互联网策略资深顾问”王洪超主讲的MSDN webcast《Gadget开发简述》视频。老实说,整个讲座技术含量很低,基本上是浪费我的时间。

技术含量低,可能因为这是一项较新的技术,也资料匮乏(Gadget参考是我看到过的最差的MSDN文档),且老王估计不是这方面专长,又或者是其讲座受众本身定位就是很低……

老王的口齿不清,这是先天不足,也罢了。但是,整个讲座废话连篇,演讲水准也超差,就令我对老王这个MVP甚感失望。倒是那个黄继佳配合的还算ok。也许老王本身就口才较差,专长技术……问题是这个讲座又毫无技术含量。

相比较而言,Microsoft UK的Developer & Platform Group的Deniel Moth所做的Vista:Sidebar Gadgets视频讲演,虽然也相当简单,但至少step by step的条理清楚。

BTW,指出老王的两个问题:

第一,他代码中创建xmlhttprequest的方式不好。首先应该利用IE7的native xmlhttprequest支持,而不是创建ActiveX控件XMLHTTP;其次读取xml dom直接用responseXML属性即可,读取requestText来创建XMLDOM完全是画蛇添足。

第二,他说调试困难。这说明他对Gadget的开发经验不足(当然,也拜微软糟糕的文档所赐)。因为有System.Debug.outputString方法,所以log基本没有问题。而且修改刷新也不需要关闭sidebar,只需要reload即可(虽然由于微软的bug,不能直接调用location.reload,但是可以用location.href = location.href的trick)。

2007-01-26

About OEM deployment of Vista Sidebar Gadget

Note: This artical is written in Chinese.


关于gadget的安装,目前总结有以下几种安装方式:

  1. 直接复制到用户目录下(%LOCALAPPDATA%\Microsoft\Windows Sidebar\Gadgets\),这种方式下,只有该用户可以看到该gadget。根据我的同事的试验,这种方式存在一个潜在的问题:如果安装程序请求了管理员权限,可能取得的用户目录将不是该用户的目录,而是该管理员的目录,这导致该用户无法看到该gadget。
  2. 打包成.gadget后,本地运行,会以对话框提示用户该gadget的来源和数字签名等信息,询问是否安装,这种方式的优点是,会直接安装到用户的运行列表中,而不像其他方式那样还需要用户自行加入sidebar,安装后的目录同第一种方式。
  3. 复制到共享gadget目录下(%ProgramFiles%\Windows Sidebar\Shared Gadgets),这种方式估计是微软指定的安放OEM所带gadget的方式,所有用户都可以看到gadget,但有两个缺点,一个是用户删除该gadget后,并没有真正删除该gadget,而是放入了SkipList中,该用户以后将无法看到该gadget,重新安装也没有用,只有关闭sidebar进程后修改配置文件才行但可到sidebar属性中选择“恢复Windows自带小工具”来恢复;另一个是用户没有共享gadget目录下的写权限,gadget程序的功能受到了一定限制(具体还需要更多测试)。

上述3种方式各有特点也各存在一些问题,我还会做进一步的测试,找到一个最佳方式。

1月28日更新:

可通过以下命令行指令修改权限:

icacls "%ProgramFiles%\Windows Sidebar\Shared Gadgets\MyGadget" /grant Users:(F)
icacls "%ProgramFiles%\Windows Sidebar\Shared Gadgets\MyGadget" /grant Users:(IO)(OI)(CI)(F)

注意,这需要你对MyGadget目录具有充分权限,例如使用管理员帐号操作。

2007-01-07

I just wanna commit nothing

A good article: if u don't want window to be opened, do not post "don't open me" on the window, just remove the handle of the window.

But the other example is questionable. The author suggest that disable the "commit my comments" button if the user hasn't entered any word. But it maybe make some users think comments is not allowed here. It's not like the "save" button, which should be disabled if nothing changed, there is subtle diffence which hard to express.

I understand the author don't like the popup alert dialog, so do I. A common way replace alert, is inserting the hint in red bold font below the textarea, or fadein/fadeout the messages on top of the page. The latter becomes very popular in recent web 2.0 sites.

In my opinion, popup dialog is not always evil. But the word is. "Please enter your comments" is too genteel and so boring. Let's say "Hey guy, you didn't enter anything!" with two choice: "Oops, it's a misplay..." and "I just wanna commit nothing!"

2006-12-31

A bug of Douglas Crockford's uber

In Douglas Crockford's famous Classical Inheritance in JavaScript, he write a function named 'uber' which simulate 'super' for OO programming. Someone pointed out a bug of it, but don't understand why and just try to write his own OO solution.

Below is the test case:


function BaseClass() {}
BaseClass.prototype.getName = function() {
    return "BaseClass(" + this.getId() + ")";
}
BaseClass.prototype.getId = function() {
    return 1;
}

function SubClass() {}
SubClass.inherits(BaseClass);
SubClass.prototype.getName = function() {
    return "SubClass(" + this.getId() + ") extends " +
        this.uber("getName");
}
SubClass.prototype.getId = function() {
    return 2;
}

function MyClass() {}
MyClass.inherits(SubClass);
MyClass.prototype.getName = function() {
    return "MyClass(" + this.getId() + ") extends " +
        this.uber("getName");
}
MyClass.prototype.getId = function() {
    // Should always return 2 which is the result of SubClass.getId()
    return this.uber("getId");
}

alert(new TopClass().getName());

//Expect result: "MyClass(2) extends SubClass(2) extends BaseClass(2)"
//Actual result:"MyClass(2) extends SubClass(1) extends BaseClass(1)"

I did some research about this interesting bug, and got the patch.

Douglas Crockford's original source


Function.prototype.inherits = function (parent) {
    var d = 0, p = (this.prototype = new parent());
    this.prototype.uber = function (name) {
        var f, r, t = d, v = parent.prototype;
        if (t) {
            while (t) {
                v = v.constructor.prototype;
                t -= 1;
            }
            f = v[name];
        } else {
            f = p[name];
            if (f == this[name]) {
                f = v[name];
            }
        }
        d += 1;
        r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
        d -= 1;
        return r;
    }
    return this;
}

My patched version


Function.prototype.inherits = function(parent) {
    var d = {}, p = (this.prototype = new parent());
    
    this.prototype.uber = function(name) {
     if (!(name in d)) d[name] = 0;
        var f, r, t = d[name], v = parent.prototype;
        if (t) {
            while (t) {
                v = v.constructor.prototype;
                t -= 1;
            }
            f = v[name];
        } else {
            f = p[name];
            if (f == this[name]) {
                f = v[name];
            }
        }
        d[name] += 1;
        r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
        d[name] -= 1;
        return r;
    }
}

The problem is because of d, which indicates the depth of supercall. In original code, every method share the same d, which will cause bug when nest call (one method call another). So give every method their own counter, solves the problem.

String format function for JavaScript

Note: This artical is the republication of my two posts A high performance string format function for JavaScript and Just another high performance string format function for JavaScript on csdn blog.


Last month, I wrote a logging tool for js, and to avoid performance depression, I need a string formatter function.

I found that though many js toolkit or framework provide string format function, such as Atlas, but they r not quite fast. Most r using String.replace(regex, func) to replace the placeholder(such as '{n}' or '$n'), but this function tend to slow, because every match will call the func, and js function calling is very expensive.

On the contrary, native functions r very fast, so to improve performance, we should utilize the native functions as possible as we can. A wonderful example is StringBuilder which use Array.join to concat the string.

So I create my String.format(), it's very fast.

Usage:


var name = 'world';
var result = 'Hello $1!'.format(name);
// result = "Hello world!"

var letters = String.format(
 '$1$2$3$4$5$6$7$8$9$10$11$12$13$14$15\
 $16$17$18$19$20$21$22$23$24$25$26',
 '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');
// letters = "abcdefghijklmnopqrstuvwxyz"

The later one almost same fast as the former one, no other implementation can have the same performance as I know.

Note:

  • It's depend on String.replace(regex, string), so u can use at most 99 placeholder($1 to $99), but if the script engine is too old, it maybe only support nine ($1 to $9) or not work at all (eg. JScript before 5.5?).
  • literal $ should be escape into $$ (two $).
  • $` and $' will be reomoved, and $& will replaced into some strange things :)
  • '$1 1'.format('a') result in 'a 1', if you want to strip the space, u can't write '$11'.format(...) because it will try to match the 11nd parameter, u should write '$011'.format(...) instead.
  • There is a magic character which you can't use anyway, currently I choose 0x1f (which means data separator in ascii and unicode).

Source code:


// Copyright (c) HE Shi-Jun , 2006
// Below codes can be used under GPL (v2 or later) or LGPL (v2.1 or later) license

if (!String._FORMAT_SEPARATOR) ...{
    String._FORMAT_SEPARATOR = String.fromCharCode(0x1f);
    String._FORMAT_ARGS_PATTERN = new RegExp('^[^' + String._FORMAT_SEPARATOR + ']*'
      + new Array(100).join('(?:.([^' + String._FORMAT_SEPARATOR + ']*))?'));
}
if (!String.format)
    String.format = function (s) ...{
    return Array.prototype.join.call(arguments, String._FORMAT_SEPARATOR).
    replace(String._FORMAT_ARGS_PATTERN, s);
}
if (!''.format)
    String.prototype.format = function () ...{
    return (String._FORMAT_SEPARATOR +
    Array.prototype.join.call(arguments, String._FORMAT_SEPARATOR)).
    replace(String._FORMAT_ARGS_PATTERN, this);
}

Below is just another format function:


// Copyright (c) HE Shi-Jun , 2006
// Below codes can be used under GPL (v2 or later) or LGPL (v2.1 or later) license

format2.cache = ...{};
function format2(pattern) ...{
    if (!(pattern in format2.cache)) ...{
        format2.cache[pattern] = new Function('"' + pattern.replace(/"/g, '\"').replace(/$([0-9]+)/g, '" + arguments[$1] + "').replace(/$$/g, '$') + '"');
    }
    return format2.cache[pattern](arguments);
}

Compare to previous method, it's even more fast in heavy using (especially on FireFox and Opera), because it's compile the pattern to function and cache it. But this method will waste memory. So the best practice is combining these two methods.

And the no cache version here, but not helpful, because it's lose the advantage of cacheable and will be very slow on Opera:


// Copyright (c) HE Shi-Jun , 2006
// Below codes can be used under GPL (v2 or later) or LGPL (v2.1 or later) license

function format3(pattern) ...{
    return eval('"' + pattern.replace(/"/g, '\"').replace(/$([0-9]+)/g, '" + arguments[$1] + "').replace(/$$/g, '$') + '"');
}

2006-12-27

Keep connection

The seaquake occured yestereve(2006-12-26T20:25+8:00) cause at least sixeight cables damaged. It affects the internet connections from China to USA and Europe. Most people, include me, can't access MSN, Yahoo, MySpace and many other sites. As a MSN user, I'm very worry about losing the connection to the world in the next two weeks.

But I'm pleased that I can still connect most Google services, such as gmail, gtalk, google reader, and blogger. Someone said that is because Google has some servers at China. But I doubt whether there are some servers of blogger at China? Another guess is Google services are mainly base on the continent cables not the sea cables. The result of TraceRoute support this.

Not surprisingly, I have read the arguments about .com domain and drum for .cn domain again, which says .cn is controlled by chinese people ourselves, and won't be affected by such accident. Ridiculous, let's make our own China Intranet, put off Internet...

Anyway, It's a good opportunity to prove my choice about blogger is reasonable.

2006-12-25

Hello world

For every programmer, it's the first step to write "Hello world" case. Here is mine.

With a new year coming, I finally start this new blog. In past days, I am maintaining three blogs, csdn, sfo and my-donews. All three are in chinese. Though I wrote a few posts in english, but the UI(web pages) of them are in chinese which may affect sth (I'm not sure).

Anyway, I want to be more open to the whole worlds, esepecially in the technique fields. Until now there are too many blog host sites(eg. wordpress.com) are fobidden by China GWF. Fortunately, (google do sth and) blogger comes back for china users. It's one of the most famous and the best blog host, and it's an international place. So I'm here.

To be honest, I will still post many posts in chinese, but at least with an additional title and abstract in english.

BTW, after register, what I first do is changing the settings of blogger, which default to localized chinese interface. Hum... It's not as easy as I thought. There are two, one is settings->formatting->language and the other is dashboard->change language. The latter determines the UI language of author's manage dashboard, but the lang used by toolbar on top of the pages also depends on it. It's obviously a wrong design, because the lang settings of the author should not affect the readers.