人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

June 5, 2007

为什么在派生类中再次实现一个Interface?

Filed under: .NET, C#

比如:
TemplateContorl实现了INameContainer,其派生类UserContorl又实现INameContainer.

INameContainer仅仅是一个marker interface,其用途也就是看一个class是否实现了此interface,
UserContorl就算不实现INameContainer,仍然可以cast为INameContainer.

又如:
StringCollection,实现了IList, ICollection, IEnumerable,而IList实现了ICollection, IEnumerable,
ICollection又实现了IEnumerable.
其目的在于可在StringCollection中显式实现这些Interface,对一些方法的参数类型进行强化:
public int IndexOf(string value);
int IList.IndexOf(object value)
{
return this.IndexOf((string) value);
}
以便在编译阶段发现问题.

考察如下代码:
interface ITest
{
void ShowMsg();
}

interface IITest:ITest
{
}

public class TestA : ITest
{
public void ShowMsg()
{

Console.WriteLine(”TestA:”);

}

void ITest.ShowMsg()
{

Console.WriteLine(”TestA:ITest”);

}
}
public class TestB :TestA, ITest
{
public void ShowMsg() //Complier warning,hides inherited member ‘TestA.ShowMsg()’
{
Console.WriteLine(”TestB:”);
}
void ITest.ShowMsg()
{

Console.WriteLine(”TestB:ITest”);
}
}

TestB test = new TestB();
test.ShowMsg();
(test as TestA).ShowMsg();

ITest itest = new TestB();
itest.ShowMsg();
输出:
TestB:
TestA:
TestB:ITest
如果去掉TestB对ITest的实现, (test as ITest).ShowMsg();将输出TestB:

June 4, 2007

Working with Vista .net 3.0

Filed under: .NET, Windows platform

1.Virtual Studio
Vista只支持 vb6和vs2005, 使用vs2005
需要VS2005 sp1 和 vs2005 sp1 update for vista

2.sql server
Microsoft SQL Server 2005 requires SP2 to run on Windows Vista.

3.IIS
http://blogs.msdn.com/webdevtools/archive/2006/09/18/761206.aspx
Developing Web Applications on Windows Vista with Visual Studio 2005
Select Web Management Tools->IIS6 Management Compatibility->IIS Metabase and IIS6 configuration compatiblity
Select WWW service->ASP.ET
Run Visual Studio 2005 in the context of an administrator account

4..NET framework
Microsoft .NET Framework 3.0 Deployment Guide
http://msdn2.microsoft.com/en-us/library/aa480173.aspx

SDK for vista and .net framework 3.0
Visual Studio 2005 extensions for .NET Framework 3.0

Visual Studio 2005 Extensions for WwF
Visual Studio 2005 Extensions for WCF, WPF 。

May 31, 2007

为什么一个COM组件被重复下载

Filed under: .NET, 使用技巧

不知何故,一个COM组件被重复下载,以下是针对这个问题的检查点:
1.Check <Windows Dir>\Downloaded Program Files

2.Check 注册表中My Computer\HKEY_CLASSES_ROOT\<Class Name>\CLSID

后发现,已下载的com组件的version与HTML中指定的版本不同,故反复下载.
<OBJECT id=<??????> onresize=\”window.oExportsDialog.fnSetSize ()\” codeBase=http://<myhost>/???.cab#Version=1,0,21,1975 data=data:application/x-oleobject;base64,+jIurin7Qky/+XrPoasKGxAHAAATIQAA3BEAAA== border=0
classid=CLSID:??????????????????????? name=????></OBJECT>

May 30, 2007

authentication and authorization

Filed under: .NET

这两个单词我一直记不住
authentication (checking a user’s identity) and authorization (verifying a user’s right to access resources).
authentication,就象有人敲门时问”谁!”,对应”then”的发音.
authorization,是看用户的权限(right),对应”ri”的发音.

May 29, 2007

COM Interop

Filed under: .NET, C#

1. null 参数的传入
COM components don’t support parameter overloading, so for each value in a parameter list, you’ve got to pass in something, even if it does nothing.
Moreover, COM parameters are always passed by reference, which means that you can’t pass in a null value.

Instead of creating “dummy” object variables, the Type.Missing field can be used.
class Program
{
private static Object OptionalParamHandler = Type.Missing;

static void Main(string[] args)
{
Application NewExcelApp = new Application();
NewExcelApp.Worksheets.Add(ref OptionalParamHandler,
ref OptionalParamHandler, ref OptionalParamHandler,
ref OptionalParamHandler);
}
}

2. RuntimeWrappedException(new in .net 2.0)
COM errors won’t be CLS compliant, they won’t be caught with Exception, .net 2.0提供
RuntimeWrappedException封装了Non CLS-Compliant的异常.
代码一般写成:
private static void IllustrateExceptions()
{
try
{
// Something that throws an exception
}
catch (Exception ex)
{
// In 1.x this will catch only CLS-Compliant
// In 2.0 both CLS and Non CLS-Compliant will
// be caught by this block.
}
catch
{
// All exceptions, CLS-Compliant and Non CLS-Compliant are caught
}
}

3. COM interop的缺点:

  • Static members COM objects are fundamentally different from .NET types. One of the differences is lack of support for static members.

  • Parameterized constructors COM types don’t allow parameters to be passed into a constructor. This limits the control you have over initialization and the use of overloaded constructors.

  • Inheritance One of the biggest issues is the limitations COM objects place on the inheritance chain. Members that shadow members in a base class aren’t recognizable, and therefore, aren’t callable or usable in any real sense.

  • Portability Operating systems other than Windows don’t have a registry. Reliance on the Windows registry limits the number of environments a .NET application can be ported to.

如果一个.NET Class要被COM使用,就必须:
提供无参数的构造函数,暴露给COM的type和type member必须为public.
Abstract clsss 不能被COM使用.

May 21, 2007

How to check windows username and password

Filed under: Code snippets

WindowsIdentity
http://support.microsoft.com/kb/319615/zh-cn

static public bool CheckAccount(string userName, string pwd)
{
string user = userName;
string domin = System.Environment.MachineName;
IntPtr tokenHandle = new IntPtr(0);

if (userName.Contains(”\\”))
{
string[] arr = userName.Split(new char[] { ‘\\’});
user = arr[1];
domin = arr[0];
}

// Call LogonUser to obtain an handle to an access token.
bool returnValue = LogonUser(user, domin, pwd,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
return returnValue;
}

[DllImport(”advapi32.dll”, SetLastError = true)]
public extern static bool LogonUser(String lpszUsername, String lpszDomain,
String lpszPassword, int dwLogonType,
int dwLogonProvider, ref IntPtr phToken);

const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
const int SecurityImpersonation = 2;

April 27, 2007

能否在函数中修改string类型的函数参数

Filed under: C#

string test = “string”;
this.funString(test);
Console.WriteLine(test); //依然输出”string”

private void funString(string input)
{
input = “new string”;
}
如果换一种写法,答案就很明了:
string a = “string a”;
string b = a;
a = “new string a”;

Console.WriteLine(a); // new string a
Console.WriteLine(b); // string a

这是由于string 虽然是reference 类型,但:
A String object is called immutable (read-only) because its value cannot be modified once it has been created.
Methods that appear to modify a String object actually return a new String object that contains the modification.

funString中的input是test的一个reference, 但修改input不会修改test, 就像上个例子中的a和b.

此时生成的IL代码为:
.method private hidebysig instance void funString(string input) cil managed
{
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldstr “new string” //把 “new string”压栈
IL_0006: starg.s input //把栈顶元素即 “new string” 赋给input
IL_0008: ret
} // end of method Form1::funString

如果把代码写成
private void funRefString(ref string input)
{
input = “new string”;
}
则会生成代码
.method private hidebysig instance void funRefString(string& input) cil managed
{
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.1 //把1号参数,即input压栈, 这是和funString的最核心的不同, funString通过忽略这条指令来
//保证string的immutable
//同时,此处没有ldind.ref 这条指令,对string进行了特殊处理
IL_0002: ldstr “new string” //把 “new string”压栈
IL_0007: stind.ref //把栈顶的两个元素弹出来,进行ref 赋值.
IL_0008: ret
} // end of method Form1::funRefString

此时直接修改了test的值.

如果fun的参数是其他reference类型,使用或不使用ref关键字生成的代码也有所不同,但执行结果完全相同:
.method private hidebysig instance void funForm(class [System.Windows.Forms]System.Windows.Forms.Form f) cil managed
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldstr “new Form Text”
IL_0007: callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Text(string)
IL_000c: nop
IL_000d: ret
} // end of method Form1::funForm

.method private hidebysig instance void funRefForm(class [System.Windows.Forms]System.Windows.Forms.Form& f) cil managed
{
// Code size 15 (0xf)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldind.ref //这是唯一的不同, 其中用是把栈顶元素弹出,再把其address压栈,对于reference type来说,没有任何意义.
IL_0003: ldstr “new Form Text”
IL_0008: callvirt instance void [System.Windows.Forms]System.Windows.Forms.Control::set_Text(string)
IL_000d: nop
IL_000e: ret
} // end of method Form1::funRefForm

March 21, 2007

Using Configuration.Section to access subsection

Filed under: .NET, Code snippets

Using Configuration.Section to access subsection
Copy from http://geekswithblogs.net/mnf/archive/2006/05/12/77981.aspx

I have a section in Web.Config:

<applicationSettings>

<FSBsnsCsLib.Properties.Settings>

</FSBsnsCsLib.Properties.Settings>

</applicationSettings>

I’ve tried to access inner section using shortcut “Section/Subsection”

string sSectionName=”applicationSettings/FSBusinessLib.My.MySettings”;
System.Configuration.ClientSettingsSection sectSettings = (ClientSettingsSection)config.Sections[sSectionName];

but it returned null.

The correct way is the following:

conststringcnstApplicationSection = “applicationSettings”;
ConfigurationSectionGroupgrpApplicationSection = config.SectionGroups[cnstApplicationSection];
string sSectionName=”FSBusinessLib.My.MySettings”;
System.Configuration.ClientSettingsSection sectSettings = grpApplicationSection .Sections[sSectionName];

March 7, 2007

.net2.0 自带的压缩/解压类GZipStream Class

Filed under: .NET, Code snippets

http://www.codeguru.com/csharp/.net/net_data/sortinganditerating/article.php/c13375/
http://msdn2.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx

支持gzip格式(见RFC 1952),生成的压缩文件后缀为.gz,不能压缩大于4GB的文件
和XP内置的zip格式不兼容

//–压缩
FileStream fs = new FileStream(”es_resume.doc”, FileMode.Open);
byte[] input = new byte[fs.Length];
fs.Read(input, 0, input.Length);
fs.Close();

FileStream fsOutput = new FileStream(”es_resume.gzip”,
FileMode.Create,
FileAccess.Write);
GZipStream zip = new GZipStream(fsOutput, CompressionMode.Compress);

zip.Write(input, 0, input.Length);
zip.Close();
fsOutput.Close();

//–解压
FileStream fs = new FileStream(”es_resume.gzip”, FileMode.Open);
FileStream fsOutput = new FileStream(”es_resume2.doc”,
FileMode.Create,
FileAccess.Write);
GZipStream zip = new GZipStream(fs, CompressionMode.Decompress, true);

byte[] buffer = new byte[4096];
int bytesRead;
bool continueLoop = true;
while (continueLoop)
{
bytesRead = zip.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
fsOutput.Write(buffer, 0, bytesRead);
}
zip.Close();
fsOutput.Close();
fs.Close();

March 2, 2007

WM_POPUPSYSTEMMENU message

Filed under: .NET

在task bar上点击鼠标右键,会弹出system menu,此消息为:
WM_POPUPSYSTEMMENU(0x313)

February 28, 2007

String Resource使用

Filed under: .NET

1.方法1
把resource文件(Strings.resx和Strings.zh-CHS.resx)作为Embedded Resource build到Assembly中.
假定生成的assembly的default namespace为MyApp,resource位于Res 目录下,
则会在assembly中生成名为MyApp.Res.Strings.resources的resource,
同时生成zh-CHS目录,及:GMailClient.resources.dll,其中包含名为GMailClient.Res.Strings.zh-CHS.resources的资源.

//First parameter is: Assemlby default namespace + folder + base resource name
//Second parameter is : Assembly contails the
resourceManager = new ResourceManager(”MyApp.Res.Strings”, System.Reflection.Assembly.GetExecutingAssembly());
StringResources.GetString(resId);

测试:
使用 System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(”zh-CN”);
设定UICulture,ResourceManager会使用这个Culture来读取对应的resource.

注意:Culture ‘zh-CHS’ is a neutral culture(与某种语言关联但不与国家/地区关联的区域性). It cannot be used in formatting and parsing and therefore cannot be set as the thread’s current culture.BUT, Culture ‘zh-CHS’ can be set as Current UI Culture.
在这里,我有意生成名为GMailClient.Res.Strings.zh-CHS.resources的resource(Chinese, neutral),但设定UICulture为zh-CN(PRC:Special),读取结果正确.可推测其逻辑为:对于一个Special Culture,找不到相应的
资源,就尝试其对应的neutral culture对应的资源.

对于NeutralCulture和:specified culture可以使用下面的函数进行转化
public static CultureInfo GetNeutralCulture(string cultureName)
{
System.Globalization.CultureInfo c = new System.Globalization.CultureInfo(cultureName);
if (! c.IsNeutralCulture)
{
c = new System.Globalization.CultureInfo(c.LCID & 0x3FF); //低10位
}
return c;
}
举例
zh-CHS 0x0004 Chinese (Simplified) , Neutral
zh-CN 0x0804 Chinese - China

zh-CHT 0x7C04 Chinese (Traditional) , Neutral
zh-TW 0x0404 Chinese - Taiwan
zh-HK 0x0C04 Chinese - Hong Kong SAR
zh-MO 0x1404 Chinese - Macao SAR
zh-SG 0x1004 Chinese - Singapore

下面的代码可以显示zh的相关的culture
foreach ( CultureInfo ci in CultureInfo.GetCultures( CultureTypes.AllCultures ) )
{
if ( ci.TwoLetterISOLanguageName == “zh” )
{
Console.Write( “{0,-6} {1,-40}”, ci.Name, ci.EnglishName );
if ( ci.IsNeutralCulture ) {
Console.WriteLine( “: neutral” );
}
else {
Console.WriteLine( “: specific” );
}
}
}
/*
This code produces the following output.

zh-CHS Chinese (Simplified) : neutral
zh-TW Chinese (Taiwan) : specific
zh-CN Chinese (People’s Republic of China) : specific
zh-HK Chinese (Hong Kong S.A.R.) : specific
zh-SG Chinese (Singapore) : specific
zh-MO Chinese (Macao S.A.R.) : specific
zh-CHT Chinese (Traditional) : neutral

*/

方法2:自己搞

public class PublicResourcesManager
{
private ResXResourceReader _resXReader;
private IDictionaryEnumerator _resXEnum;

public PublicResourcesManager(string resourceRootFolder, string resourceFileName)
{
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentUICulture;
string resourceFolder = resourceRootFolder.TrimEnd(’\\’);
string fileName = String.Format(”{0}\\{1}\\{2}”, resourceFolder, ci.Name, resourceFileName);

try
{
// first try [country][region] folder…
_resXReader = new ResXResourceReader(fileName);
_resXEnum = _resXReader.GetEnumerator();
if (_resXEnum!=null)
return;
}
catch(Exception ex) {}

_resXReader.Close();

try
{
// try [country] folder (if culture isn’t a neutral culture…
if (!ci.IsNeutralCulture)
{
ci = new CultureInfo(ci.LCID & 0x03ff);

fileName = String.Format(”{0}\\{1}\\{2}”, resourceFolder, ci.Name, resourceFileName);
_resXReader = new ResXResourceReader(fileName);

_resXEnum = _resXReader.GetEnumerator();
if (_resXEnum!=null)
return;
}
}
catch(Exception ex) {}

_resXReader.Close();

try
{
// just try root folder…
fileName = String.Format(”{0}\\{1}”, resourceFolder, resourceFileName);
_resXReader = new ResXResourceReader(fileName);
_resXEnum = _resXReader.GetEnumerator();
}
catch(Exception ex)
{
string err = ex.Message;
}
}

public string GetString(string name)
{
string str = “”;

if (_resXEnum != null)
{
_resXEnum.Reset();
while (_resXEnum.MoveNext())
{
if (string.Compare(name, _resXEnum.Key.ToString(), true, CultureInfo.InvariantCulture)==0)
str=(string)_resXEnum.Value;
}
}
return str;
}
}

此处的逻辑是先找Folder\CultureName\Resource来找
如果失败,就把Culture转成neutral culture,再按Folder\CultureName\Resource找一次.
再失败,就尝试Folder\Resource

最常用的还是.net自己提供的resource管理机制,
在Form的property grid中可以设定form的Language,会为Form自动生成该Language的resource:
如MainForm.zh-CHS.resx,这些resource会被设置为Embedded Resource,其内容为:
<data name=”$this.Icon” type=”System.Drawing.Icon, System.Drawing”>
<value>…Binary Content…<value>
</date>
<data name=”$this.Text” type=”System.Drawing.Icon, System.Drawing”>
<value>Hello!<value>
</date>

在InitializeComponent()会生成代码
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));

resources.ApplyResources(this, “$this”);
resources.ApplyResources(this.pictureBox1, “pictureBox1″);

把resourc中的内容读出,并设置到from上.

3.使用时:
this.pictureBox1.Image = global::MyApplication.Properties.Resources.Winter;
不要轻易手动修改这些自动生成的代码,容易乱套.

February 9, 2007

Writing Quality Code by FxCop team

Filed under: .NET

Fxcop team 发布了一本九十几页的小书<<The Quality Code Handbook>>
http://blogs.msdn.com/fxcop/archive/2007/02/07/free-writing-quality-code-e-book-with-information-on-both-native-and-managed-code-analysis.aspx
该书使用的文件格式并不常见,需要阅读工具:http://www.dnaml.com/

November 22, 2006

How to Get Neutral Culture

Filed under: .NET, Code snippets

string resourceFolder = “Folder”;
string resourceFileName = “ResFile.resx”;
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
string fileName = String.Format(”{0}\\{1}\\{2}”, resourceFolder, ci.Name, resourceFileName);

Console.WriteLine(fileName);

ci = new CultureInfo(ci.LCID & 0x03ff);

fileName = String.Format(”{0}\\{1}\\{2}”, resourceFolder, ci.Name, resourceFileName);
Console.WriteLine(fileName);

ci = new CultureInfo(”zh-CHS”);
Console.WriteLine(ci.IsNeutralCulture); //Note! it’s true

ci = new CultureInfo(”fr-FR”);
Console.WriteLine(ci.IsNeutralCulture);

November 10, 2006

GAC里有什么?

Filed under: .NET

Keywords:GAC,GAC_32,GAC_MSIL,NativeImages

安装了.net2.0后,在命令行下可以看到
c:\windows\assembly目录下有如下内容
2006-04-08 00:32 <DIR> GAC
2006-11-10 21:55 <DIR> GAC_32
2006-04-07 23:39 <DIR> GAC_MSIL
2006-04-08 00:32 <DIR> NativeImages1_v1.1.4322
2006-10-20 04:23 <DIR> NativeImages_v2.0.50727_32
2006-10-19 02:18 <DIR> temp
2006-10-19 02:19 <DIR> tmp

GAC中是.net1.1的assembly

从.net2.0开始支持64bit,理论上.net assembly是MSIL代码,不用关心平台是
32位还是64位,但有些Manage c++的assembly同时包含MSIL code和Native code,
所以出现了32bit .net assembly 和64bit .net assemlby,在32位平台上,只需要安装
32bit .net assembly, 在64位平台上,要能直接运行32位的程序(Windows on windows),
所以要同时安装32bit .net assembly和64bit .net assembly,然而不是所有的assembly
都包含native code,所以可以把.net assembly分为两部分,所以在32位机器上会看到
GAC_32和GAC_MSIL这两个目录,在64位机器上会看到GAC_32,GAC_64,
GAC_MSIL这三个目录.打开GAC_32和GAC_MSIL这两个目录,可以看到GAC_MSIL
中包含大部分.net framework assembly和所有应用程序的assemly,GAC_32中包含
mscorlib等底层的assembly.

打开NativeImages目录,可以看到目录中包含所有的.net framework assembly的Native
Image,可见为了提高性能,MS为所有的.net framework assembly生成了image,

temp和tmp是两个空目录.

c:\windows\assembly下的隐藏文件Desktop.ini指定了使用Shell扩展SHFusion.dll来显示目录下的文件.

October 28, 2006

FWK Design Guidelines CD

Filed under: .NET

Transcripts for the MSDN Designing .NET Class Libraries chats (Brad Abrams’ Blog)
http://blogs.msdn.com/brada/archive/2005/07/11/437388.aspx

MSDN: Designing .NET Framework Class Libraries cross index (More chat transcripts by CLR PM)
http://www.bluebytesoftware.com/blog/PermaLink,guid,26be120b-7b86-47f2-bb2c-1c8a063807a5.aspx

Designing .NET Class Libraries (MSDN 所有的讲座)
http://msdn2.microsoft.com/en-us/netframework/aa497250.aspx

————————————-
Setting The Stage
by Brad Abrams
————————————-

————————————
API Usability
by Steven Clarke(http://blogs.msdn.com/stevencl/default.aspx)
http://msdn.microsoft.com/chats/transcripts/net/2005_0223_apiusability.aspx
http://www.microsoft.com/seminar/shared/asp/view.asp?url=/seminar/en/20040929usability/manifest.xml&rate=1
————————————
了解API的使用者(Target audience),提供易用,好懂的API

1.如何收集反馈,在开发周期中检查是否达到设计目标
2.API的3重境界:
能工作
易懂的API,用户明白如何工作,
用户可以预测(predict)如何使用

3.没有程序员愿意学习如何使用API

4.如何设计API
从设计开始就注意
Use the Cognitive Dimensions
Understand users’ scenarios.
Get feedback

5. Cognitive Dimensions
abstraction level
Learning Style : Top down
Working Framework : work set
Work-Step Unit : Develop 完成一个工作所需的步骤
Premature Commitment
Progressive Evaluation
9. Gathering User Feedback
Early and often
API review
Expreience review
Usablity study

14. Common Usability Problems

————————————-
Designing Progressive APIs
by Krzysztof Cwalina {CLR Team PM}
http://www.microsoft.com/seminar/shared/asp/view.asp?url=/seminar/en/20040929prog_apis/manifest.xml&rate=2
————————————-
3种程序员
1. Vertical
2. Pragmatic
3. Einsteins
vb, MFC, ATL

Progressive API
1.易学:
80/20 Rule
Defaults and helps
2.Powerful
Richness
Performance
Scalablity
3.Consistent

设计原则: Scenario-Driven
Defing top scenario
Write code samples first, design API later
Make top scenario easy, make the rest possible
Usablity test top scenarios

设计原则2: Supporting experimentation

设计原则3: Aggregate component

设计原则4: Self-Documenting APIs
命名
Exception
设计原则5: Keeping Things Simple
Number of objects
Dependencies
Lines of code
OO

————————————-
Designing Inheritance Hierarchies
by Brad Abrams
http://www.microsoft.com/seminar/shared/asp/view.asp?url=/seminar/en/20040929hierarchies/manifest.xml&rate=2
————————————-
Keywords: Interface versus base class
So you can do the minimum now, and then add more to it in the future.

Overriding的思考点:
1.不要改变base class 定义的 contract
2.通常需要call base, 除非有充足的理由.
3.不要让class写出这样的code:
if( obj is network stream) …
else if(obj is …) …

Interface
Explicit Implementation

————————————-
FxCop in Depth
by Jeffrey Van Gogh, Michael Murray
http://www.microsoft.com/seminar/shared/asp/view.asp?url=/seminar/en/20041012fxcop/manifest.xml&rate=0
http://www.microsoft.com/china/msdn/events/webcasts/shared/msdntv/episode.aspx?xml=/china/msdn/events/webcasts/msdntv/20031204FxCopMM/manifest.xml
————————————-
FxCop干了什么:
Access IL metadata
Examine IL method bodies
Walk call graphs
Determine some argument
Use spelling checker (if office is installed)
规则分类:
COM
Design
Globalization
Naming
Performance
Usage
Security
Custom

————————————-
Designing for Managed Memory World(经典!)
by Brad Abrams
http://www.microsoft.com/seminar/shared/asp/view.asp?url=/seminar/en/20040929memory_world/manifest.xml&rate=1
————————————-
Framework的作者需要封装native 资源
~ 被编译器翻译为
protected override void Finalize()
{
try
{

}
finally
{
base.finalize();
}
}

何时需要~即 Finalize()
仅在需要释放外部资源时.

Dispose Pattern
Dispose()会 被多次调用
Dispose()不能throw exceptiion
if(disposed)
throw new ObjectDisposedException();

使用:
using( Resource res = new Resource())
{
res.DoWork();
}

GC.AddMemoryPressure()
GC.RemoveMemoryPressure()

HandleCollector
.NET Framework 2.0 中新增。
跟踪未处理的句柄,并在达到指定阈值时强制执行垃圾回收。

————————————-
Member Types
by Brad Abrams
http://www.microsoft.com/seminar/shared/asp/view.asp?url=/seminar/en/20040929member_types/manifest.xml&rate=2
————————————-
1.Constructor
在c++中不要在一个Constructor中throw exception.
在c#中可以这样做,Finalizer仍旧可以调用,GC仍旧可被执行.

永远显式定义一个default constuctor,以免错误:
//v1
public class Foo
{
}
此时 Foo f = new Foo(); 正常工作

//v2
pubolc class Foo
{
public Foo(int value)
}
此时 Foo f = new Foo(); 出错

So what that essentially means is between the two releases, you’ve removed the default
one and added this new one, so that will break code.

2. Overloading
参数少的函数会假定传入defatul value
参数的顺序要一致,参数最多的函数最好定义为virtual

Performance:
使JIT生成 in-line函数:
少使用virutal method
不要定义过多的局部变量

Property and Method:
property 返回不变的值如: string Name{get;},
从逻辑上说是一个data member
method 返回变化的值: Guid GetNext(){};conversion,
复杂的逻辑
可能不会马上返回.

不要定义用来生成snapshotting的array 类型的property,, 防止这样的写法:
for(int i= 0; i < list.Length; i++)
{
list.All[i]….
}

Event Pattern
protected void DoClick()
{
PaintDown();
try
{
onClick(); //call event handler
}
finally
{
if(windowHandler != null)
{
PaintUp();
}
}
}

Static Member 的用途及使用pattern
Singleton Pattern
Factory methods

Ref and Out Parameters:
主要用于interop
Ref是CLR的特性
Out是c#的属性

————————————-
Naming Conventions
by Brad Abrams
http://msdn2.microsoft.com/en-us/netframework/aa497259.aspx
————————————-
All type and publicly exposed member are PascalCased
Parameter are camelCased

So also the principle of least surprise, you want to do what developers expect.

Type Naming:
1.使用名词
2.如果从Exception派生, 命名为ArgumetException
————————————-
Packaging, Assemblies and Namespaces
by Michael Murray (Longhon SDK Team PM)

Assemply 和Namespace 为什么要使用不同的名字?
Assemply名称使人易于找出需要reference的dll
不同版本的Type最好位于不同的assembly.
同一个Assemlby中的代码的信任级别是相同的.
改动会引发rebuild

————————————-

————————————-
Performance
by Rico Mariani, Maoni Stephens
————————————-

————————————-
Rich Type System

————————————-

October 23, 2006

Java面试中的陷阱(转贴)

Filed under: C#

第一,谈谈final, finally, finalize的区别。

final?修饰符(关键字)如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承。因此一个类不能既被声明为 abstract的,又被声明为final的。将变量或方法声明为final,可以保证它们在使用中不被改变。被声明为final的变量必须在声明时给定初值,而在以后的引用中只能读取,不可修改。被声明为final的方法也同样只能使用,不能重载

finally?再异常处理时提供 finally 块来执行任何清除操作。如果抛出一个异常,那么相匹配的 catch 子句就会执行,然后控制就会进入 finally 块(如果有的话)。
finalize?方法名。java 技术允许使用 finalize() 方法在垃圾收集器将对象从内存中清除出去之前做必要的清理工作。这个方法是由垃圾收集器在确定这个对象没有被引用时对这个对象调用的。它是在 object 类中定义的,因此所有的类都继承了它。子类覆盖 finalize() 方法以整理系统资源或者执行其他清理工作。finalize() 方法是在垃圾收集器删除对象之前对这个对象调用的。

第二,anonymous inner class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)?

匿名的内部类是没有名字的内部类。不能extends(继承) 其它类,但一个内部类可以作为一个接口,由另一个内部类实现。

第三,static nested class 和 inner class的不同,说得越多越好(面试题有的很笼统)。
nested class (一般是c++的说法),inner class (一般是java的说法)。java内部类与c++嵌套类最大的不同就在于是否有指向外部的引用上。具体可见http: //www.frontfree.net/articles/services/view.asp?id=704&page=1
注: 静态内部类(inner class)意味着1创建一个static内部类的对象,不需要一个外部类对象,2不能从一个static内部类的一个对象访问一个外部类对象

第四,&和&&的区别。
&是位运算符。&&是布尔逻辑运算符。

第五,hashmap和hashtable的区别。
都属于map接口的类,实现了将惟一键映射到特定的值上。
hashmap 类没有分类或者排序。它允许一个 null 键和多个 null 值。
hashtable 类似于 hashmap,但是不允许 null 键和 null 值。它也比 hashmap 慢,因为它是同步的。

第六,collection 和 collections的区别。
collections是个java.util下的类,它包含有各种有关集合操作的静态方法。
collection是个java.util下的接口,它是各种集合结构的父接口。

第七,什么时候用assert。
断言是一个包含布尔表达式的语句,在执行这个语句时假定该表达式为 true。如果表达式计算为 false,那么系统会报告一个 assertionerror。它用于调试目的:
assert(a > 0); // throws an assertionerror if a <= 0
断言可以有两种形式:
assert expression1 ;
assert expression1 : expression2 ;
expression1 应该总是产生一个布尔值。
expression2 可以是得出一个值的任意表达式。这个值用于生成显示更多调试信息的 string 消息。
断言在默认情况下是禁用的。要在编译时启用断言,需要使用 source 1.4 标记:
javac -source 1.4 test.java
要在运行时启用断言,可使用 -enableassertions 或者 -ea 标记。
要在运行时选择禁用断言,可使用 -da 或者 -disableassertions 标记。
要系统类中启用断言,可使用 -esa 或者 -dsa 标记。还可以在包的基础上启用或者禁用断言。
可以在预计正常情况下不会到达的任何位置上放置断言。断言可以用于验证传递给私有方法的参数。不过,断言不应该用于验证传递给公有方法的参数,因为不管是否启用了断言,公有方法都必须检查其参数。不过,既可以在公有方法中,也可以在非公有方法中利用断言测试后置条件。另外,断言不应该以任何方式改变程序的状态。

第八,gc是什么? 为什么要有gc? (基础)。
gc是垃圾收集器。java 程序员不用担心内存管理,因为垃圾收集器会自动进行管理。要请求垃圾收集,可以调用下面的方法之一:
system.gc()
runtime.getruntime().gc()

第九,string s = new string(”xyz”);创建了几个string object?
两个对象,一个是”xyx”,一个是指向”xyx”的引用对象s。

第十,math.round(11.5)等於多少? math.round(-11.5)等於多少?
math.round(11.5)返回(long)12,math.round(-11.5)返回(long)-11;

第十一,short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错?
short s1 = 1; s1 = s1 + 1;有错,s1是short型,s1+1是int型,不能显式转化为short型。可修改为s1 =(short)(s1 + 1) 。short s1 = 1; s1 += 1正确。

第十二,sleep() 和 wait() 有什么区别? 搞线程的最爱
sleep()方法是使线程停止一段时间的方法。在sleep 时间间隔期满后,线程不一定立即恢复执行。这是因为在那个时刻,其它线程可能正在运行而且没有被调度为放弃执行,除非(a)”醒来”的线程具有更高的优先级
(b)正在运行的线程因为其它原因而阻塞。
wait()是线程交互时,如果线程对一个同步对象x 发出一个wait()调用,该线程会暂停执行,被调对象进入等待状态,直到被唤醒或等待时间到。

第十三,java有没有goto?
goto?java中的保留字,现在没有在java中使用。

第十四,数组有没有length()这个方法? string有没有length()这个方法?
数组没有length()这个方法,有length的属性。
string有有length()这个方法。

第十五,overload和override的区别。overloaded的方法是否可以改变返回值的类型?
方法的重写overriding和重载overloading是java多态性的不同表现。重写overriding是父类与子类之间多态性的一种表现,重载overloading是一个类中多态性的一种表现。如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (overriding)。子类的对象使用这个方法时,将调用子类中的定义,对它而言,父类中的定义如同被”屏蔽”了。如果在一个类中定义了多个同名的方法,它们或有不同的参数个数或有不同的参数类型,则称为方法的重载(overloading)。overloaded的方法是可以改变返回值的类型。

第十六,set里的元素是不能重复的,那么用什么方法来区分重复与否呢? 是用==还是equals()? 它们有何区别?
set里的元素是不能重复的,那么用iterator()方法来区分重复与否。equals()是判读两个set是否相等。
equals()和==方法决定引用值是否指向同一对象equals()在类中被覆盖,为的是当两个分离的对象的内容和类型相配的话,返回真值。

第十七,给我一个你最常见到的runtime exception。
arithmeticexception, arraystoreexception, bufferoverflowexception, bufferunderflowexception, cannotredoexception, cannotundoexception, classcastexception, cmmexception, concurrentmodificationexception, domexception, emptystackexception, illegalargumentexception, illegalmonitorstateexception, illegalpathstateexception, illegalstateexception,
imagingopexception, indexoutofboundsexception, missingresourceexception, negativearraysizeexception, nosuchelementexception, nullpointerexception, profiledataexception, providerexception, rasterformatexception, securityexception, systemexception, undeclaredthrowableexception, unmodifiablesetexception, unsupportedoperationexception

第十八,error和exception有什么区别?
error 表示恢复不是不可能但很困难的情况下的一种严重问题。比如说内存溢出。不可能指望程序能处理这样的情况。
exception 表示一种设计或实现问题。也就是说,它表示如果程序运行正常,从不会发生的情况。

第十九,list, set, map是否继承自collection接口?
list,set是

map不是

第二十,abstract class和interface有什么区别?
声明方法的存在而不去实现它的类被叫做抽象类(abstract class),它用于要创建一个体现某些基本行为的类,并为该类声明方法,但不能在该类中实现该类的情况。不能创建abstract 类的实例。然而可以创建一个变量,其类型是一个抽象类,并让它指向具体子类的一个实例。不能有抽象构造函数或抽象静态方法。abstract 类的子类为它们父类中的所有抽象方法提供实现,否则它们也是抽象类为。取而代之,在子类中实现该方法。知道其行为的其它类可以在类中实现这些方法。
接口(interface)是抽象类的变体。在接口中,所有方法都是抽象的。多继承性可通过实现这样的接口而获得。接口中的所有方法都是抽象的,没有一个有程序体。接口只可以定义static final成员变量。接口的实现与子类相似,除了该实现类不能从接口定义中继承行为。当类实现特殊接口时,它定义(即将程序体给予)所有这种接口的方法。然后,它可以在实现了该接口的类的任何对象上调用接口的方法。由于有抽象类,它允许使用接口名作为引用变量的类型。通常的动态联编将生效。引用可以转换到接口类型或从接口类型转换,instanceof 运算符可以用来决定某对象的类是否实现了接口。

第二十一,abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized?
都不能

第二十二,接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承实体类(concrete class)?
接口可以继承接口。抽象类可以实现(implements)接口,抽象类是否可继承实体类,但前提是实体类必须有明确的构造函数。

第二十三,启动一个线程是用run()还是start()?
启动一个线程是调用start()方法,使线程所代表的虚拟处理机处于可运行状态,这意味着它可以由jvm调度并执行。这并不意味着线程就会立即运行。run()方法可以产生必须退出的标志来停止一个线程。

第二十四,构造器constructor是否可被override?
构造器constructor不能被继承,因此不能重写overriding,但可以被重载overloading。

第二十五,是否可以继承string类?
string类是final类故不可以继承。

第二十六,当一个线程进入一个对象的一个synchronized方法后,其它线程是否可进入此对象的其它方法?
不能,一个对象的一个synchronized方法只能由一个线程访问。

第二十七,try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?
会执行,在return前执行。

第二十八,编程题: 用最有效率的方法算出2乘以8等於几?
有c背景的程序员特别喜欢问这种问题。

2 << 3

第二十九,两个对象值相同(x.equals(y) == true),但却可有不同的hash code,这句话对不对?
不对,有相同的hash code。

第三十,当一个对象被当作参数传递到一个方法后,此方法可改变这个对象的属性,并可返回变化后的结果,那么这里到底是值传递还是引用传递?
是值传递。java 编程语言只由值传递参数。当一个对象实例作为一个参数被传递到方法中时,参数的值就是对该对象的引用。对象的内容可以在被调用的方法中改变,但对象的引用是永远不会改变的。

第三十一,swtich是否能作用在byte上,是否能作用在long上,是否能作用在string上?
switch(expr1)中,expr1是一个整数表达式。因此传递给 switch 和 case 语句的参数应该是 int、 short、 char 或者 byte。long,string 都不能作用于swtich。

第三十二,编程题: 写一个singleton出来。
singleton模式主要作用是保证在java应用程序中,一个类class只有一个实例存在。
一般singleton模式通常有几种种形式:
第一种形式: 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getinstance方法获取对它的引用,继而调用其中的方法。
public class singleton {
  private singleton(){}
  //在自己内部定义自己一个实例,是不是很奇怪?
  //注意这是private 只供内部调用
  private static singleton instance = new singleton();
  //这里提供了一个供外部访问本class的静态方法,可以直接访问  
  public static singleton getinstance() {
    return instance;   
   }
}
第二种形式:
public class singleton {
  private static singleton instance = null;
  public static synchronized singleton getinstance() {
  //这个方法比上面有所改进,不用每次都进行生成对象,只是第一次     
  //使用时生成实例,提高了效率!
  if (instance==null)
    instance=new singleton();
return instance;   }
}
其他形式:
定义一个类,它的构造函数为private的,所有方法为static的。
一般认为第一种形式要更加安全些

hashtable和hashmap
hashtable继承自dictionary类,而hashmap是java1.2引进的map interface的一个实现

hashmap允许将null作为一个entry的key或者value,而hashtable不允许

还有就是,hashmap把hashtable的contains方法去掉了,改成containsvalue和containskey。因为contains方法容易让人引起误解。

最大的不同是,hashtable的方法是synchronize的,而hashmap不是,在
多个线程访问hashtable时,不需要自己为它的方法实现同步,而hashmap
就必须为之提供外同步。

hashtable和hashmap采用的hash/rehash算法都大概一样,所以性能不会有很大的差异。

October 22, 2006

c#问答

Filed under: C#

—-VS自动生成的代码为
namespace ConsoleApplication1
{
class Program
{
….

}
}
class Program的访问权限为? 能否定义为private 或 protected?

—-构造函数是否可以为virtual? why?

—-c#中的overloading函数是否可以仅仅只有返回值不同,why?
(在调用函数,并忽略其返回值时, 你能说出是在调用哪个函数吗?)
能不能参数列表完全相同,仅仅用ref或out来区别?
—-有没有特例?
public static explicit operator Int32(Rational r){}
public static explicit operator Single(Rational r){}
实际生成的代码在metadata中的记录为:
public static Int32 op_Explicit(Rational r)
public static Single op_Explicit(Rational r)
CLR可以仅通过返回值识别函数,c++,c#,vb,java都不支持.

—-为什么要定义缺省构造器?
//v1
public class Foo
{
}
//v2
pubolc class Foo
{
public Foo(int value)
}
此时已有的代码会出现什么问题?

—-C++的构造函数中能否抛出异常,c#呢?why?此时GC的行为如何?

—-How about this code snippet?

class a
{
public a(int c)
{

}
}

class b : a
{
public b(int c) //: base(c)
{ }
}

—-How about this one?
class a
{
public a()
{ }
}

class b : a
{
public b()
{ }
}

A:
class a
{
public a()
{ }
public a(int c)
{

}
}

class b : a
{
public b(int c)
{ }
}

Will creat code in b.b(int c) to call a()

—-能否在finally block中return一个值? why?

—-下面的代码返回值为?
private static int GetInt()
{
string a = null;
try
{
Console.WriteLine(a.Length);
return 10;
}
finally
{
Console.WriteLine(”finally block”);
}
return 100;
}
(因为没有catch,所以不会有返回值.)
如果去掉Console.WriteLine(a.Length); return 10 和 finally谁先执行?
(return 10 先执行)

—-What is the difference:

try
{}
catch()
{
throw;
}

try
{}
catch()
{
throw new Exception();
}

—-Do you like using:
try
{}
catch(Excption e)
{}
why?

September 15, 2006

STAThreadAttribute

Filed under: .NET

在VS中,生成一个windows application,程序的Main()函数上会应用
STAThreadAttribut, 而生成Console application就不会应用这个Attribute

static class Program
{
[STAThread]
static void Main()
{

Application.Run(new Form1());
}
}

class Program
{
static void Main(string[] args)
{
}
}

缺省情况下,application的主线程的Apartment state为multi-threaded apartment
(ApartmentState.MTA),设置主线程Apartment state的唯一方法就是使用STAThreadAttribut.

STAThreadAttribut使得一个application的COM 线程模式为single-threaded apartment (STA),
STAThreadAttribut只能应用在程序的入口函数上,对于其他的函数不起作用,

在程序中设置一个线程的COM 线程模式,也可以使用如下的代码:

Thread t = new Thread(new ThreadStart(StartNewStaThread));
//.net1.1
t.ApartmentState = ApartmentState.STA;
t.Start();

private void StartNewStaThread()
{
Application.Run(new Form1());
}
在.net2.0中Thread.ApartmentState被Thread.SetApartmentState (ApartmentState state)取代

注意线程的Apartment state 必须要在线程启动前设置.

从逻辑上说,apartment 是线程和object的容器,apartment中的object可以被这个apartment中任何
一个线程访问. 一个STA只能包含一个线程,一个MTA可以包含多个线程。MTA中各线程可以并行的调用
本公寓内实例化的组件一个进程可以包含多个STA,但只能有一个MTA。

.NET framework不使用apartment 模式, 所有的managed object在使用共享资源时自发地保证线程
安全.由于COM使用了apartment,所以CLR在操作COM ojbect时需要生成和初始化apartment.常用的COM组件有
Clipboar和File Dialog.COM 线程模型只适用于使用 COM interop 的应用程序。如果将此属性应用到
不使用 COM interop 的应用程序,将没有任何效果。
Windows Forms不支持MTA.所以windows程序要使用STAThreadAttribut

在Fantasy Soft的bolg不可错过的MSDN TV-IronPython: Python on the .NET Framework,有
下列描述:
如果你打算在Interactive Mode下面直接执行以上代码,你会碰到如下的错误:
Traceback (most recent call last):
at <shell>
System.InvalidCastException: Creating an instance of the COM component with CLSID {D45FD2FC-5C6E-11D1-9EC1-00C04FD7081F}
from the IClassFactory failed due to the following error: 80004002.
这是由线程的问题引起的,解决的办法就是修改IronPythonConsole目录下PythonCommandLine.cs,在源代码的Main函数前增加[STAThread],
然后重新构建这个Solution。

MSDN上对80004002的定义是: Interface not supported error
见:Standard COM Errors
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/CS07Default/html/b88924d0-f9ca-41a5-af9e-66158ab795d2.asp

September 14, 2006

IronPython Python on the .NET Framework笔记

Filed under: .NET

见IronPython: Python on the .NET Framework
http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20051110PythonJH/manifest.xml
————————————-
Build IronPython
————————————-
msbuild IronPython.sln
若在vs中build,请把 IronPythonConsole设为startup project.

————————————-
构成
————————————-
ipy.exe IronPython的控制台
ipyw.exe
Iron.Math.dll
Iron.Python.dll
Lib\Site.py

————————————-
IronPython 用到了.net2.0 哪些 Feature?
————————————-
These include Generics, DynamicMethods, new kinds of delegates, and more.

————————————-
Demo中feature的学习
————————————-
1.import Python 库

>>> import sys # 导入sys module;
>>> sys.path.append(”c:/Python24/Lib”) # 增加搜索路径
>>> import this # 导入Python中名为this的module;
>>> import random # 导入Python中名为random的module;
>>> random.__doc__ # 打印模块的document;
>>> cards = range(51) # range方法用于产生51个元素的List
>>> random.shuffle(cards) # 洗牌
>>> cards # 打印洗牌结果

2. 使用.net 类库

>>> import System # import the standard system module
>>> System.Environment.Version # 打印syste version
>>> form System.Math import * # import all the functions from the math module
>>> Sin(PI/2)
>>> form System import Random
>>> r = Random() # Create new instance
>>> [r.Next(0, 100) for i in range(10)] # 生成10个随机数

3. 派生
>>> class MyRandom(Random): pass # pass表示一条空语句
>>> mr = new MyRandow()
>>> [mr.Next(0, 100) for i in range(10)]
>>> mr.foo = 42 # 为实例mr增加了一个名为foo的field
>>> def Sample(self): return 0.5 # 定义了一个名为Sample的function
>>> MyRandom.Sample = Sample # Override Random 的Sample方法
>>> [mr.Next(0,100) for i in range(10)] # 此时由于改写了Sample方法,而Next方法需要依靠Sample方法的返回结果,
# 因此得到值全为50
>>> def Sample(self): return 0.8 + 0.2*super(MyRandom, self).Sample() # 重新定义了Sample function,调用基类方法

4. 使用From,为control定义event handler
>>> from AvalonStartup import *
>>> w = Window()
>>> w.Show()
>>> b = Button(Content=”Click me”)
>>> w.Content = b
>>> def doIt(* args ): print args
>>> b.Click += doIt

4. 使用 XAML
>>> calc = LoadXaml(’calc.xaml’)
>>> w.Content = calc
>>> for node in Walk(calc) : print node

>>> [node for node in Walk(calc) if isinstance(node, Button)] # 判断一个instance 的type
>>> buttons = _
>>> for b in buttons : print b
>>> for b in buttons : b.Background = Brushes.Blue
>>> ss = SpeakchSynthesizer()
>>> def sayIt(b , e) : ss.SpeakTextAsync(b.Name)
>>> for b in buttons : b.Click += sayIt

5. 与C#调用PythonEngine, 在vs中debug .py调本
在xaml文件中写
<Button Content=”Run Script” Click =”RunScript”>

在cs文件中
using IronPython.Hosting;
public void RunScript(object a , object b)
{
PythonEngine engine = new PythonEngine();
engine.SetVariable(”win” , this);
engine.Execute(”win.SetImage(’c:/images/itrun.jpg’)”);

System.Windows.Forms.OpFileDialog ofd = new System.Windows.Forms.OpFileDialog();
ofd.ShowDialog();
eng.RunFile(ofd.FileName); # 执行文件simple.py
}

# simple.py
text = TextBlock(Text=”Hello”, FontSize=100, Forground=Brush.White)
a = DoubleAnination(0.0 , Duration(TimeSpan.FromSeconds(3)))
a.RepeatBehavior = RepeatBehavior(3)
text.BeginAnimation(Shape.OpacityProperty , a)
Canvas.SetLeft(text , 50)
Canvas.SetTop(text , 10)
win.Content.Children[1].Children.Add(text)

由于IronPython代码最终是会转换为IL代码,由.NET Framework运行,故而IronPyton实现了以下功能:

在c#中调用一个.py文件,如果文件中出错,vs可以brack到出错的代码,
.net debugger可以可以在.py文件中加断点,
可以在debug时修改.py中变量的值

6. 在.py脚本中调用COM组件
首先使用.tlbimp生成将COM组件的wrapper
>tlbimp c:\WINDOWS\msagent\agentsvr.exe
生成AgentServerOjbects.dll

# merlin.py
import sys
sys.LoadAssemblyFromFile(AgentServerObjects.dll)
from AgentServerOjbects import *
a = AgentServerClass
id, rast = a.Load(”merlin.acs”)
ch = a.GetCharacter(id)
ch.SetSize(128,128)
ch.Show(0)
ch.MoveTo(600,100,2000)

我使用的是IronPython1.0, 在1.0中,去掉了LoadAssemblyByName和LoadAssemblyFromFile这两个方法.
而使用built-in module:clr来提供Loading .NET libraries的功能:
clr.AddReference
clr.AddReferenceToFile
clr.AddReferenceToFileAndPath
clr.AddReferenceByName
clr.AddReferenceByPartialName

代码修要改为
# merlin.py for IronPython 1.0
import clr
clr.AddReferenceToFileAndPath(’c:\IronPython\AgentServerObjects.dll’)
from AgentServerObjects import *
a = AgentServerClass()
id, rast = a.Load(”merlin.acs”)
ch = a.GetCharacter(id)
ch.SetSize(128,128)
ch.Show(0)
ch.MoveTo(600,100,2000)

August 10, 2006

特殊的Exception : ThreadAbortException

Filed under: .NET
using System;
using System.Threading;
using System.Security.Permissions;
	
namespace ThreadAbortTest
{
	
        public class ThreadWork
        {
                public static void DoWork()
                {
                        try
                        {
                                DoWorkInternal();
                        }
                        catch(ThreadAbortException e)
                        {
                                Console.WriteLine(\"Exception In Dowork(): {0}\", e.Message);
                                //Thread.ResetAbort();
                        }
                        finally
                        {
                                Console.WriteLine(\"Dowork() is dying\");
                        }
                }
	
                public static void DoWorkInternal()
                {
                        try
                        {
                                for(int i=0; i<10000; i++)
                                {
                                        Console.WriteLine(\"DoWorkInternal - working.\");
                                        Thread.Sleep(100);
                                }
                        }
                        catch(ThreadAbortException e)
                        {
                                Console.WriteLine(\"Exception In DoWorkInternal(): {0}\", e.Message);
                                //Thread.ResetAbort();
                        }
                        finally
                        {
                                Console.WriteLine(\"DoWorkInternal() ending\");
                        }
                }
        }
	
        class ThreadAbortTest
        {
                public static void Main()
                {
                        Thread myThread = new Thread(new ThreadStart(ThreadWork.DoWork));
                        myThread.Start();
                        Thread.Sleep(1000);
                        myThread.Abort();
                        myThread.Join();
                        Console.WriteLine(\"Main ending.\");
                }
        }
}
	

显示
DoWorkInternal - working.

DoWorkInternal - working.
Exception In DoWorkInternal(): Thread was being aborted.
DoWorkInternal() ending
Exception In Dowork(): Thread was being aborted.
Dowork() is ending
Main ending.

1.ThreadAbortException 在DoWorkInternal中被catch了,DoWork中依然可以catch到.
显然,MS希望Thread.Abort调用时,调用栈中每个函数都知道.
2.去掉所有的try-catch,程序照常执行. VS的Debug-Exception设定对话框中,打开所有的
exception,可看到ThreadAbortException 是一个特殊的exception.
3. myThread.Abort(); myThread.Join(); //等待myThread的finally块的执行

July 29, 2006

“是否同意”按钮的实现

Filed under: ASP.NET, Code snippets

[script type=”text/javascript”]
ar secs = 3;
var agree = document.getElementById(”agreeb”);
agree.disabled=true;
for(i=1;i<=secs;i++)
{
window.setTimeout(”update(” + i + “)”, i * 1000);
}
function update(num)
{
if(num == secs)
{
agree.value =” 我 同 意 “;
agree.disabled=false;
}
else
{
printnr = secs-num;
agree.value = “请认真查看<服务条款和声明> (” + printnr +” 秒后继续)”;
}
}
[script]

Win Form 的 Dock和Splitter

Filed under: Code snippets

如果在Form上放一个 Panel ,panel.Dock = Left
在放一个Splitter,Splitter的Dock缺省为Left, 不能为None,也不能为Fill.

注意此时:
this.panel1.Dock = System.Windows.Forms.DockStyle.Left;
this.panel1.Location = new System.Drawing.Point(0, 0);

this.splitter1.Location = new System.Drawing.Point(200, 0);

this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel1);

这时的拖动Splitter, Panel会随之变化.

如果把
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel1);
的顺序换一下,打开Designer就会看到,splitter就会被放在form的最左边,
运行时splitter也会被放在form的最左边.
此时代码尚无任何改变,把form的size改一下,导致designer产生代码,就会看到:
this.splitter1.Location = new System.Drawing.Point(0, 0);
this.panel1.Location = new System.Drawing.Point(3, 0);

!–可见对于使用了dock的control,他们的location实际是由deisnger,或在
运行时算出来的,指定的值并无效果.
对于指定了相同dock的多个control,比如panel1和splitter,都要dock到Left,最左边的
Control必须最后加到form.Controls中

大多情况下,form上splitter的右边还会有一个dock属性为fill的panel,
正常的顺序是先添加panel_left,再添加splitter,再添加panel_right,
此时生成的代码顺序是:

this.panel_Right.Location = new System.Drawing.Point(272, 0); //Note

this.Controls.Add(this.panel_Right);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel_Left);

如果把代码调整为:
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel_Left);
this.Controls.Add(this.panel_Right);

panel_right就会fill到整个form,而不是splitter右边的区域:
this.panel_Right.Location = new System.Drawing.Point(0, 0); //Note
this.panel_Right.Size = new System.Drawing.Size(640, 533);

!–可见,fill的control要最先加到容器中.
查看这个问题有个好办法,把一个button放到panel_right的左上角,如果button的location不接近(0,0),
就说明有问题.

再进一步,在Panel_Right上加三个panel:
Top(Dock=Top), Center(Dock=Fill), Bottom(Dock=Bottom)
添加的顺序为Top, Botton, Center,
生成的代码顺序为:
this.panel_Right.Controls.Add(this.panel_Center);
this.panel_Right.Controls.Add(this.panel_Bottom);
this.panel_Right.Controls.Add(this.panel_Top);

现在,我已经知道这个顺序的奥妙了,我不会再尝试改变这个顺序.

July 27, 2006

Windows Forms 程序中的多线程

Filed under: .NET

参考
Safe, Simple Multithreading in Windows Forms, Part 1, 2,3
http://msdn.microsoft.com/library/en-us/dnforms/html/winforms06112002.asp
http://msdn.microsoft.com/library/en-us/dnforms/html/winforms08162002.asp
http://msdn.microsoft.com/library/en-us/dnforms/html/winforms01232003.asp

Safe, Even Simpler Multithreading in Windows Forms 2.0
http://www.mikedub.net/mikeDubSamples/SafeReallySimpleMultithreadingInWindowsForms20/SafeReallySimpleMultithreadingInWindowsForms20.htm

翻译+篡改 by RivenHuang 2006/07/27

关键字:
UI线程 工作线程 线程同步 线程通信 竞争 死锁 boxing 异步调用web service

设想实现以下的case:
一个win form application, 用来计算任意长度的pi值, from上的progress
可以显示计算的进度, from上的cancle button 可以终止计算, 计算完成后form可以得到通知.

正如作者所言,”It all started innocently enough.”

Design 1—————————————————–
button click 调用函数CalcPi(int digits), CalcPi中在一个循环中干活,每计算一次更新一下UI,
包括计算结果, progress bar:

private void button_Calc_Click(object sender, System.EventArgs e)
{
this.CalcPi((int)this.numericUpDown_Digits.Value);
}

void ShowProgress(string pi, int totalDigits, int digitsSoFar)
{
this.textBox_Result.Text = pi;
this.progressBar_Calc.Maximum = totalDigits;
this.progressBar_Calc.Value = digitsSoFar;
}

void CalcPi(int digits)
{
StringBuilder pi = new StringBuilder(”3″, digits + 2);

// Show progress
ShowProgress(pi.ToString(), digits, 0);

if( digits > 0 )
{
pi.Append(”.”);

for( int i = 0; i < digits; i += 9 )
{
int nineDigits = NineDigitsOfPi.StartingAt(i+1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format(”{0:D9}”, nineDigits);
pi.Append(ds.Substring(0, digitCount));

// Show progress
ShowProgress(pi.ToString(), digits, i + digitCount);
}
}
}

看上去很美,尝试一下CalcPi(1000),此时,progress bar在努力地前进着,而textbox好像在偷懒,
text区域没有任何输出,但它的滚动条上的thumb又在变化(出现,变短), 然后切换到别的程序,
再切回来,form会失去响应,白屏了.如果这是一个我自己玩的程序,我会容忍,因为我知道它在干活,
如果是工作中的程序,就有必要解决一下这个问题.

分析一下:
此时的程序是一个单线程程序(相信你攒的大多数程序都是这样),在CalcPi()中,试图调用ShowProgress
来设置textBox_Result和progressBar_Calc的值来立刻重画以显示当前的工作成绩,(progress的表现要比
textbox的表现好一些,why?我也不知道),在把form放到后台,再放到前台后,form的Paint event会被触发
(其实就是windows的WM_PAINT消息,对于windows程序来说,这是个很有些门道的message,详情见
Programming windows 5e ch5 图形基础),但实际上此时程序正在执行CalcPi(),Paint 的事件处理函数只好
排队.

要解决这个问题肯定要使用多线程, 正解是另开一个工作线程来干活,并和UI通信,报告当前的进度,但我在
我们的代码中见过另类的做法: 在UI线程中干活,再开一个线程来刷新UI,也能干活,但我担心在某些情况下
会出现一些微妙的bug.

Desing 2———————————————–

在button click中另开线程.注意ThreadStart含参数,所以要把CalcPi(digits)包装一下

private void button_Calc_Click(object sender, System.EventArgs e)
{
Thread piThread = new Thread(new ThreadStart(CalcPiThreadStart));
piThread.Start();
}

void CalcPiThreadStart()
{
CalcPi((int)this.numericUpDown_Digits.Value);
}

run, 看上去更美,唯一的缺憾就是CalcPiThreadStart这个没用的东西非常碍眼.
使用异步的delegate可以弥补这个缺憾,注意,此时的工作线程是线程池中的线程.

Desing 3———————————————–

private void button_Calc_Click(object sender, System.EventArgs e)
{
CalcPiDelegate calcPi = new CalcPiDelegate(CalcPi);
//–忆苦代码:-)
//calcPi((int)numericUpDown_Digits.Value);
calcPi.BeginInvoke((int)numericUpDown_Digits.Value, null, null);
}

有关 delegate, Chris Sells推荐了.NET Delegates: A C# Bedtime Story一文,
在Framework design guideline一书中,有 Async Pattern可供参考.

真的天下太平了吗?Windows世界中有这样一条警句:
“Though shalt not operate on a window from other than its creating thread”,

回头看看已有的代码,X! 不就在说我吗?当然目前好像没什么错误,但是在”某些情况下
会出现一些微妙的bug.”
为了安全,在ShowProgress中添加

void ShowProgress(string pi, int totalDigits, int digitsSoFar)
{
// Make sure we’re on the right thread
Debug.Assert(this.InvokeRequired == false);

}
红叉子马上就来了.

有矛就有盾,.NET中所有从System.Windows.Forms.Control派生的class,当然包含
System.Windows.Forms.Form, 都有一个InvokeRequired属性,用以返回是否需要使用一些
Control上的方法把对control的操作传递给create control的线程.这个property可以在
任何一个线程中访问,

.NET的Control上只有Invoke, BeginInvoke, EndInvoke, GreateGraphics这4个方法可以从任何线程
调用,其他的调用, 必须使用Invoke方法来传递.

目前问题的解决方案就是使用一个delegate来把对UI control的操作通过 Control上的Invoke
方法传递过去,当然还需要使用异步Invoke,否则工作线程也会被block.本例中由于工作线程只为
UI thread一人服务,使用Invoke不会有问题.

Design4 ——————–
void CalcPi(int digits)
{
StringBuilder pi = new StringBuilder(”3″, digits + 2);

// Get ready to show progress asynchronously
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);

// Show progress
this.Invoke(showProgress, new object[] { pi.ToString(), digits, 0});

if( digits > 0 )
{
pi.Append(”.”);

for( int i = 0; i < digits; i += 9 )
{
int nineDigits = NineDigitsOfPi.StartingAt(i+1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format(”{0:D9}”, nineDigits);
pi.Append(ds.Substring(0, digitCount));

// Show progress
this.Invoke(showProgress,new object[] { pi.ToString(), digits, i + digitCount});
}
}
}

在Design4中出现了两次this.Invoke, 重构, 把代码移动到ShowProgress中

Desing5———————————-
void ShowProgress(string pi, int totalDigits, int digitsSoFar)
{
System.Diagnostics.Debug.Assert(this.InvokeRequired == false);

if( this.InvokeRequired == false )
{
this.textBox_Result.Text = pi;
this.progressBar_Calc.Maximum = totalDigits;
this.progressBar_Calc.Value = digitsSoFar;
}
else
{
// Show progress asynchronously
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
this.Invoke(showProgress, new object[] { pi, totalDigits, digitsSoFar});
}
}

void CalcPi(int digits)
{
StringBuilder pi = new StringBuilder(”3″, digits + 2);

ShowProgress(pi.ToString(), digits, 0);

if( digits > 0 )
{
pi.Append(”.”);

for( int i = 0; i < digits; i += 9 )
{
int nineDigits = NineDigitsOfPi.StartingAt(i+1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format(”{0:D9}”, nineDigits);
pi.Append(ds.Substring(0, digitCount));

// Show progress
ShowProgress(pi.ToString(), digits, 0);
}
}
}

现在可以考虑cancel 功能的实现了
1. UI上的对应: 在开始计算后, button上的”Calc”要变为”Cancel”
还可以弹出一个带progress bar和cancel button的 dialog,

2.通常会使用一个变量来标示是否操作被取消,在从UI线程得知工作线程线程应该停止
(cancel button click被执行),到工作线程自己知道将被停止,并停止发送进度之间的这
一小段时间内,应该禁用 UI。
否则,用户在第一个工作线程停后又开始别的工作, UI就线程必须判断是从新的工作线程获
取进度还是从即将关闭的旧线程获取进度。这就需要工作线程能够通知外界是否它已经停止.

Design 6

enum CalcState
{
Pending, // No calculation running or canceling
Calculating, // Calculation in progress
Canceled, // Calculation canceled in UI but not worker
}

CalcState _state = CalcState.Pending;

在本例中由ShowProgress来设置_state变量,以通知工作线程停止
并重新设置UI, 使button enable.

delegate void ShowProgressDelegate(string pi, int totalDigits, int digitsSoFar);

void ShowProgress(string pi, int totalDigits, int digitsSoFar)
{
lock(this._stateLock)
{
if( _state == CalcState.Canceled )
{
_state = CalcState.Pending;
}
}

// Make sure we’re on the right thread
if( this.InvokeRequired == false )
{
this.textBox_Result.Text = pi;
this.progressBar_Calc.Maximum = totalDigits;
this.progressBar_Calc.Value = digitsSoFar;

// Check for completion
if( _state == CalcState.Pending || (digitsSoFar == totalDigits) )
{
_state = CalcState.Pending;
this.button_Calc.Text = “Calc”;
this.button_Calc.Enabled = true;
}
}
// Transfer control to correct thread
else
{
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);

// Show progress synchronously (so we can check for cancel)
Invoke(showProgress, new object[] { pi, totalDigits, digitsSoFar});
}
}

void CalcPi(int digits)
{
StringBuilder pi = new StringBuilder(”3″, digits + 2);

// Show progress (ignoring Cancel so soon)
ShowProgress(pi.ToString(), digits, 0);

if( digits > 0 )
{
pi.Append(”.”);

for( int i = 0; i < digits; i += 9 )
{
int nineDigits = NineDigitsOfPi.StartingAt(i+1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format(”{0:D9}”, nineDigits);
pi.Append(ds.Substring(0, digitCount));

// Show progress (checking for Cancel)
ShowProgress(pi.ToString(), digits, i + digitCount);
if( this._state == CalcState.Canceled ) break;
}
}
}

此时,工作线程和UI线程通过一个内部变量_state来记录工作状态,为了避免竞争,需要加上一个监视锁,
在.NET中为了共享对象提供了 Monitor 类,其作用类似于为数据加了一把锁.
Design 6.1

object _stateLock = new object();

void ShowProgress(string pi, int totalDigits, int digitsSoFar, out bool cancel)
{
lock( _stateLock )
{ // 监视锁
if( _state == CalcState.Cancel )
{
_state = CalcState.Pending;
cancel = true;
}
}

}

但是这样的做法又有可能引起死锁,需要强调的是:
“通过共享数据进行的多线程编程很难做到十全十美”.

可通过在线程之间传递数据的副本来避免使用共享数据,只有在数据很大时才考虑使用共享数据.

此处,只让UI线程(在UI线程中执行的ShowProgress)来检查_state,并返回给工作线程一个状态值表示是否取消计算.
但返回值通常用来表示操作是否正常进行,所以使用一个out参数来传递信息.

注意1:
此时工作线程通过调用ShowProgress来查看操作是否已被取消,所以不能使用Control.BeginInvoke来执行ShowProgress,
使用Control.BeginInvoke又会需要同步. 有一个卖糕的.所以还是使用Invoke

注意2:
不能直接向 Control.Invoke 简单传递bool变量来获得 cancel 参数!
因为 bool 是valut type,而 Invoke 采用object array 作为参数,其结果是作为对象传递的 bool
将被boxing而保持实际的 bool , 为此必须使用自己的对象变量 (inoutCancel) 传递它,
在同步调用 Invoke 后,我们将 object cast为 bool 以查看是否应该取消操作。

!任何时候调用带有 out 或 ref 参数的 Control.Invoke或 Control.BeginInvoke时,都必须注意
值类型和引用类型数据之间的区别。

Desing 7———————————–

void CalcPi(int digits)
{
bool cancel = false;
StringBuilder pi = new StringBuilder(”3″, digits + 2);

// Show progress (ignoring Cancel so soon)
ShowProgress(pi.ToString(), digits, 0, out cancel);

if( digits > 0 )
{
pi.Append(”.”);

for( int i = 0; i < digits; i += 9 )
{
int nineDigits = NineDigitsOfPi.StartingAt(i+1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format(”{0:D9}”, nineDigits);
pi.Append(ds.Substring(0, digitCount));

// Show progress (checking for Cancel)
ShowProgress(pi.ToString(), digits, i + digitCount,out cancel);
if( cancel ) break;
}
}
}

delegate void ShowProgressDelegate(string pi, int totalDigits, int digitsSoFar,out bool cancel);

void ShowProgress(string pi, int totalDigits, int digitsSoFar,out bool cancel)
{
// Make sure we’re on the right thread
if( this.InvokeRequired == false )
{
this.textBox_Result.Text = pi;
this.progressBar_Calc.Maximum = totalDigits;
this.progressBar_Calc.Value = digitsSoFar;
// Check for Cancel
cancel = (_state == CalcState.Canceled);

// Check for completion
if( cancel || (digitsSoFar == totalDigits) )
{
_state = CalcState.Pending;
this.button_Calc.Text = “Calc”;
this.button_Calc.Enabled = true;
}
}
// Transfer control to correct thread
else
{
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);

// Avoid boxing and losing our return value
object inoutCancel = false; // Avoid boxing and losing our return value

// Show progress synchronously (so we can check for cancel)
Invoke(showProgress, new object[] { pi, totalDigits, digitsSoFar, inoutCancel});
cancel = (bool)inoutCancel;
}
}

一路挣扎到这,我已经满头大汗,可故事还没有结束, 代码还有可优化的余地.
作者称之为 message passing model:
工作线程create一个message, 交给UI线程处理,然后检查UI线程的处理结果,整个处理过程很安全,
不存在多线程之间纠缠不清的问题,而且具有很好的可扩充性,又什么要交互的信息,就加到
ShowProgressArgs中

Desing8————————————————-

void CalcPi(int digits)
{
StringBuilder pi = new StringBuilder(”3″, digits + 2);

// Show progress (ignoring Cancel so soon)
object sender = System.Threading.Thread.CurrentThread;
ShowProgressArgs e = new ShowProgressArgs(pi.ToString(), digits, 0);

ShowProgress(sender, e);

if( digits > 0 )
{
pi.Append(”.”);

for( int i = 0; i < digits; i += 9 )
{
int nineDigits = NineDigitsOfPi.StartingAt(i+1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format(”{0:D9}”, nineDigits);
pi.Append(ds.Substring(0, digitCount));

// Show progress (checking for Cancel)
e.Pi = pi.ToString();
e.DigitsSoFar = i + digitCount;
ShowProgress(sender, e);
if( e.Cancel ) break;
}
}
}

class ShowProgressArgs : EventArgs
{
public string Pi;
public int TotalDigits;
public int DigitsSoFar;
public bool Cancel;

public ShowProgressArgs(string pi, int totalDigits, int digitsSoFar)
{
this.Pi = pi;
this.TotalDigits = totalDigits;
this.DigitsSoFar = digitsSoFar;
}
}

delegate void ShowProgressHandler(object sender, ShowProgressArgs e);

void ShowProgress(object sender, ShowProgressArgs e)
{
// Make sure we’re on the right thread
if( this.InvokeRequired == false )
{
this.textBox_Result.Text = e.Pi;
this.progressBar_Calc.Maximum = e.TotalDigits;
this.progressBar_Calc.Value = e.DigitsSoFar;
// Check for Cancel
e.Cancel = (_state == CalcState.Canceled);

// Check for completion
if( e.Cancel || (e.DigitsSoFar == e.TotalDigits) )
{
_state = CalcState.Pending;
this.button_Calc.Text = “Calc”;
this.button_Calc.Enabled = true;
}
}
// Transfer control to correct thread
else
{
ShowProgressHandler showProgress = new ShowProgressHandler(ShowProgress);
Invoke(showProgress, new object[] { sender, e});
}
}

最后,来看看最实用的case: Asynchronous Web Services,代码堪称典范,以致可以copy-paste:

CalcState state = CalcState.Pending;
localhost.CalcPiServiceProxy service = new localhost.CalcPiServiceProxy();

void calcButton_Click(object sender, System.EventArgs e)
{
switch( state )
{
case CalcState.Pending:
state = CalcState.Calculating;
calcButton.Text = “Cancel”;

// Start web service request
service.BeginCalcPi((int)digitsUpDown.Value, new AsyncCallback(PiCalculated), null);
break;

case CalcState.Calculating:
state = CalcState.Canceled;
calcButton.Enabled = false;
service.Abort(); // Fail all outstanding requests
break;

case CalcState.Canceled:
Debug.Assert(false);
break;
}
}

void PiCalculated(IAsyncResult res)
{
try
{
ShowPi(service.EndCalcPi(res));
}
catch( WebException ex )
{
//maybe time-out
ShowPi(ex.Message);
}
}

delegate void ShowPiDelegate(string pi);

void ShowPi(string pi)
{
if( this.InvokeRequired == false )
{
piTextBox.Text = pi;
state = CalcState.Pending;
calcButton.Text = “Calc”;
calcButton.Enabled = true;
}
else
{
ShowPiDelegate showPi = new ShowPiDelegate(ShowPi);
this.BeginInvoke(showPi, new object[] {pi});
}
}

在.NET2.0中,MS派来了弥赛亚 BackgroudWorker 来救助为了UI,耗时计算而抓破头皮的程序员.
ToolBox->Components->BackgroundWorker, drag it to the form.
>处理BackgroundWorker仅有的3个event:
DoWork
ProgressChanged
RunWorkerCompleted

>设置
WorkerReportsProgress = true; //实现进度条
WorkerSupportsCancellation = true; //实现cancel

想干活,请调用:BackgroundWorker的 RunWorkerAsync 方法, 搞定!

//———————————
private void button_Calc_Click(object sender, EventArgs e)
{
if (this.button_Calc.Text == “Cancel”)
{
this.backgroundWorker_Calc.CancelAsync();
return;
}

this.button_Calc.Text = “Cancel”;
this.backgroundWorker_Calc.RunWorkerAsync(this.numericUpDown_Digits.Value);
this.progressBar_Calc.Maximum = Convert.ToInt32(this.numericUpDown_Digits.Value);
}

// This method will run on a thread other than the UI thread.
// Be sure not to manipulate any Windows Forms controls created
// on the UI thread from this method.
private void backgroundWorker_Calc_DoWork(object sender, DoWorkEventArgs e)
{
int digits = int.Parse(e.Argument.ToString()); // <= RunWorkerAsync(this.numericUpDown_Digits.Value);
StringBuilder pi = new StringBuilder(”3″, digits + 2);
CalcPiUserState userState = new CalcPiUserState(pi.ToString(), digits, 0);
this.backgroundWorker_Calc.ReportProgress(0, userState);

// Calculate rest of pi, if required
if (digits > 0)
{
pi.Append(”.”);

for (int i = 0; i < digits; i += 9)
{

// Calculate next i decimal places
int nineDigits = NineDigitsOfPi.StartingAt(i + 1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format(”{0:D9}”, nineDigits);
pi.Append(ds.Substring(0, digitCount));

// Show current progress
userState.Pi = pi.ToString();
userState.DigitsSoFar = i + digitCount;
this.backgroundWorker_Calc.ReportProgress(0, userState);

// Check for cancellation
if (this.backgroundWorker_Calc.CancellationPending)
{
// Need to set Cancel if you need to distinguish how a worker thread completed
// ie by checking RunWorkerCompletedEventArgs.Cancelled
e.Cancel = true;
break;
}
}
}

e.Result = “Finished Normally.”;
}

private void backgroundWorker_Calc_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
CalcPiUserState userToken = (CalcPiUserState)e.UserState;
this.progressBar_Calc.Value = userToken.DigitsSoFar;
this.textBox_Result.Text = userToken.Pi;
}

private void backgroundWorker_Calc_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.button_Calc.Text = “Calc”;
this.textBox_Result.Text = “”;
this.progressBar_Calc.Value = 0;

if (!e.Cancelled)
{
this.Text = e.Result.ToString();
}
}
}

July 26, 2006

Assembly执行路径

Filed under: Code snippets

//————
string assemblyLocation = Assembly.GetExecutingAssembly().Location;

//————
assemblyLocation = Assembly.GetCallingAssembly().Location;

//————
string exeFolder = Path.GetDirectoryName(Application.ExecutablePath);

July 8, 2006

NAnt的代码不能Debug

Filed under: .NET

用VS2003打开NAnt的代码,断点断不到,Why?

我检查了Project的属性设定,是dubug版,一切正常,最后我发现是app.config中的下列代码导致断点不能工作:

  <startup>
        <!– .NET Framework 2.0 –>
        <supportedRuntime version="v2.0.50727" />
        <!– .NET Framework 2.0 Beta 2 –>
        <supportedRuntime version="v2.0.50215" />
        <!– .NET Framework 2.0 Beta 1 –>
        <supportedRuntime version="v2.0.40607" />
        <!– .NET Framework 1.1 –>
        <supportedRuntime version="v1.1.4322" />
        <!– .NET Framework 1.0 –>
        <supportedRuntime version="v1.0.3705" />
    </startup>

因为我使用的vs2003,所以只有把<supportedRuntime version="v1.1.4322" />移动到最顶端,断点才能工作.

这些代码是怎么生成的?

在project的propery dialog的General页上,设置Supported runtimes,在app.config中就会生成上述代码.

June 28, 2006

APM(Asynchronous Programming Modle)的3种模式

Filed under: .NET

出自CLR via C# ch23

//—-Wait until done

定义了FileOptions.Asynchronous,才能调用FileStream.BeignRead(),否则请调用FileStream.Read
如果定义了FileOptions.Asynchronous,又调用Read,FileStream会启动一个工作线程来操作文件,
并Sleep调用线程,知道工作线程完成.

FileStream fs = new FileStream(@”c:\boot.ini”, FileMode.Open, FileAccess)

Byte[] data = new Byte[100];

IAsyncResult ar = fs.BrginRead(data, 0, data.Length, null, null);

//Suspend this thread until the asynchronous operation completes
Int32 bytes = fs.EndRead(ar);

fs.Close();

//—-Polling

FileStream fs = new FileStream(@”c:\boot.ini”, FileMode.Open, FileAccess)

Byte[] data = new Byte[100];

IAsyncResult ar = fs.BrginRead(data, 0, data.Length, null, null);

while(!ar.IsComplete)
{
Thread.Sleep(10);
}

Int32 bytes = fs.EndRead(ar);

fs.Close();

//—-Callback

FileStream fs = new FileStream(@”c:\boot.ini”, FileMode.Open, FileAccess)

Byte[] data = new Byte[100];

fs.BrginRead(data, 0, data.Length, ReadIsDone, fs);

private static void ReadIsDone(IAsyncResult ar)
{
FileStream fs = (FileStream)ar.AyncState;

Int32 bytes = fs.EndRead(ar);

fs.Close();
}

也可以使用匿名方法写成:

FileStream fs = new FileStream(@”c:\boot.ini”, FileMode.Open, FileAccess)

Byte[] data = new Byte[100];

IAsyncResult ar = fs.BrginRead(data, 0, data.Length,
delegate(IAsyncResult ar)
{
Int32 bytes = fs.EndRead(ar);

fs.Close();
}
, null);

这样写的好处是匿名方法可以访问所有的局部变量(data, fs),所以不用把fs传递给它.

June 26, 2006

QueueUserWorkItem() 和UnsafeQueueUserWorkItem()

Filed under: .NET

Code Access Security(CAS) check.
CLR 会检查执行线程的call stack 中的所有assembly是否有权限访问受限制的资源.
否,则抛出SecurityException.

QueueUserWorkItem会把调用线程的权限赋给线程池中的线程,但是遍历调用线程的callstack
检查权限是一个耗时的操作,所以有了UnsafeQueueUserWorkItem().

调用UnsafeQueueUserWorkItem()的函数需要SecurityPermission,并把ControlPolicy和
ControlEvidenc打开.

June 16, 2006

不断调用System.Timers.Timer的Stop()和Start方法,会导致程序占用的内存和线程数骤增.

Filed under: .NET, My Questions

不断调用System.Timers.Timer的Stop()和Start方法,会导致程序占用的内存和线程数骤增.

System.Timers.Timer _tmr;

private void button1_Click(object sender, System.EventArgs e)
{
_tmr = new System.Timers.Timer();
_tmr.Interval = 10000000;
_tmr.Start();

while(true)
{
_tmr.Stop();
//Thread.Sleep(300); 如果使用了