人生是一场不能存盘的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); 如果使用了sleep,情况会大幅缓和,但线程数会增加.
_tmr.Start();
}

为什么?

June 13, 2006

篡改.Net Strongly Name Assembly

Filed under: .NET

1.什么是Strong Name
一个strong name由4部分构成
filename(不含扩展名).version.Culture.PublicKeyToken

2.使用 System.Reflection.AssemblyName 可以得到 strong name的相关信息如:
CulturInfo, FullName, KeyPaire, Name, Version

3.SN.exe 的使用
生成key pair
sn -k my.keys

得到public key
sn -p my.keys my.publickey

查看public key内容
sn -tp my.publickey

4. Sign
[1]Assembly的FileDef manifest table包含了组成这个Assembly的所有文件,sign 一个assembly的
第一步就是把组成这个Assembly的所有文件的hash值和文件名放入FileDef manifest table.

[2]将整个PE文件的内容hash运算,结构使用private key 签名,再将结果(RSA数字签名)植入 CLR 文件头

[3]将public key植入AssemblyDef manifest table中.
不同的公司不可能拥有相同的public key,从而可以使用
filename(不含扩展名).version.Culture.PublicKeyToken来保证一个assembly的唯一性.

5. CLR 验证:
将文件的内容hash运算,把CLR 文件头中的RSA数字签名用public key反签名,二者比较可知文件是否
清白.如果被篡改过,CLR就会扔出个System.IO.FileLoadException.

6. Delay Sign.
[1]在PE文件中为 RSA数字签名留下空间
[assembly:AssemblyKeyFile(…keys)]
[assembly:AssemblyDelaySign(true)]

[2]关闭CLR验证
sn -Vr my.dll

[3]sign
sn -R my.dll my.keys

[4]打开认证
sn -Vu my.dll

7. 如何篡改SN Assembly
1.找一个Strong Name assembly, some.exe并篡改,执行some.exe会出错.
注意,此时使用sn -Vr some.exe 也不会由效果,否则 strong name将行同虚设.

2.生成一个自己的key pair文件 sn -k mykey.snk

3.编程,用mykey.snk中的public key 来替换 some.exe中的public key
SNReplace Some.exe mykey.snk

public class SNReplace
{
public static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine(”Usage: SNReplace <assembly> <keyfile>”);
return;
}
SNReplace snr = new SNReplace();
snr.AssemblyFile = args[0];
snr.KeyFile = args[1];
snr.Replace();
}

public string KeyFile;
public string AssemblyFile;

byte[] currentKey;
byte[] newKey;

byte[] assembly;

private int keyStart;

public void Replace()
{
readKeys();
readAssembly();
findKeyStart();
replaceKey();
save();
resign();
}

private void readKeys()
{
//==得到assembly中的 pubic key
this.currentKey = AssemblyName.GetAssemblyName(this.AssemblyFile).GetPublicKey();

//==得到key pair 文件中的 pubic key
FileStream keyStream = File.OpenRead(this.KeyFile);
this.newKey = new StrongNameKeyPair(keyStream).PublicKey;
keyStream.Close();
}

private void readAssembly()
{
using (FileStream fs = File.OpenRead(this.AssemblyFile))
{
this.assembly = new byte[fs.Length];
fs.Read(this.assembly, 0, (int)fs.Length);
}
}

private void findKeyStart()
{
// Yes, it’s a slow algorithm.
byte startByte = currentKey[0];
for(int i = 0; i < this.assembly.Length; i++)
{
if (assembly[i] == startByte)
{
// Possible match
if (isKeyFound(i))
{
this.keyStart = i;
return;
}
}
}
// Not found…
Console.WriteLine(”Something’s wrong. Public key not found.”);
Environment.Exit(1);
}

private bool isKeyFound(int startIndex)
{
for(int i = 0; i < currentKey.Length; i++)
{
if (currentKey[i] != assembly[i + startIndex])
{
return false;
}
}
return true;
}

private void replaceKey()
{
for(int i = 0; i < newKey.Length; i++)
{
assembly[keyStart + i] = newKey[i];
}
}

private void save()
{
using (FileStream fs = File.Create(this.AssemblyFile))
{
fs.Write(assembly, 0, assembly.Length);
}
}
}

4. sn -R Some.exe mykey.snk

这招对于不被别人引用的assembly 非常有效,但对于被别的assembly引用的assembly,由于被引用的assembly
的hash 值被保存在引用者的FileDef中,篡改了一个assembly后还要篡改这些FileDef.比较恐怖.

做坏事之前先想清楚,是不是真的想做.

获取Public Key 信息

Filed under: Code snippets

//==得到assembly中的 pubic key
byte[] currentKey = AssemblyName.GetAssemblyName(”myAssembly.dll”).GetPublicKey();

//==得到key pair 文件中的 pubic key
FileStream keyStream = File.OpenRead(”mykey.snk”);
byte[] newKey = new System.Reflection.StrongNameKeyPair(keyStream).PublicKey;

//==使用 sn.exe

得到public key
sn -p my.keys my.publickey

查看public key内容
sn -tp my.publickey

_NET应用程序的自动更新

Filed under: .NET

出自
.NET Client Applications: .NET Application Updater Component
http://windowsforms.net/articles/appupdater.aspx
http://windowsforms.net/downloads/GDN/dotnetupdater.zip

Using The Updater Application Block
http://www.theserverside.net/tt/articles/showarticle.tss?id=UpdateAppBlock

TaskVision 解决方案概述:设计与实现
http://www.microsoft.com/china/MSDN/library/enterprisedevelopment/softwaredev/SCdnwinformswnftaskvision.mspx?mfr=true

.net的rich client自动升级方案
http://yyanghhong.cnblogs.com/archive/2004/11/08/61409.aspx

如何得知是否需要更新:
1.比较文件的时间戳,缺陷在于
如果管理员正在更新服务器上的程序,同时有个客户正在下载更新之前的版本,那么这个客户的计算
机上就会既存在更新之前的一些文件,也存在更新之后新版本的一些文件。

2.在服务器上放一个xml文件,来描述应用程序中所有assembly的版本,client会和本地的程序比较并决定
是否下载

3.server 端保存用户信息, client调用一个web service来决定是否需要更新.

如何下载:
下载使用HTTP-DAV来完成。DAV 是一种扩展的HTTP,提供遍历目录和文件的功能。
下载过程中可能会出现以下问题:更新文件所属的服务器可能会崩溃,客户端机器也可能崩溃,或者因为某种原因
用户关闭了应用程序,这些都会导致下载的终止。使用系统服务,即便应用程序自身没有在运行,更新下载也会继续。
Windows XP有一种称之为BITS的内建的下载服务,是Windows XP用来对Windows自身进行下载更新的。
参阅http://msdn.microsoft.com/library/en-us/dnwxp/html/WinXP_BITS.asp
在.NET应用程序更新组件中没有使用这种服务,因此可用在不支持系统服务的系统(Windows 9x,Mono)中使用。

.NET Application Updater component把download 和 update 过程分为几个独立,可重复执行的的过程,每个过程的
执行结果都记录在client 程序所在的路径下的一个文件中,如果某个步骤失败,.NET Application Updater component
会重试,实在不行就报错退出.

如何执行Update
该过程的难点在于有可能会更新正在运行的程序.
最简单的方案是使用一个独立的进程来执行更新,Update进程会shutdown Application进程,然后执行update,最后重启
Application.但是这个解决方案有如下的问题:
1. Update 进程由App进程产生, Update进程kill app进程,当APP运行在Job模式下, Update进程也会被终止.
2. 执行更新的模块也需要更新.

最终的方案使用了一个小的"诡计",避开直接更新应用程序本身,而是新建一个目录然后下载新版本的引用程序,下载完成
后使用新版本的可执行文件启动应用程序,并且删除老版本程序,由于要有选择地启动某个版本的程序,需要一个引子程序
AppStart,用它来作为应用程序的入口.整个应用程序的目录结构如下:
Program File
    My App
        AppStart.exe
        AppStart.config
        V1 Folder
            MyApp.exe
        V2 Folder
           MyApp.exe
AppStart.exe会根据AppStart.config来决定启动那个版本的exe
<Config>
    <AppFolderName>V1 Folder</AppFolderName>
    <AppExeName>MyApp.exe</AppExeName>
    <AppLaunchMode>appdomain</AppLaunchMode>
</Config>
更新程序可以通过修改<AppFolderName>来决定执行那个版本的app.
<AppLaunchMode>会使AppStart.exe和MyApp.exe运行在同一进程的不同的AppDomain中,
Appstart启动MyApp后就sleep,等待MyApp结束.通常情况下MyApp结束后,AppStart也会shutdown,
但如果MyApp结束时返回一个特有的返回值,AppStart会重新MyApp.

.Net Updater Component
只有一个文件,AppUpdater.dll.
主要属性:
AutoFileLoad: 用户实现按需下载,当CLR找不到一个dll时,会raise AppDomain.AssemblyResolve 事件,
.Net Updater Component会hook这个event,进行下载,更新.
ChangeDetectionMode: 采用何种方式检查更新,一般使用ServerManifestCheck.
ShowDefatultUI: 是否使用.Net Updater Component自带的UI提示用户,也可以hook .Net Updater Component的
有关事件如OnUpdateComplete来弹出自定义的UI.
AppUpdater obj必须生成在app的主UI线程中,否则不能显示UI,也不能给UI线程发Event显示UI.
UpdateUrl: 在何处查找Updata信息,如果使用了ServerManifestCheck Mode,UpdateUrl可指定为:
http://yourWebserver/SampleApp_ServerSetup/UpdateVersion.xml.
UpdateVersion.xml的内容为:
<VersionConfig>
     <AvailableVersion>1.0.0.0</AvailableVersion>
     <ApplicationUrl>http://localhost/SampleApp_ServerSetup/1.0.0.0/</ApplicationUrl>
</VersionConfig>
用来描述需要下载文件所在的目录

Downloader.DownloadRetryAttempts : 下载重试次数 
Downloader.SecondsBeteweenDownloadRety : 
Downloader.UpdateRetryAttempts : 
Downloader.ValidateAssemblies : 是否进行了Strong Name检查后才进行下载.

Poller.AutoStart : 是否在程序启动后自动检测
Poller.DownloadOnDetection : 是否在检测到更新后自动下载
Poller.InitialPollInterval : 程序启动后多长时间开始检测.
Poller.PollInterval

使用AppUpdater.dll

1.Create 一个带Form的Project,把 .Net Updater Component揪到From上,并配置

2.Client端
Build出一个AssemblyVersion为1.0.0.0的SampleApp.exe
c:\ClientSetup\Appstart.config
                   \AppStart.exe
                  \1.0.0.0\
                             \SampleApp.exe

Appstart.config的内容为
<Config>
    <AppFolderName>1.0.0.0</AppFolderName>
    <AppExeName>SampleApp.exe</AppExeName>
</Config>

3.Server端
Build出一个AssemblyVersion为2.0.0.0的SampleApp.exe
Create VD ServerSetup

ServerSetup\UpdateVersion.xml
                \2.0.0.0\

UpdateVersion.xml的内容为:
<VersionConfig>
    <AvailableVersion>3.0.0.0</AvailableVersion>
    <ApplicationUrl>http://localhost/ServerSetup/2.0.0.0/</ApplicationUrl>
</VersionConfig>

配置IIS,由于.net updater component使用了HTTP-DAV协议,所以在vd ServerSetup上要打开
"Directory Browsing"选项.

4.把玩
在Client端运行SampleApp.exe, 可看到提示是否需要更新…

5.深入讨论按需下载.
把AutoFileLoad设为true可实现按需下载,下载需要时间,此时applicatin 会完全失去相应

6.安全
1.拦截数据包,并篡改
解药:使用HTTPS,做法很简单只要使用HTTPS URL代替 HTTP URL
但价格昂贵,HTTPS会加密被下载的所有文件.

2.服务器上的文件被篡改.
解药:使用strong name..net updater component会比较已安装的组件的public key和要下载的组件
的public key,只有被相同private key标记的assembly才会由相同的public key, 所以如果一致,
就认为要下载的文件是合法的.
但在现实中,Application的各个组件常常是由不同的private key标记的,比如有这样的application,
由一个exe和一个第3方控件组成.此时,构造一个名为AppUpdateKeys.dll的assembly,
public class KeyList
{
public static byte[][] Keys;
public static string[] ExceptionList;

static KeyList()
{
//Add the list of public keys your app uses here
Keys = new byte[][]
{
new byte[] { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 95, 81, 246, 90, 218, 186, 162, 97, 166, 49, 31, 81, 219, 192, 9, 180, 14, 174, 24, 158, 138, 225, 14, 38, 226, 192, 31, 171, 74, 47, 210, 255, 104, 31, 90, 175, 172, 246, 149, 141, 132, 248, 25, 166, 64, 102, 240, 89, 239, 22, 97, 54, 233, 217, 7, 155, 23, 87, 172, 111, 39, 104, 48, 97, 200, 50, 155, 32, 37, 42, 212, 167, 201, 220, 50, 119, 84, 201, 191, 19, 164, 227, 94, 9, 44, 79, 115, 18, 25, 236, 73, 169, 16, 14, 84, 241, 175, 110, 112, 223, 214, 81, 111, 220, 222, 16, 224, 208, 204, 65, 108, 207, 171, 88, 52, 149, 212, 147, 62, 9, 112, 118, 105, 25, 24, 161, 235, 213 }
};

//Add the list of files that don’t need to be signed, but are allowed to be downloaded even if not signed.
//PDB files would be a good example of this type of file.
ExceptionList = new string[] {"simpleform.dll", "simpleform.pdb"};
}
}
AppUpdateKeys.dll包含了应用程序用到的所有assembly的public key,然后用应用程序的private key
来标记AppUpdateKeys.dll,下载时updater会首先对比AppUpdateKeys.dll的public key和应用程序的publickey,
如果通过验证,就下载AppUpdateKeys.dll,并提取AppUpdateKeys.dll中所有的public key,包含这些 public key
的Assembly就被认为是合法的.同时AppUpdateKeys.dll和可以定义一个ExceptionList, list中的文件可以不进行
验证.

实际应用 Terrarium:
Terrarium hook .NET Application Updater component 的 OnCheckForUpdate event,并在event handler中调用web
service来检查更新.OnCheckForUpdate是由poller 线程引发的,所以调用web service不会lock UI 线程.

Terrarium hook .NET Application Updater component 的 OnUpdateComplete event 使用自定义的UI, OnUpdateComplete
由UI 线程引发,所以可以直接在OnUpdateComplete的event handler中使用UI.

附录:
.Net 平台上的其他自动升级方案

Updater Application Block version 2.0
http://www.microsoft.com/downloads/details.aspx?FamilyID=c6c09314-e222-4af2-9395-1e0bd7060786&DisplayLang=en

Using the Updater Application Block
http://www.theserverside.net/tt/articles/showarticle.tss?id=UpdateAppBlock

DotNet No-Touch Deployment (NTD)
http://www.dotnet-online.de/web/notouch/

Clickonce
http://www.windowsforms.net/WhidbeyFeatures/default.aspx?PageID=2&ItemID=19&Cat=Runtime&tabindex=5

June 10, 2006

.NET Assembly的Versions

Filed under: .NET

参考 CLR via C# Assemlby Version Resource Information

.NET Assebly的Versions

Version 的格式
Major Number.Minor Number.Build Number.Reversion Number
Major Number和Minor Number是面向用户的版本.
Build Number 每次build递增一次.
Reversion Number 对build进行修订, 比如修改了一个daily build中一个严重的bug.

Jeffrey Richter 在书中写道:未来的CLR会自动加载最新版本的Assembly,并在新版本出错时
自动加载老版本, CLR希望Assembly在修改了一些bug后保持相同的Major Number和Minor Number,
用Build Number和Reversion Number来描述bug的修改.

既然Build Number 每次build递增一次,有没有什么工具来自动完成这个工作呢?答案是:自理.

每个Assebmly包含三个Version
AssemblyFileVersion :存储在win32资源中, CLR不关心这个版本号,
AssemblyInformationnalVersion :存储在win32资源中, CLR不关心这个版本号,此版本号用来表示包含
Assembly的产品的版本
AssemblyVersion: 存储在AssemblyDef manifest metadata table中,CLR会使用这个版本号

工具的支持:
CSC.exe和AL.exe在每次build时可以自动增加AssemblyVersion, 但要慎用.改变一个Assembly的
AssemblyVersion会导致引用这个Assembly的其它Assembly无法工作.

在VS会为每一个.net Porject生成 AssemblyInfo.cs 可在其中设置相关的信息.
[assembly: AssemblyVersion(”1.0.0.0″)]
[assembly: AssemblyFileVersion(”1.0.1.0″)]
如果使用[assembly: AssemblyVersion(”1.0.*”)], 在每次程序修改后build或rebuild后, assembly的
AssemblyVersion的Build Number和 ReversionNumber和会自动增加.ReversionNumber每次都变,
Build Number随日期的变化而变化.

有没有什么工具可以显式地设置一个solution中所有的project的AssemblyVersion?

通过程序获得版本信息:
//== Get File Version
System.Diagnostics.FileVersionInfo.GetVersionInfo

//==Get Assembly Version
AssemblyName assName = Assembly.GetExecutingAssembly().GetName();
string version = assName.Version.ToString();

对于一个win32的exe或dll,在Explore中查看它的属性(Properties->Version)可以看到
File Version
Product Version

一个.net Assembly在Explore中查看它的属性(Properties->Version)可以看到
Assebly Version (对应 AssemblyVersion)
File Version (对应 AssemblyFileVersion)
Product Version (对应 AssemblyInformationnalVersion, 如果不指定,则和AssemblyFileVersion对应)

_NET程序中的重画

Filed under: .NET

参考
MSDN : Synchronous and Asynchronous Drawing

Control.Invalidate()

查看 Reflector的结果
//–.net 1.1
public void Invalidate(bool invalidateChildren)
{
if (this.window.Handle != IntPtr.Zero)
{
if (invalidateChildren)
{
SafeNativeMethods.RedrawWindow(new HandleRef(this.window, this.window.Handle), null, NativeMethods.NullHandleRef, 0x85);
}
else
{
SafeNativeMethods.InvalidateRect(new HandleRef(this.window, this.window.Handle), null, (this.controlStyle & ControlStyles.Opaque) != ControlStyles.Opaque);
}
this.NotifyInvalidate(this.ClientRectangle);
}
}

//–.net 2.0
public void Invalidate(bool invalidateChildren)
{
if (this.IsHandleCreated)
{
if (invalidateChildren)
{
SafeNativeMethods.RedrawWindow(new HandleRef(this.window, this.Handle), null, NativeMethods.NullHandleRef, 0x85);
}
else
{
using (Control.MultithreadSafeCallScope scope1 = new Control.MultithreadSafeCallScope())
{
SafeNativeMethods.InvalidateRect(new HandleRef(this.window, this.Handle), null, (this.controlStyle & ControlStyles.Opaque) != ControlStyles.Opaque);
}
}
this.NotifyInvalidate(this.ClientRectangle);
}
}

SafeNativeMethods.RedrawWindow(new HandleRef(this, this.Handle), null, new HandleRef(region, ptr1), 0x85);
如果invalidateChildren 为true, MS偷了个懒,直接调用了Win32 API RedrawWindow(),
重画了整个window,而不是调用每个子Control的Invalidate

#define RDW_INVALIDATE 0x0001 [*]
#define RDW_INTERNALPAINT 0x0002
#define RDW_ERASE 0x0004 [*]

#define RDW_VALIDATE 0x0008
#define RDW_NOINTERNALPAINT 0x0010
#define RDW_NOERASE 0x0020

#define RDW_NOCHILDREN 0x0040
#define RDW_ALLCHILDREN 0x0080 [*]

#define RDW_UPDATENOW 0x0100
#define RDW_ERASENOW 0x0200

#define RDW_FRAME 0x0400
#define RDW_NOFRAME 0x0800

如果使用了RDW_UPDATENOW, RedrawWindow API会直接调用win proc来处理WM_PAINT消息,而不是向消息队列中
插入WM_PAINT消息,RedrawWindow()才返回.这一点和UpdateWindow()相似.

SafeNativeMethods.InvalidateRgn(new HandleRef(this, this.Handle), new HandleRef(region, ptr1), !this.GetStyle(ControlStyles.Opaque));
这相当于一个异步调用,函数并不会在画法结束后返回,而是产生一个window 的invalidata range.
当窗口的消息队列为空时,windows会在消息队列中添加一个WM_PAINT Message,画法将在WM_PAINT
被处理时执行.如果消息队列中已经包含一个WM_PAINT Message,则windows会计算出一个新的invalidata range,
第3个参数为true,则整个background 在BeginPaint()被调用时被擦掉,对应透明的control(Control.Opaque 为false)
第3个参数为false,则整个background保持不变,对应不透明的control

MultithreadSafeCallScope是一个private class,从名字上看是为了提供线程安全.

Control.Update()
实际直接调用 Win32 API UpdateWindow(new HandleRef(this.window, this.window.Handle));
如果window的invalid range非空,UpdateWindow会直接调用win proc来处理WM_PAINT消息,而不
是向消息队列中插入WM_PAINT消息,处理结束后UpdateWindow()才返回.

Control.Refresh()
Invalidate control 的client area,并立即重画control及其子control
public virtual void Refresh()
{
this.Invalidate(true);
this.Update();
}
由于调用了Update(),Refresh()会在WM_PAINT消息处理函数执行完毕后才返回.

Control.OnPaint
Raises the Paint event,同时提供画法的实现.

June 9, 2006

_NET 中的 Timers

Filed under: .NET

.NET 中的Timer3胞胎

Win32平台上有两种线程:UI线程和工作线程,UI线程大多数时间是空闲的,它实际上是一个形如
while (GetMessage (&msg))
{
ProcessMessage (&msg) ;
}
的循环,如果这个UI线程的消息队列中有消息, UI线程就会取出这个message并处理.
工作线程没有message loop,主要用来在后台处理事务.

System.Windows.Forms.Timer Control
windows timer, 其历史可以追溯到vb 1.0, 主要是为了方便windows froms程序的编写.
有一个Interval属性
为使用UI线程进行事务处理的单线程环境设计,依赖于os的timer message,精度较差,
操作可以在UI线程中进行,也可以在别的线程中进行.

注意windows不会向消息队列中放入多个WM_TIMER消息,而是将多个WM_TIMER消息合并成
一个消息(和WM_PAINT类似),如果设定WM_TIMER消息的间隔为1秒,而消息处理函数的执行
时间超过1秒,在消息3处理函数的执行期间程序不会收到WM_TIMER消息.

System.Timers.Timer component
有一个Interval属性
针对server的多线程环境进行了了优化,采用了和System.Windows.Forms.Timer不同的架构.
值得注意的是System.Timers.Timer的SynchronizingObject属性.如果这个属性为null,处理
Elapsed event由线程池中的线程触发,即Elapsed event的处理函数将运行在系统线程池的
线程中,如果 SynchronizingObject属性被设置为一个Windows Forms component, 那么
Elapsed event的处理函数将运行在生成component的那个线程中,通常情况下,这个线程就
是UI线程.
如果处理Elapsed event的方法的执行时间大于Interval属性的值,又会有一个线程池中的线
程激发Elapsed event,Elapsed event的处理函数将会被重入
.

using System;
using System.Timers;

public class Timer1
{
public static void Main()
{
// Normally, the timer is declared at the class level, so
// that it doesn’t go out of scope when the method ends.
// In this example, the timer is needed only while Main
// is executing. However, KeepAlive must be used at the
// end of Main, to prevent the JIT compiler from allowing
// aggressive garbage collection to occur before Main
// ends.
System.Timers.Timer aTimer = new System.Timers.Timer();

// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;

Console.WriteLine(”Press the Enter key to exit the program.”);
Console.ReadLine();

// Keep the timer alive until the end of Main!
GC.KeepAlive(aTimer);
}

// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine(”Hello World!”);
}
}
注意!由于Elapsed event由线程池中的线程出发,存在着这样的可能:event 的处理函数
正在执行,而另一个线程池中的线程调用的Timer.Stop(),这将导致在Timer.Stop()调用后
Elapsed event仍可被触发.使用Interlocked.CompareExchange()可以避免这种情况.

System.Threading.Timer class
在代码中使用,不依赖于os 的timer
使用 TimerCallback delegate 来指定需要执行的函数,这个函数将执行在线程池
的线程中,而不是生成System.Threading.Timer的线程中.
在timer生成后,可以使用System.Threading.Timer.Change()来重新定义timer的
等待时间和执行间隔时间.
注意,如果使用了System.Threading.Timer,就要保持对Timer的引用,否则,Timer将会被
GC回收,使用Timer.Dispose()可以释放Timer所占用的资源.
由于callback函数由线程池中的线程执行,如果timer的interval值小于callback函数的
执行时间,callback函数会被多个线程执行.如果线程池中的线程被用光,callback函数
会排队等待,不能如期执行.

//—-
using System;
using System.Threading;

class TimerExample
{
static void Main()
{
//信号量,false参数用来设置信号量的初始状态为non-signaled
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);

// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus);

// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250);

// When autoEvent signals, change the period to every 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);

// When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
}
}

class StatusChecker
{
int invokeCount, maxCount;

public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}

// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine(”{0} Checking status {1,2}.”,
DateTime.Now.ToString(”h:mm:ss.fff”),
(++invokeCount).ToString());

if(invokeCount == maxCount)
{
// Reset the counter and signal Main.
invokeCount = 0;
autoEvent.Set();
}
}
}

ThreadPool
线程池中的线程为后台线程,其IsBackgroud为true, 当application的所有前台线程执行
完毕后,就算是线程池中的线程仍在执行,application也会结束.

June 3, 2006

_Net Framework 中的design pattern

Filed under: .NET

出自
Discover the Design Patterns You’re Already Using in the .NET Framework
http://msdn.microsoft.com/msdnmag/issues/05/07/DesignPatterns/

//–Observer Pattern
当一个对象(Subject)发生改变时,会通知另外一个对象(Observer).

最原始的做法是由 Subject 来调用Observer上的方法,这将导致 Subject 与某个特定的 Observer
紧耦合,当Observer的个数不定时,代码将无法控制.

GOF中的Observer Pattern

public abstract class CanonicalSubjectBase
{
private ArrayList _observers = new ArrayList();

public void Add(ICanonicalObserver o)
{
_observers.Add(o);
}

public void Remove(ICanonicalObserver o)
{
_observers.Remove(o);
}

public void Notify()
{
foreach(ICanonicalObserver o in _observers)
{
o.Notify();
}
}
}

public interface ICanonicalObserver
{
void Notify();
}
所有的Observer角色将实现ICanonicalObserver接口,Subject角色派生自CanonicalSubjectBase,

.Net中的Observer Pattern,利用的event 和 delegate

public delegate void Event1Hander();
public delegate void Event2Handler(int a);

public class Subject
{
public Subject(){}

public Event1Hander Event1;
public Event2Handler Event2;

public void RaiseEvent1()
{
Event1Handler ev = Event1;
if (ev != null)
ev();
}

public void RaiseEvent2()
{
Event2Handler ev = Event2;
if (ev != null)
ev(6);
}
}

public class Observer1
{
public Observer1(Subject s)
{
s.Event1 += new Event1Hander(HandleEvent1);
s.Event2 += new Event2Handler(HandleEvent2);
}

public void HandleEvent1()
{
Console.WriteLine(”Observer 1 - Event 1″);
}

public void HandleEvent2(int a)
{
Console.WriteLine(”Observer 1 - Event 2″);
}
}

//–Iterator Pattern
Iterator Pattern被应用在for ,和for each语句中,查看IL代码可以看到

int[] values = new int[] {1, 2, 3, 4, 5};

IEnumerator e = ((IEnumerable)values).GetEnumerator();

while(e.MoveNext())
{
Console.Write(e.Current.ToString() + ” “);
}

//–Decorator Pattern
.NET 对Stream及其派生类的实现是Decorator Pattern的一个范本,Stream的派生类
在派生的同时又包含基类,在保持接口不变的情况下实现了功能的扩展.

MemoryStream ms = new MemoryStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
PrintBytes(ms); //不变

BufferedStream buff = new BufferedStream(ms);
PrintBytes(buff);
buff.Close(); //不变

FileStream fs = new FileStream(”../../decorator.txt”, FileMode.Open);
PrintBytes(fs); //不变
fs.Close();

//–Adapter Pattern
.NET Framework的一个强大之处就是实现了向后兼容,.NET代码 和 COM对象之间可以
任意调用. 在.net 代码中调用COM对象只需使用VS.NET的”Add Refrence”来引入这个
COM对象,VS.NET会调用tlbimp.exe来生成一个包含Runtime Callable Wrapper (RCW)
class的interop assembly, .NET通过调用 RCW class中的方法来使用COM对象.
需要注意的是COM对象使用了和.NET不同的数据类型和错误处理机制,比如,.NET使用
System.String 而 COM对象使用 BSTR , COM组件中的方法返回一个 HRESULT 来标识执行
结果,而RCW 会产生exception,供其他的managed 代码处理.
在.net代码中调用一个包含string 参数的COM方法, 可直接传入System.String,RCW
会负责把System.String转化成 BSTR.

Adapter Pattern 中Adapter 封装了 Adaptee,这一点和Decorator Pattern有所类似,
但二者的区别在于Decorator 中object的接口保持不变,Adapter可以改变接口.

//–Factory Pattern
.NET Framework中有大量的class,在使用时不是通过调用构造器来产生实例的,
比如使用System.Convert.ToXXX() 静态方法可进行对象转换,产生新的实例.
System.Net.WebRequest.Create() 会根据传入的URI参数产生对应的Request实例,

//–Strategy Pattern
Array 和 ArrayList 都提供了Sort()方法,它们的Sort()方法都使用了QuickSrot算法
缺省情况下Sort()方法利用List中各个元素对IComparable的实现来比较,但也可以传入一个
实现了IComparer的参数,使用IComparer.Compare()方法来排序.比如:

public class Certificate
{

public static List<Certificate> GetAllCertificate(String sortExpression)
{
SQLDataAccess dataAccess = SQLDataAccess.GetSQLDataAccess();
List<Certificate> certificates = dataAccess.GetAllCertificate();
certificates.Sort(new CertificateComparer(sortExpression));
return certificates;
}

}

public class CertificateComparer : IComparer<Certificate>
{
private bool _reverse;
private string _sortColumn;

public CertificateComparer(string sortExpression)
{
_reverse = sortExpression.ToLowerInvariant().EndsWith(” desc”);
if (_reverse)
{
_sortColumn = sortExpression.Substring(0, sortExpression.Length - 5);
}
else
{
_sortColumn = sortExpression;
}

}

public int Compare(Certificate a, Certificate b)
{
int retVal = 0;
switch (_sortColumn)
{
case “Type”:
retVal = (int)a.CertificateType - (int)b.CertificateType;
break;
case “Name”:
retVal = String.Compare(a.CertificateName, b.CertificateName, StringComparison.InvariantCultureIgnoreCase);
break;
case “Description”:
retVal = String.Compare(a.Description, b.Description, StringComparison.InvariantCultureIgnoreCase);
break;
}
return (retVal * (_reverse ? -1 : 1));
}
}

List<T>.FindXXX<T>(Predicate<T>) 系列方法可以使用传入的Predicate<T> delegate来查找元素,
Predicate<T> delegate的定义如下:
public delegate bool Predicate<T> (T obj)

using System;
using System.Collections.Generic;

public class Example
{
public static void Main()
{
List<string> dinosaurs = new List<string>();

dinosaurs.Add(”Compsognathus”);
dinosaurs.Add(”Amargasaurus”);

Console.WriteLine(”\nTrueForAll(EndsWithSaurus): {0}”, dinosaurs.TrueForAll(EndsWithSaurus));
Console.WriteLine(”\nFind(EndsWithSaurus): {0}”, dinosaurs.Find(EndsWithSaurus));
Console.WriteLine(”\nFindLast(EndsWithSaurus): {0}”,dinosaurs.FindLast(EndsWithSaurus));
}

// Search predicate returns true if a string ends in “saurus”.
private static bool EndsWithSaurus(String s)
{
if ((s.Length > 5) && (s.Substring(s.Length - 6).ToLower() == “saurus”))
{
return true;
}
else
{
return false;
}
}
}

//–Composite Pattern in ASP.NET
准确的说应该是.net 的control设计中到处体现了Composite Pattern, Parent control中包含了 sub control,
对from或page的重画调用可以通过这种层级关系一层层传递下去.

//–Template Method Pattern
重载父类方法:
Page.CreateChildControl()
Page.Render()
….

//–Patterns in the ASP.NET Pipeline
从一个web request到在浏览器上显示出结果会经过多个步骤:
Request -> IIS + aspnet_isapi.dll -> ASP.net Work process

-> HttpApplication -> HttpModules * n -> HeepHandler
其中, HttpApplication 通常是由 Global.asax 产生的, HttpModules是一些实现了IHttpModule
接口的class, 每个HttpModule都会修改request,然后把request传递给下一个HttpModule,ASP.NET
提供了一些标准的module:FormsAuthenticationModule, PassportAuthenticationModule,
WindowsAuthenticationModule, and SessionStateModule…最后,request被交给了HttpHandler,
一个HttpHandler是实现了IHttpHandler接口的class, 最典型的HttpHandler就是System.Web.UI.Page
在IHttpHandler.ProcessRequest 中,Page 会发出一系列的events:Init, Load, and Render,处理
ViewState.

//–Intercepting Filter Pattern
HttpApplication class 在处理 request时会发出一系列的event,BeginRequest, AuthenticateRequest,
AuthorizeRequest, and EndRequest,当HttpApplication加载某个HttpModule时,会调用 IHttpModule.Init()
HttpModule会利用这个机会来注册它所关心的event.

//–Other Web Presentation Patterns in ASP.NET
MVC 模式:View:ASPX 页面, Model-Control: codebehind file.

May 26, 2006

在Managed代码中慎用API

Filed under: .NET

引自
ExitThread() in managed program?
http://blogs.msdn.com/yunjin/archive/2004/01/30/65386.aspx

以下代码有问题吗?
[DllImport( "Kernel32.dll")]
public static extern void ExitThread(int exitCode);

public static void Run ()
{
    …
    // calling OS’s ExitThread to exit the current thread
    ExitThread (0);
}

public static void Main ()
{
    ThreadStart threadStart = new ThreadStart(Run);
    Thread thread = new Thread(threadStart);
    thread.Start();
    …
}

需要注意的是在CLR的控制下,某些系统调用在unmanaged和managed环境下的行为并不相同,
ExitThread就是其中一个,同时,managed threads 和unmanaged threads 也有所不同.
1.当一个managed thread退出时,比如线程处理函数返回或ThreadAbortException被抛出,
CLR会作一些清理的工作(比如stack unwinding),调用API ExitThread()或TerminateThread()
会绕过析构函数的调用,或finally 代码块.

2.在某些情况下,可能有好几个managed thread 被映射到一个OS thread,调用ExitThread 可能
会终止多个 managed thread.

Managed Heap Object pinned

Filed under: .NET

引自
OutOfMemoryException and Pinning
http://blogs.msdn.com/yunjin/archive/2004/01/27/63642.aspx

如果大量使用锁定的object,managed heap会被不可移动的内存块分割
成很多的小碎片,导致OutOfMemoryException.
比如Socket.BeginReceive的buffer参数就会被锁定, 以便unmanaged code 可以
访问这个buffer.

使用SOS可以发现
0:000>!dumpheap

     Address       MT     Size
     00a71000 0015cde8       12 Free
     00a7100c 0015cde8       12 Free
     00a71018 0015cde8       12 Free
     00a71024 5ba58328       68
     00a71068 5ba58380       68
     00a710ac 5ba58430       68
     00a710f0 5ba5dba4       68
     …
     00a91000 5ba88bd8     2064
     00a91810 0019fe48     2032 Free
     00a92000 5ba88bd8     4096
     00a93000 0019fe48     8192 Free
     00a95000 5ba88bd8     4096
     …
     total 1892 objects

     Statistics:
           MT    Count TotalSize Class Name
     5ba7607c        1        12 System.Security.Permissions.HostProtectionResource
     5ba75d54        1        12 System.Security.Permissions.SecurityPermissionFlag
     5ba61f18        1        12 System.Collections.CaseInsensitiveComparer
     …
     0015cde8        6     10260      Free
     5ba57bf8      318     18136 System.String
     …
    
以上数据表明在heap中有3个free slots
statistics一节显示heap中有10,260 bytes的Free objects和18,136 bytes 的字符串.
之所以可以看到这些free object,就说明这些free ojbect处在无法回收的live object之间.
如果heap中存在大量的Free objects,就表明heap中存在大量的内存碎片.

进一步可以使用
0:000>!dumpobj 00a92000    //00a92000 处的对象是一个byte array
   Name: System.Byte[]
   MethodTable 0x00992c3c
   EEClass 0x00992bc4
   Size 4096(0x1000) bytes
     Array: Rank 1, Type System.Byte
     Element Type: System.Byte
    
0:000>!gcroot 00a92000     //address 00a92000 it’s rooted by local variables in thread 1
   Scan Thread 0 (728)
     Scan Thread 1 (730)
     ESP:88cf548:Root:05066b48(System.IO.MemoryStream)->00a92000 (System.Byte[])
     ESP:88cf568:Root:05066b48(System.IO.MemoryStream)->00a92000 (System.Byte[])
     …
     Scan HandleTable 9b130
     Scan HandleTable 9ff18
     HANDLE(Pinned):d41250:Root: 00a92000 (System.Byte[])  //pinned handle.

0:000>!objsize   //显示所有pinned 对象的handle
    …
     HANDLE(Pinned):d41250: sizeof(00a92000) = 4096 ( 0x1000) bytes (System.Byte[])
     HANDLE(Pinned):d41254: sizeof(00a95000) = 4096 ( 0x1000) bytes (System.Byte[])
     HANDLE(Pinned):d41258: sizeof(00ac8b5b0) = 16 ( 0x10) bytes (System.Byte[])
     …

查看对象的详细信息,

可以采用以下措施来减小锁定 object的负面影响:
1.尽量使两个相邻的锁定 object挨得更紧.
2.尽量使锁定 object处在heap的底部,这是由于free的内存集中在heap的顶部.
3.缩短object被锁定的时间.
4.不要每次create一个对象,然后锁定它,而是重用被锁定的对象.

以下的代码演示如何使用一个1k的被锁定的buffer:

public class BufferPool
{
    private const int INITIAL_POOL_SIZE = 512; // initial size of the pool
    private const int BUFFER_SIZE = 1024; // size of the buffers

    // pool of buffers
    private Queue m_FreeBuffers;

    // singleton instance
    private static BufferPool m_Instance = new BufferPool();
    public static BufferPool Instance
    {
        get
        {
            return m_Instance;
        }
    }

    protected BufferPool()
    {
        m_FreeBuffers = new Queue(INITIAL_POOL_SIZE);
        for (int i = 0; i < INITIAL_POOL_SIZE; i++)
        {
            m_FreeBuffers.Enqueue(new byte[BUFFER_SIZE]);
        }
    }

    // check out a buffer
    public byte[] Checkout(uint size)
    {
        if (m_FreeBuffers.Count > 0)
        {
            lock (m_FreeBuffers)
            {
                if (m_FreeBuffers.Count > 0)
                    return (byte[])m_FreeBuffers.Dequeue();
            }
        }
      // instead of creating new buffer,
        // blocking waiting or refusing request may be better

        return new byte[BUFFER_SIZE];
    }

    // check in a buffer
    public void Checkin(byte[] buffer)
    {
        lock (m_FreeBuffers)
        {
            m_FreeBuffers.Enqueue(buffer);
        }
    }
}

 

May 20, 2006

.NET 多线程1_基本操作

Filed under: .NET

和Jave一样, .net从语言级别上支持了线程操作.

//—————–.NET 定义的线程的状态
System.Threading.ThreadState
System.Diagnostics.ThreadState

//——————–Thread 相关的class
System.Threading.Thread
System.Threading.ThreadStart

System.Threading.Timer

System.Threading.ThreadPool

 

//—————- Create Thread
Thread threadObj = new Thread(new ThreadStart(MyWorkerThreadMethod)); //此时state为 Unstarted.
threadObj.Start();  //注意,此时线程一定马上执行,OS会负责把线程从ready态设置到running态.

MyWorkerThreadMethod()要符合ThreadStart Delegate的格式: 无参数,无返回值.可以是静态方法.

//—————- 访问线程信息
Thread currentThreadObject =Thread.CurrentThread;
currentThreadObject.Name = "PrimaryThread";

//—————–操作线程
//—- 挂起
if (threadObject.ThreadState ==ThreadState.Running )
{
  threadObject.Suspend();
}

//—- 恢复
if (threadObject.ThreadState ==ThreadState.Suspended )
{
  threadObject.Resume();
}

//—- Sleep
Thread.Sleep(5000);
Thread.Sleep(TimeSpan.Infinite);

//—- 等待另一个线程结束
if(Thread.CurrentThread.GetHashCode() != threadObject.GetHashCode())
{
    threadObject.Join();   
    //or threadObject.Join(1000);      
}

//—- 结束线程
if (threadObject.IsAlive == true )
{
  threadObject.Abort();
}

会引发一个ThreadAbortException Exception

//——————线程同步
保证在某一时刻,只能有一个线程访问某个数据块

private static readonly object lockObj = newobject();

Test obj = null;
lock(lockObj)
{
     if(obj == null)
        obj = new Test();
}

[*]引用一道网上流传的c#面试题:
调用test方法时i>10时是否会引起死锁?

public void test(int i)
{
    lock(this)
    {
        if (i>10)
        {
            i - - ;
            test(i);
        }
    }
}
我想不会,整个代码中没有哪一行要访问this的实例数据.

 

参考
Working with Threads in C# (2006.05.18)
http://aspalliance.com/846

Multithreading in .NET
http://www.codeproject.com/dotnet/multithread.asp

CLR 的线程池(Jeffrey Richter)
http://www.microsoft.com/china/MSDN/library/netFramework/netframework/NECLRT.mspx?mfr=true
http://msdn.microsoft.com/msdnmag/issues/03/06/NET/

利用.Net 线程池提高应用程序性能
http://edobnet.cnblogs.com/archive/2005/11/29/287094.html

.NET’s ThreadPool Class - Behind The Scenes
http://www.codeproject.com/csharp/threadtests.asp

ASP.NET 2.0 中的异步页
http://www.microsoft.com/china/msdn/library/webservices/asp.net/issuesWickedCodetoc.mspx?mfr=true

如何取字符串的字节数

Filed under: Code snippets

int len = System.Text.Encoding.Default.GetBytes(strTest).Length;

和 strTest.Length 不同,后者返回的是字符数.

May 16, 2006

4种字符串判空的方法

Filed under: C#

1.  myStr.Length == 0

2.  myString == String.Empty

3.  myString==""

4.  String.IsNullOrEmpty (2.0)

在1.0时,FxCop推荐使用方法1,但为了防止null refrence,我们得先判一下null.

2.0有了新的静态方法IsNullOrEmpty(),那个最好呢?

使用Reflector打开.net 2,050727 下的mscorlib.dll

1 的代码为

[MethodImpl(MethodImplOptions.InternalCall)]
public extern int get_Length();

2和3  要使用了运算符==,而string的==的代码为

public static bool operator ==(string a, string b)
{
      return string.Equals(a, b);
}

string.Equals的代码为:

public static bool Equals(string a, string b)
{
      if (a == b)
      {
            return true;
      }
      if ((a != null) && (b != null))
      {
            return string.EqualsHelper(a, b);
      }
      return false;
}
看到这,你恐怕不会使用这种方法了吧.更有甚者myString==""还会先new一个空串出来.更浪费资源.

4 的代码为:

public static bool IsNullOrEmpty(string value)
{
      if (value != null)
      {
            return (value.Length == 0);
      }
      return true;
}

正是我们期待已久的答案.

string.Equals的静态方法和实例方法哪个更快

Filed under: C#

比较string是否相等可以使用静态方法String.Equals(), 也可以调用字符串的实例方法, 用reflector察看mscorlib.dll

–Instance Equals method implementation:
<.net  2.0.50727>
public bool Equals(string value)
{
    if ((value == null) && (this != null))
    {
        return false;
    }

    return string.EqualsHelper(this, value);
}

<.net 1.1>
[MethodImpl(MethodImplOptions.InternalCall)]
public extern bool Equals(string value);

An internal call is a call to a method implemented within the common language runtime itself.
 

–Static Equals method implementation:
<.net  2.0.50727>
public static bool Equals(string a, string b)
{
      if (a == b)
      {
           return true;
      }
      if ((a != null) && (b != null))
      {
           return string.EqualsHelper(a, b);
      }
      return false;
}

<.net 1.1>
public static bool Equals(string a, string b)
{
      if (a == b)
      {
            return true;
      }
      if ((a != null) && (b != null))
      {
            return a.Equals(b);
      }
      return false;
}

[*]读EqualsHelper的代码,可以看看MS是怎么比字符串的.

可以看到,静态方法会先比较refrence,如果事先知道字符串相等的可能性较大,使用静态方法会快那么一点点.

 

May 15, 2006

操作Windows Service

Filed under: Code snippets

Namespace: System.ServiceProcess
Assembly: system.serviceprocess.dll

//—-判断本机是否运行了某项服务

ServiceController service = new ServiceController("MSSQLSERVER");

if(service.Stauts == ServiceProcess.ServiceControllerStatus.Running){…}

//—改变Service运行状态

private const string myService = "XXX";

ServiceController service = new ServiceController(myService );

if(service.Status != ServiceControllerStatus.Stopped)

{

    service.Stop();

    serviceControl.WaitForStatus(ServiceControllerStatus.Stopped);

}

service.Start();

//—-安装.net service

%SystemRoot%\Microsoft.NET\Framework\<Version>\InstallUtil /u /name=S1 myService.exe
%SystemRoot%\Microsoft.NET\Framework\<Version>\InstallUtil /name=S1 myService.exe
%SystemRoot%\system32\services.msc /s

//—-命令行操作

net start "myService"

net stop "myService"

Check UNC path

Filed under: Code snippets

Uri uri = new Uri("……….");

–Indicating whether the Uri is a universal naming convention (UNC) path.

Uri.IsUnc

–Indicating whether the specified Uri references the local host.

Uri.IsLoopback

C#的const和readonly

Filed under: C#

–相同

const和readonly的值一旦初始化则都不再可以改写.

–不同

    const只能在声明时初始化;readonly既可以在声明时初始化也可以在构造器中初始化;
    const隐含static,不可以再写static const;readonly则不默认static,如需要可以写static readonly;
    const是编译期静态解析的常量(因此其表达式必须在编译时就可以求值);readonly则是运行期动态解析的常量;
    const既可用来修饰类中的成员,也可修饰函数体内的局部变量;readonly只可以用于修饰类中的成员

得到windows安装路径

Filed under: Code snippets

方法1 使用API

Private Declare Function GetWindowsDirectory Lib "kernel32.dll" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
 
‘ Return values as C:\Windows or <Driver>:\Windows
Public Function GetTheWindowsDirectory() As String
    Dim strWindowsDir As String        ‘ Variable to return the path of Windows Directory
    strWindowsDir = Space(250)         ‘ Initilize the buffer to receive the string
    GetWindowsDirectory(strWindowsDir, 250) ‘ Read the path of the windows directory
    Return strWindowsDir
End Function
   
方法2
Environment.GetEnvironmentVariable("windir")

Is string null or empty?

Filed under: Code snippets

Cheap and interesting trick:

    Convert.ToString((object)stringVar) == ""
 
This works because Convert.ToString(object) returns an empty string if object is null. 

注意!!!
Convert.ToString(string) returns null if string is null.

(Or, if you’re using .NET 2.0 you could always use String.IsNullOrEmpty.)

其实以上的代码还可以再优化一点点:

根据FxCop的建议,我们应该使用

 Convert.ToString((object)stringVar).Length==0

数字,日期的格式化

Filed under: Code snippets

–Custom Numeric Format Strings

    int a =100;
    Console.WriteLine(a.ToString("000000"));
   

    输出"000100"
  
– Standard Numeric Format Strings
    比如输出16进制数 X or x    Hexadecimal

    Console.WriteLine(a.ToString("X"));

    输出"64"

    Console.WriteLine(a.ToString("X6"));

    输出"000064"

– Composite Formatting

    Each format item takes the following form.
             {index[,alignment][:formatString]}

    String.Format("hours = {0:hh}", DateTime.Now); 得到 hours = 07

    String.Format("Date = {0:yy/MM/dd}", DateTime.Now);  得到 Date = 06-05-15

 

序列化

Filed under: Code snippets

参考
http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpguide/html/cpconBasicSerialization.asp

一个Class实现序列化需要使用SerializableAttribute() Attribute或实现ISerializable

缺省情况下,一个被SerializableAttribute标记的类型中的所有public和
private field(除过NonSerialized标记的field)都会被
序列化,如果想改变序列化的处理过程,需要实现ISerializable.
如果类型中包含pointer,将有可能无法从另一个环境中被反序列化,此时应该
用NonSerialized标记point字段

!!需要特别注意的是,Serializable 属性不能被继承。如果我们从 MyObject 派生一个新类,
此新类必须也用该属性标记,否则它不能被序列化。例如,当您试图序列化下面的类的实例时,
您将获得 SerializationException。

//========= A test object that needs to be serialized.
[Serializable()]       
public class TestSimpleObject 
{

    public int member1;
    public string member2;
    public string member3;
    public double member4;
   
    // A field that is not serialized.
    [NonSerialized()] public string member5;
   
    }
}

//=========使用
//==Bin
FileStream fs = new FileStream("my.bin" , FileMode.Creat);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs , myObj);
fs.Close();

//==Soap
FileStream fs = new FileStream("my_Soap.xml" , FileMode.Creat);
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(fs , myObj);
fs.Close();

//==XML
FileStream fs = new FileStream("my.xml" , FileMode.Creat);
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(MyType));
xmlSer.Serialize(fs , myObj);
fs.Close();

//==Deserialize
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();

如何得到当前Application的cofig文件的路径

Filed under: Code snippets

string cfgFullPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

如何在程序运行时得到当前的call stack

Filed under: Code snippets

需要引入以下的namespace
using System.Diagnostics; //For StackTrace
using System.Reflection;  //MethodInfo

Step1. Create a StackTrace
    StackTrace stackTrace = new StackTrace();
    大多时情况下,我们希望在exception 发生时找到引发exceptioin的代码,
    此时需要使用
    try
    {
        …
    }
    catch(Exception exp)
    {
        StackTrace stackTrace = new StackTrace(exp);
    }
    此时通过stackTrace.ToString() 已经可以得到大致的callstack信息.

step2. 通过StatckFrame得到代码信息

    int frameCount = stackTrace.FrameCount;   
    for (int i = 0; i < frameCount; i++)
    {
        StackFrame stackFrame = stackTrace.GetFrame(i);

        // Display the stack frame properties.
        Console.WriteLine(" File: {0}", stackFrame.GetFileName());
        Console.WriteLine(" Line Number: {0}", stackFrame.GetFileLineNumber());
        Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber());
        //还有很多其他的功能GetILOffset(),GetNativeOffset()…
    }

step3. 通过MethodInfo得到每一个函数的信息,用到的主要是Reflection的技巧
    int frameCount = stackTrace.FrameCount;   
    for (int i = 0; i < frameCount; i++)
    {
        StackFrame stackFrame = stackTrace.GetFrame(i);
        MethodInfo methodInfo = (MethodInfo)stackFrame.GetMethod();
       
        //1 get Access
        string access = string.Empty;
        if (methodInfo.IsPrivate)
            access = "private ";
        else if (methodInfo.IsPublic)
            access = "public ";
        else if (methodInfo.IsFamily)
            access = "protected ";
        else if (methodInfo.IsAssembly)
            access = "Internal ";
       
        if (methodInfo.IsStatic)
            access += "static ";
       
        //2 method nanme
        string methodName = methodInfo.Name;
       
        //3 parameter info
        ParameterInfo[] pInfos = methodInfo.GetParameters();
        string paramterList = string.Empty;
        for (int j = 0; j < pInfos.Length; j++)
        {
            paramterList += string.Format(", {0} {1}", pInfos[j].ParameterType.Name, pInfos[j].Name);
        }
       
        // Get rid of the first ", " if it exists.
        if (paramterList.Length > 2)
            paramterList = paramterList.Substring(2);
       
        string output = access + methodInfo.ReturnType.Name + " "+ methodName + "(" + paramterList + ")";
        Console.WriteLine(output);
       
    }   

如何得到.net framework的安装路径

Filed under: Code snippets

LOCAL_MACHINE\software\Microsoft\.NetFramework
下可以看到 InstallRoot为"C:\WINDOWS\Microsoft.NET\Framework\"

LOCAL_MACHINE\software\Microsoft\.NetFramework\policy
下会有key
v1.1
v2.0

每个key下会有当前的次版本号:
如:
v1.1->4322
v2.0->50727
根据InstallRoot, primer version, sub version就可以得到.net frame work的安装路径.

C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

May 14, 2006

如何判断一个dll是否是.net assembly

Filed under: Code snippets

方法1.

引用自http://lozanotek.com/archive/2004/11/15/159.aspx

private const int COR_E_ASSEMBLYEXPECTED = -2147024885;
private bool IsAssembly(string asmFile)
{
    bool isAsmbly = true;
    try
    {
         AssemblyName.GetAssemblyName(asmFile);
    }
    catch(BadImageFormatException imageEx)
    {
         int hrResult = Marshal.GetHRForException(imageEx);
         isAsmbly = (hrResult != COR_E_ASSEMBLYEXPECTED);
    }

    return isAsmbly;
}
方法2.运用PE格式的知识,佩服.

出自http://geekswithblogs.net/rupreet/archive/2005/11/02/58873.aspx

  public static bool GetCLRHeaders(string fileFullName)
        {
            uint peHeader;
            uint peHeaderSignature;
            ushort machine;
            ushort sections;
            uint timestamp;
            uint pSymbolTable;
            uint noOfSymbol;
            ushort optionalHeaderSize;
            ushort characteristics;
            ushort dataDictionaryStart;
            uint[] dataDictionaryRVA = new uint[16];
            uint[] dataDictionarySize = new uint[16];

            Stream fs = new FileStream(fileFullName, FileMode.Open, FileAccess.Read);
            try
            {
                BinaryReader reader = new BinaryReader(fs);

                //PE Header starts @ 0x3C (60). Its a 4 byte header.
                fs.Position = 0x3C;
                peHeader = reader.ReadUInt32();

                //Moving to PE Header start location…
                fs.Position = peHeader;
                peHeaderSignature = reader.ReadUInt32();

                //We can also show all these value, but we will be      
                //limiting to the CLI header test.
                machine = reader.ReadUInt16();
                sections = reader.ReadUInt16();
                timestamp = reader.ReadUInt32();
                pSymbolTable = reader.ReadUInt32();
                noOfSymbol = reader.ReadUInt32();
                optionalHeaderSize = reader.ReadUInt16();
                characteristics = reader.ReadUInt16();
                /*
                    Now we are at the end of the PE Header and from here, the
                    PE Optional Headers starts…
                    To go directly to the datadictionary, we’ll increase the
                    stream’s current position to with 96 (0x60). 96 because,
                    28 for Standard fields
                    68 for NT-specific fields

                    From here DataDictionary starts…and its of total 128 bytes. DataDictionay has 16 directories in total,
                    doing simple maths 128/16 = 8.
                    So each directory is of 8 bytes.
                    In this 8 bytes, 4 bytes is of RVA and 4 bytes of Size.
                    btw, the 15th directory consist of CLR header! if its 0, its not a CLR file :)
                  */

                dataDictionaryStart = Convert.ToUInt16(Convert.ToUInt16(fs.Position) + 0x60);
                fs.Position = dataDictionaryStart;
                for (int i = 0; i < 15; i++)
                {
                    dataDictionaryRVA[i] = reader.ReadUInt32();
                    dataDictionarySize[i] = reader.ReadUInt32();
                }
                return dataDictionaryRVA[14] != 0;
            }
            finally
            {
                fs.Close();
            }
        }






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham