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

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;

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();

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);

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 26, 2006

Assembly执行路径

Filed under: Code snippets

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

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

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

June 13, 2006

获取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

May 20, 2006

如何取字符串的字节数

Filed under: Code snippets

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

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

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

得到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