DLL Exports

DLL Exports
一般来说,VB和VC共同编程有3种方式:一种是VC生成DLL,在VB中调用DLL;一种是VC生成ActiveX控件(.ocx),在VB中插入;还有一种是在VC中生成ActiveX Automation服务器,在VB中调用。相对而言,第一种方法对VC编程者的要求最低,但要求你的伙伴进行配合,我推荐这种方法。
    先说说VC++的编程。首先在VC++中生成Win32 DLL工程。在这个工程中添加几个函数供VB用户调用。一个DLL中的函数要想被VB调用,必须满足两个条件:一是调用方式为stdcall,另一个是必须是export的。要做到第一条,只须在函数声明前加上__stdcall关键字。如:
    short __stdcall sample(short nLen, short *buffer)
    要做到第二条,需要在*.def文件中加上如下的几行:
    EXPORTS
     sample @1
    这里的sample是你要在VB中调用的函数名,@1表示该函数在DLL中的编号,每个函数都不一样。注意这里的函数名是区分大小写的。至于你说的需要传递大量数据,可以这样做,在VB中用一个数组存放数据,然后将该数组的大小和地址传给VC(至于如何在VB中编程我会在下面介绍)。就象上面的例子,nLen是数组大小,buffer是数组地址,有了这两条,你可以象使用VC的数组一样进行处理了。至于输出图形,可以生成WMF或BMP格式,让VB调用。不过,我认为也可以直接输出到视窗,只要VB将窗口的句柄hWnd和hDC以及视窗的绘图位置(VB和VC采用的坐标系必须一致才行)传给VC就行了。而VB的AutoRedraw属性必须为False,在Paint事件中调用VC的绘图程序。
    再谈谈VB的编程。VB调用DLL的方法和调用Windows API的方法是一样的,一般在VB的书中有介绍。对于上面一个例子,先要声明VC函数:
    Declare Function sample Lib "mydll.dll" (ByVal nLen As Integer, buffer As Integer) As Integer
    这里mydll.dll是你的dll的名字。你可能已经注意到了两个参数的声明有所不同,第一个参数加上了ByVal。规则是这样的:如果在VC中某个参数声明为指针和数组,就不加ByVal,否则都要加上ByVal。在VB中调用这个函数采用这样的语法:
    sample 10, a(0)
    这里的a()数组是用来存放数据的,10为数组长度,这里的第二个参数不能是a(),而必须是要传递的数据中的第一个。这是VB编程的关键。
    下面在说几个可能遇到的问题。一个问题是VB可能报告找不到dll,你可以把dll放到system目录下,并确保VB的Declare语句正确。另一个问题是VB报告找不到需要的函数,这通常是因为在VC中*.def文件没设置。第三种情况是VB告诉不能进行转换,这可能是在VC中没有加上__stdcall关键字,也可能是VB和VC的参数类型不一致,注意在VC中int是4个字节(相当于VB的Long),而VB的Integer只有2个字节。必须保证VB和VC的参数个数相同,所占字节数也一致。最后一个要注意的问题是VC中绝对不能出现数组越界的情况,否则会导致VB程序崩溃。
    总的来说,你和你的伙伴需要一些时间来进行协调和摸索,但这种方法绝对可行,也不难掌握。
添加评论
单击隐藏此项的评论。
VC中DLL的创建及调用方法
DLL的创建
首先,用VC集成开发界面中的“新建”,新建一个项目。无论是VC6.0还是VC.NET,都有建立DLL项目的选项。只不过有些稍有不同,例如VC.NET中就有ISAPI DLL,扩展存储过程DLL等,这些都不在讨论的范围。例如我们建立了一个用静态连接MFC库的DLL项目,名称为mydll
然后,编辑mydll.cpp文件,在其中加入我们自己的函数void go()。注意,不需要在mydll.h中声明它,而需要将函数头变成如下样子:
extern “c” __declspec(dllexport) void go()
{
//code……
}
dllexport表示这个函数是由外部调用的。
由于是否带参数,要影响到外部调用的方式,因此,我们再声明一个带参数的函数:
extern “c” __declspec(dllexport) void went(CString str)
{
//code……
}
OK,下面编译连接形成mydll.dll文件。
DLL的调用
好,下面我们就用VC写个程序调用它。在调用的函数中,首先要获得DLL的句柄,有如下语句:
HINSTANCE     dllinstance;
dllinstance=::LoadLibrary(strDllUrl);
if(dllinstance==NULL) AfxMessageBox("can't open dll file");
其中strDllUrl是mydll.dll路径的字符串,这样程序才能找到它。::LoadLibrary获得参数标识的DLL文件的句柄。
获得句柄后,下面要获得函数地址以便执行它。有如下语句:
FARPROC  proc;
proc=GetProcAddress(dllinstance,"go");
if(proc==NULL) AfxMessageBox("can't find function");
else proc();
FARPROC是一个远程过程指针,通过GetProcAddress获得函数的地址。它的两个参数就是dll文件句柄和函数的名字了。
然后FARPROC就可以和go一样的使用了,它就是go ,go 就是它。
而对于带参数的DLL中的函数,调用方法有所不同。因为对函数的调用是通过对它地址的引用进行的,这样,传入参数对不对,在函数调用程序的编译和联接过程中,无法知道其正确性。因此,要在调用程序中对DLL中带参数的函数做个声明,如mydll中的went,我们要做个声明如下:
typedef void (FAR __cdecl *MYWENT)(CString);
然后以类型MYWENT声明变量既可调用,如下:
MYWENT myproc;
myproc =(MYWENT)GetProcAddress(dllinstance,"go");
if(myproc ==NULL) AfxMessageBox("can't find function");
else myproc (“o-----yeah---------”);
注意声明的时候呢,由于DLL中WENT的定义为C语言调用规范,因此MYWENT前一定要用__cdecl,而VC中常用的__stdcall是PASCAL调用规范,不可以的。一定要注意。
添加评论
单击隐藏此项的评论。
JAVA调用DLL(JNI)
最近在公司里做了一个手机的项目,需要JAVA程序在发送短信的时候和第三方的短信服务器连接。短信接口是用C++写的。琢磨了三天,大致搞懂了JNI的主体部分。先将心得整理,希望各位朋友少走弯路。
首先引用一篇文章,介绍一个简单的JNI的调用的过程。
JAVA以其跨平台的特性深受人们喜爱,而又正由于它的跨平台的目的,使得它和本地机器的各种内部联系变得很少,约束了它的功能。解决JAVA对本地操作的一种方法就是JNI。
JAVA通过JNI调用本地方法,而本地方法是以库文件的形式存放的(在WINDOWS平台上是DLL文件形式,在UNIX机器上是SO文件形式)。通过调用本地的库文件的内部方法,使JAVA可以实现和本地机器的紧密联系,调用系统级的各接口方法。
简单介绍及应用如下:
一、JAVA中所需要做的工作
在JAVA程序中,首先需要在类中声明所调用的库名称,如下:
static {
System.loadLibrary(“goodluck”);
}
在这里,库的扩展名字可以不用写出来,究竟是DLL还是SO,由系统自己判断。
还需要对将要调用的方法做本地声明,关键字为native。并且只需要声明,而不需要具 体实现。如下:
public native static void set(int i);
public native static int get();
然后编译该JAVA程序文件,生成CLASS,再用JAVAH命令,JNI就会生成C/C++的头文件。
例如程序testdll.java,内容为:
public class testdll
{
static
{
System.loadLibrary("goodluck");
}
public native static int get();
public native static void set(int i);
public static void main(String[] args)
{
testdll test = new testdll();
test.set(10);
System.out.println(test.get());
}
}
用javac testdll.java编译它,会生成testdll.class。
再用javah testdll,则会在当前目录下生成testdll.h文件,这个文件需要被C/C++程序调用来生成所需的库文件。
二、C/C++中所需要做的工作
对于已生成的.h头文件,C/C++所需要做的,就是把它的各个方法具体的实现。然后编译连接成库文件即可。再把库文件拷贝到JAVA程序的路径下面,就可以用JAVA调用C/C++所实现的功能了。
接上例子。我们先看一下testdll.h文件的内容:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class testdll */
#ifndef _Included_testdll
#define _Included_testdll
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: testdll
* Method: get
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_testdll_get (JNIEnv *, jclass);
/*
* Class: testdll
* Method: set
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_testdll_set (JNIEnv *, jclass, jint);
#ifdef __cplusplus
}
#endif
#endif
在具体实现的时候,我们只关心两个函数原型
JNIEXPORT jint JNICALL Java_testdll_get (JNIEnv *, jclass); 和
JNIEXPORT void JNICALL Java_testdll_set (JNIEnv *, jclass, jint);
这里JNIEXPORT和JNICALL都是JNI的关键字,表示此函数是要被JNI调用的。而jint是以JNI为中介使JAVA的int类型与本地的int沟通的一种类型,我们可以视而不见,就当做int使用。函数的名称是JAVA_再加上java程序的package路径再加函数名组成的。参数中,我们也只需要关心在JAVA程序中存在的参数,至于JNIEnv*和jclass我们一般没有必要去碰它。
好,下面我们用testdll.cpp文件具体实现这两个函数:
#include "testdll.h"
int i = 0;
JNIEXPORT jint JNICALL Java_testdll_get (JNIEnv *, jclass)
{
return i;
}
JNIEXPORT void JNICALL Java_testdll_set (JNIEnv *, jclass, jint j)
{
i = j;
}
编译连接成库文件,本例是在WINDOWS下做的,生成的是DLL文件。并且名称要与JAVA中需要调用的一致,这里就是goodluck.dll 。把goodluck.dll拷贝到testdll.class的目录下,java testdll运行它,就可以观察到结果了。
我的项目比较复杂,需要调用动态链接库,这样在JNI传送参数到C程序时,需要对参数进行处理转换。才可以被C程序识别。
大体程序如下:
public class SendSMS {
static
{
System.out.println(System.getProperty("java.library.path"));
System.loadLibrary("sms");
}
public native static int SmsInit();
public native static int SmsSend(byte[] mobileNo, byte[] smContent);
}
在这里要注意的是,path里一定要包含类库的路径,否则在程序运行时会抛出异常:
java.lang.UnsatisfiedLinkError: no sms in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1491)
at java.lang.Runtime.loadLibrary0(Runtime.java:788)
at java.lang.System.loadLibrary(System.java:834)
at com.mobilesoft.sms.mobilesoftinfo.SendSMS.(SendSMS.java:14)
at com.mobilesoft.sms.mobilesoftinfo.test.main(test.java:18)
Exception in thread "main"
指引的路径应该到.dll文件的上一级,如果指到.dll,则会报:
java.lang.UnsatisfiedLinkError: C:/sms.dll: Can't find dependent libraries
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1560)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1485)
at java.lang.Runtime.loadLibrary0(Runtime.java:788)
at java.lang.System.loadLibrary(System.java:834)
at com.mobilesoft.sms.mobilesoftinfo.SendSMS.(SendSMS.java:14)
at com.mobilesoft.sms.mobilesoftinfo.test.main(test.java:18)
Exception in thread "main"
通过编译,生成com_mobilesoft_sms_mobilesoftinfo_SendSMS.h头文件。(建议使用Jbuilder进行编译,操作比较简单!)这个头文件就是Java和C之间的纽带。要特别注意的是方法中传递的参数jbyteArray,这在接下来的过程中会重点介绍。
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class com_mobilesoft_sms_mobilesoftinfo_SendSMS */
#ifndef _Included_com_mobilesoft_sms_mobilesoftinfo_SendSMS
#define _Included_com_mobilesoft_sms_mobilesoftinfo_SendSMS
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_mobilesoft_sms_mobilesoftinfo_SendSMS
* Method: SmsInit
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_mobilesoft_sms_mobilesoftinfo_SendSMS_SmsInit
(JNIEnv *, jclass);
/*
* Class: com_mobilesoft_sms_mobilesoftinfo_SendSMS
* Method: SmsSend
* Signature: ([B[B)I
*/
JNIEXPORT jint JNICALL Java_com_mobilesoft_sms_mobilesoftinfo_SendSMS_SmsSend
(JNIEnv *, jclass, jbyteArray, jbyteArray);
#ifdef __cplusplus
}
#endif
#endif
对于我要调用的C程序的动态链接库,C程序也要提供一个头文件,sms.h。这个文件将要调用的方法罗列了出来。
/*
* SMS API
* Author: yippit
* Date: 2004.6.8
*/
#ifndef MCS_SMS_H
#define MCS_SMS_H
#define DLLEXPORT __declspec(dllexport)
/*sms storage*/
#define SMS_SIM 0
#define SMS_MT 1
/*sms states*/
#define SMS_UNREAD 0
#define SMS_READ 1
/*sms type*/
#define SMS_NOPARSE -1
#define SMS_NORMAL 0
#define SMS_FLASH 1
#define SMS_MMSNOTI 2
typedef struct tagSmsEntry {
int index; /*index, start from 1*/
int status; /*read, unread*/
int type; /*-1-can't parser 0-normal, 1-flash, 2-mms*/
int storage; /*SMS_SIM, SMS_MT*/
char date[24];
char number[32];
char text[144];
} SmsEntry;
DLLEXPORT int SmsInit(void);
DLLEXPORT int SmsSend(char *phonenum, char *content);
DLLEXPORT int SmsSetSCA(char *sca);
DLLEXPORT int SmsGetSCA(char *sca);
DLLEXPORT int SmsSetInd(int ind);
DLLEXPORT int SmsGetInd(void);
DLLEXPORT int SmsGetInfo(int storage, int *max, int *used);
DLLEXPORT int SmsSaveFlash(int flag);
DLLEXPORT int SmsRead(SmsEntry *entry, int storage, int index);
DLLEXPORT int SmsDelete(int storage, int index);
DLLEXPORT int SmsModifyStatus(int storage, int index); /*unread -> read*/
#endif
在有了这两个头文件之后,就可以进行C程序的编写了。也就是实现对JNI调用的两个方法。在网上的资料中,由于调用的方法实现的都比较简单,(大多是打印字符串等)所以避开了JNI中最麻烦的部分,也是最关键的部分,参数的传递。由于Java和C的编码是不同的,所以传递的参数是要进行再处理,否则C程序是会对参数在编译过程中提出警告,例如;warning C4024: 'SmsSend' : different types for formal and actual parameter 2等。
Sms.c的程序如下:
#include "sms.h"
#include "com_mobilesoft_sms_mobilesoftinfo_SendSMS.h"
JNIEXPORT jint JNICALL Java_com_mobilesoft_sms_mobilesoftinfo_SendSMS_SmsInit(JNIEnv * env, jclass jobject)
{
return SmsInit();
}
JNIEXPORT jint JNICALL Java_com_mobilesoft_sms_mobilesoftinfo_SendSMS_SmsSend(JNIEnv * env, jclass jobject, jbyteArray mobileno, jbyteArray smscontent)
{
char * pSmscontent ;
//jsize theArrayLengthJ = (*env)->GetArrayLength(env,mobileno);
jbyte * arrayBody = (*env)->GetByteArrayElements(env,mobileno,0);
char * pMobileNo = (char *)arrayBody;
printf("[%s]/n ", pMobileNo);
//jsize size = (*env)->GetArrayLength(env,smscontent);
arrayBody = (*env)->GetByteArrayElements(env,smscontent,0);
pSmscontent = (char *)arrayBody;
printf("
添加评论
单击隐藏此项的评论。
DirectX Sound
我感觉声音的播放比较简单。我们从播放声音开始。为什么我这么觉得?我也不知道。
这里是展示最最最最最简单的DirectX播放声音的例子,我尽量省略了无关的代码。最后的代码只有19行,够简单了吧?
准备工作:
1.安装了DirectX SDK(有9个DLL文件)。这里我们只用到MicroSoft.DirectX.dll 和 Microsoft.Directx.DirectSound.dll
2.一个WAV文件。(这样的文件比较好找,在QQ的目录里就不少啊。这里就不多说了。)名字叫SND.WAV,放在最后目标程序的同个目录下面

开始写程序啦。随便用个UltraEdit就好了。
1.引入DirectX 的DLL文件的名字空间:
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
2.建立设备。在我们导入的Microsoft.DirectX.DirectSound空间中,有个Device的类。这个是表示系统中的声音设备。
Device dv=new Device();
3.设置CooperativeLevel。因为windows是多任务的系统,设备不是独占的,所以在使用设备前要为这个设备设置CooperativeLevel。调用Device的SetCooperativeLevel方法:其中,第一个参数是一个Control,第二个参数是个枚举类型。
在这个程序中,Control我随便弄了个参数塞进去(很汗吧!)。如果在windows程序中,可以用this代替。第二个参数就是优先级别,这里表示优先播放。
dv.SetCooperativeLevel((new UF()),CooperativeLevel.Priority);
4.开辟缓冲区。对于上面的声音设备,他有个自己的缓冲区,叫主缓冲区。系统中,一个设备有唯一的主缓冲区。由于windows是多任务(又是这个!),所以可以有几个程序同时利用一个设备播放声音,所以每个程序都自己开辟一个二级缓冲区,放自己的声音。
系统根据各个程序的优先级别,按照相应的顺序分别去各个二级缓冲区中读取内容到主缓冲区中播放。这里,我们为SND.WAV开辟一个缓冲区。
其中,第一个参数表示文件名(傻瓜都看出来了!),第二个就是需要使用的设备。
SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);
5.接下来就可以播放啦。第一个参数表示优先级别,0是最低的。第2个参数是播放方式,这里是循环播放。
buf.Play(0,BufferPlayFlags.Looping);
6.由于命令行程序没有消息循环,执行完代码就退出了,所以,我们需要暂停程序。
Console.Read();
7.关键的部分已经完了,这里只是交代一下刚才的那个倒霉的new UF() 是什么东西。这个完全是为了应付SetCooperativeLevel的参数要求。我不知道这样做有什么附作用(各位如果因此把声卡烧了…………^_^|||)
class UF:Form{}
8.代码写完啦~~~。下面可以编译了,这里编译比较复杂点。
csc /r:directX/MicroSoft.DirectX.dll;directX/Microsoft.Directx.DirectSound.dll dxsnd.cs
这里,我把2个DLL文件放在当前目录的directx目录下(这个是我自己建的,你只需要指出这2个文件的位置就可以了。)
顺便把我的目录结构说明一下:
|
|--dxsnd.cs
|--snd.wav
|--
|
|--MicroSoft.DirectX.dll
|--Microsoft.Directx.dll
 
下面是完整代码:
//dxsnd.cs
using System;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
using System.Windows.Forms;
namespace test1
{
class test
{
public static void Main(string [] args)
{
Device dv=new Device();
dv.SetCooperativeLevel((new UF()),CooperativeLevel.Priority);
SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);
buf.Play(0,BufferPlayFlags.Looping);
Console.ReadLine();
}
class UF:Form{}
}
}
添加评论
单击隐藏此项的评论。
动态编译执行c#代码
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.ICodeCompiler comp = provider.CreateCompiler();
            System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll")  ;
            cp.ReferencedAssemblies.Add("system.data.dll")  ;
            cp.ReferencedAssemblies.Add("system.xml.dll")  ;
            cp.GenerateExecutable  =  false  ;
            cp.GenerateInMemory  =  true  ;
            string code = @"using System; 
                            using System.Data;   
                            using System.Xml;      
                            public  class Judgement
                            {        
                                 public  object  GetJude()
                                 {   
                                      return  ("  +  expression  +  @");   
                                 }   
                            }" ;
            System.CodeDom.Compiler.CompilerResults cr = comp.CompileAssemblyFromSource(cp,code);
            System.Diagnostics.Debug.Write(code);
            if(cr.Errors.HasErrors)
            {
                System.Text.StringBuilder errorMsg = new System.Text.StringBuilder();
              
                foreach(System.CodeDom.Compiler.CompilerError err in cr.Errors)
                {
                    errorMsg.Append(err.ErrorText );
                }
                System.Diagnostics.Debug.WriteLine(errorMsg.ToString());
              
                throw new System.Exception("编译错误:  "  +  errorMsg.ToString());
                //return false;
            }
            else
            {
                System.Reflection.Assembly  tmp = cr.CompiledAssembly;
                object _Compiled  =  tmp.CreateInstance("Judgement");
                System.Reflection.MethodInfo mi = _Compiled.GetType().GetMethod("GetJude");
               
                return mi.Invoke(_Compiled,null);
            }
添加评论
单击隐藏此项的评论。
4月17日
VS2005里面如何把.NET2.0打包进安装程序
在 Setup Project Property 里 Prerequisites...
1. 顶上 Create setup program to install prerequisite components打上勾
2. 中间列表 .Net Framework 2.0打上勾 (Windows Install 3.1也是)
3. 下面 Download prerequisites from the same location as my application也打上勾
添加评论
单击隐藏此项的评论。
检索文件版本信息

开发人员和编译人员可以将版本信息嵌入到可执行文件、DLL 文件和驱动程序文件中。您可能需要检索部分或全部版本信息以用作应用程序的一部分,在 Visual Basic 6.0 中执行此操作需要大量的 API 调用。您需要调用 GetVersionInfoSize、VerQueryValue 和 GetFileVersionInfo Win32 API 函数,在 Visual Basic 中使用上述任何函数都不容易。

这种情况再一次显示出 .NET 框架的强大:使用 FileVersionInfo 对象使得这些工作变得非常简单。您只需调用 FileVersionInfo 对象的共享 GetVersionInfo 方法,传递一个文件名,一切问题就都迎刃而解了。示例窗体使用了以下代码:

Dim fvi As FileVersionInfo = _
 FileVersionInfo.GetVersionInfo(strFile)

完成以上操作之后,检索 FileVersionInfo 对象的属性就是一件非常简单的事情了。示例窗体使用下面所示的一小段程序,将每个属性名称和值都添加到窗体的 ListView 控件中:

Private Sub AddItem( _
ByVal strProperty As String, _
ByVal strValue As String)
    With lvwInfo.Items.Add(strProperty)
        .SubItems.Add(strValue)
    End With
End Sub

真正起作用的是代码,而代码只需反复调用 AddItem,每个属性调用一次即可:

AddItem("Comments", fvi.Comments)
AddItem("CompanyName", fvi.CompanyName)
AddItem("Language", fvi.Language)
' 此处删除了一些行...
AddItem("Product", fvi.ProductName)
AddItem("ProductPrivatePart", _
 fvi.ProductPrivatePart.ToString())
AddItem("ProductVersion", fvi.ProductVersion)
AddItem("SpecialBuild", fvi.SpecialBuild)
添加评论
单击隐藏此项的评论。
打开与保存对话框
    Dim ofd As OpenFileDialog = New OpenFileDialog()
    ofd.Filter = _
        "Executable files (*.exe;*.dll;*.ocx)|" & _
        "*.exe;*.dll;*.ocx|" & _
        "Drivers (*.sys;*.drv;*.fnt)|" & _
        "*.sys;*.drv;*.fnt|" & _
        "All files (*.*)|*.*"
    ofd.FilterIndex = 1
    ofd.ShowReadOnly = False
    ofd.RestoreDirectory = True
    If ofd.ShowDialog() = DialogResult.OK Then
        If ofd.FileName.Length > 0 Then
            ' 显示文件版本信息。
            DisplayFileInfo(ofd.FileName)
        End If
    End If
添加评论
单击隐藏此项的评论。
3月1日
将程序加载到内存中运行
private void button1_Click(object sender, System.EventArgs e)
{
AppDomainSetup ads = new AppDomainSetup();
ads.ShadowCopyFiles = "true";
AppDomain.CurrentDomain.SetShadowCopyFiles();
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain newDomain = AppDomain.CreateDomain("newDomain", adevidence, ads);
newDomain.SetShadowCopyFiles();
byte[] rawAssembly = loadFile("ClassLibrary2.dll");
Assembly asm = newDomain.Load(rawAssembly, null);
object obj = asm.CreateInstance("ClassLibrary2.Form1");
(obj as Form).ShowDialog();
obj = null;
asm = null;
AppDomain.Unload(newDomain);
newDomain = null;
}
private byte[] loadFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open);
byte[] buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
fs = null;
return buffer;
}
添加评论
单击隐藏此项的评论。
2月26日
如何实现让一个.exe文件在本机上只能运行一次
在.net中,有个Mutex类就是负责实现此功能的类,Mutex类是同步基元,它只向一个线程授予对共享资源的独占访问权。只要在加载的那个窗体里面把Main()方法稍微改一下就行了。 static void Main() { bool bExist; Mutex MyMutex=new Mutex(true,"OnlyRunOncetime",out bExist); if(bExist) { Application.Run(new Form1()); MyMutex.ReleaseMutex(); } else { MessageBox.Show("程序已经运行!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information); } }
添加评论
单击隐藏此项的评论。
2月19日
屏闭NT/2000/XP/2003系统Ctrl+Alt+Del的完美解决方案
library  SASWinHook;  
 
{  
   SASWinHook  
   copyrights  by  Liu  Yang  LYSoft  http://lysoft.7u7.net  2006.1.1  
 
   usage:  only  need  to  inject  this  dll  to  WinLogon.exe  
}  
 
uses  Windows,  Messages;  
 
{$R  *.res}  
 
var  
   FHandle:  THandle;  
   OldAppProc:  Pointer;  
 
function  HookProc(hHandle:  THandle;  uMsg:  Cardinal;  
   wParam,  lParam:  Integer):  LRESULT;  stdcall;  
var  K,  C:  Word;    //  wndproc  
begin  
   if  uMsg  =  WM_HOTKEY  then  
         begin  
               K  :=  HIWORD(lParam);  
               C  :=  LOWORD(lParam);  
               //  press  Ctrl  +  Alt  +  Del  
               if  (C  and  VK_CONTROL<>0)  and  (C  and  VK_MENU  <>0)  and  (  K  =  VK_DELETE)  
                     then  Exit;      //  disable  Ctrl  +  Alt  +  Del  
         end;  
   Result  :=  CallWindowProc(OldAppProc,  hHandle,  
       uMsg,  wParam,  lParam);  
end;  
 
procedure  EntryPointProc(Reason:  Integer);  
begin  
   case  reason  of  
       DLL_PROCESS_ATTACH:  
           begin    //  hook  SAS  window  wndproc  
               FHandle  :=  FindWindow('SAS  window  class',  'SAS  window');  
               if  not  IsWindow(FHandle)  then  Exit;    //  is  window  found?  
               //  save  old  wndproc  
               OldAppProc  :=  Pointer(GetWindowLong(FHandle,  GWL_WNDPROC));  
               //  set  new  wndproc  
               SetWindowLong(FHandle,  GWL_WNDPROC,  Cardinal(@HookProc));  
           end;  
       DLL_PROCESS_DETACH:  
           begin  
               if  FHandle  >  0  then  
                     begin    //  unhook  
                         if  Assigned(OldAppProc)  then  
                               SetWindowLong(FHandle,  GWL_WNDPROC,  LongInt(OldAppProc));  
                         OldAppProc  :=  nil;  
                     end;  
           end;  
       end;  
end;  
 
begin  
   OldAppProc  :=  nil;  
   FHandle  :=  0;  
   DllProc  :=  @EntryPointProc;  
   EntryPointProc(DLL_PROCESS_ATTACH);  
end.  
添加评论
单击隐藏此项的评论。
2月18日
StructureToPtr
Imports   System.Runtime.InteropServices

...
Class   ...

<StructLayout(LayoutKind.Sequential)>   _
Private   Class   DEVNAMES
                Dim   wDriverOffset   As   Short
                Dim   wDeviceOffset   As   Short
                Dim   wOutputOffset   As   Short
                Dim   wDefault   As   Short
End   Class


      Sub   ...
            Dim   hDev   As   IntPtr
            Dim   devnames   as   New   DEVNAMES()
            devnames.XXXX   =   XXXX   '设置  

            hDev   =   Marshal.AllocHGlobal(Marshal.SizeOf(devnames))
            Marshal.StructureToPtr(devnames,   hDev,   False)
            PageSettings.SetHdevmode(hDev)
            Marshal.FreeHGlobal(hDev)
      End   Sub

End   Class
------------------------------------------------------------------------------------------------------------------------
Imports   System.Drawing.Printing
Imports   System.Runtime.InteropServices

Public   Class   Class1
        Private   Declare   Function   GlobalFree   Lib   "kernel32"   Alias   "GlobalFree"   (ByVal   hMem   As   IntPtr)   As   Integer

        Private   ps   As   PageSettings   =   New   PageSettings()
        Private   pr   As   PrinterSettings   =   New   PrinterSettings()

        Public   mDevMode   As   New   DEVMODE()
 
        Public   Sub   PrintOut()
                Dim   ip   As   IntPtr   =   pr.GetHdevmode
                Marshal.PtrToStructure(ip,   mDevMode)
                GlobalFree(ip)
        End   Sub

End   Class

<StructLayout(LayoutKind.Sequential)>   _
Public   Class   DEVMODE
        <VBFixedString(32),   System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr,   SizeConst:=32)>   Dim   dmDeviceName   As   String
        Dim   dmSpecVersion   As   Short
        Dim   dmDriverVersion   As   Short
        Dim   dmSize   As   Short
        Dim   dmDriverExtra   As   Short
        Dim   dmFields   As   Integer
        Dim   dmOrientation   As   Short
        Dim   dmPaperSize   As   Short
        Dim   dmPaperLength   As   Short
        Dim   dmPaperWidth   As   Short
        Dim   dmScale   As   Short
        Dim   dmCopies   As   Short
        Dim   dmDefaultSource   As   Short
        Dim   dmPrintQuality   As   Short
        Dim   dmColor   As   Short
        Dim   dmDuplex   As   Short
        Dim   dmYResolution   As   Short
        Dim   dmTTOption   As   Short
        Dim   dmCollate   As   Short
        <VBFixedString(32),   System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr,   SizeConst:=32)>   Dim   dmFormName   As   String
        Dim   dmUnusedPadding   As   Short
        Dim   dmBitsPerPel   As   Integer
        Dim   dmPelsWidth   As   Integer
        Dim   dmPelsHeight   As   Integer
        Dim   dmDisplayFlags   As   Integer
        Dim   dmDisplayFrequency   As   Integer
End   Class
添加评论
单击隐藏此项的评论。
2月17日
安装包在安装时,怎麽更改config文件?
使用VS2005制作安装包。
1.在“新建项目”对话框的左侧树状图中选择“Other Project Types”->“Setup and Deployment”节点,在右侧选择“Web Setup Project”。
 
2.在Solution Explorer中在Solution上点右键,选择“Add”->“Existing Web Site”,将存放编译好的Web网站的文件夹加入Solution中。
 
如果添加使用aspnet_compiler编译好的网站,有可能会出现下面的提示框,点击“是”就行。
 
3.再添加一个新的“Class Library”,名称“CreateDB”,用以创建数据库的操作。
 
删除默认生成的“class1.cs”,在这个项目上点右键,选择“Add”->“New Item”,在弹出的对话框中选择“Installer Class”,点击OK。
 
在类中添加如下代码:
private void ExecuteSql(string connectionString, string databaseName, string sql)
{
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
try
{
sqlCommand.Connection.Open();
sqlCommand.Connection.ChangeDatabase(databaseName);
sqlCommand.ExecuteNonQuery();
}
catch (Exception exception)
{
throw exception;
}
finally
{
sqlCommand.Connection.Close();
}
}
public override void Install(System.Collections.IDictionary stateSaver)
{
string server = this.Context.Parameters["server"];
string database = this.Context.Parameters["dbname"];
string user = this.Context.Parameters["user"];
string password = this.Context.Parameters["pwd"];
string targetDir = this.Context.Parameters["targetdir"];
try
{
string connectionString = String.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096",
server, user, password);
//create db
ExecuteSql(connectionString, "master", "CREATE DATABASE " + database);
//set user
string setUserString = "sp_addlogin 'XXXXXX', 'XXXXXX', 'XXXXXX'";
string setAccessString = "sp_grantdbaccess 'XXXXXX'";
string setRole = "sp_addrolemember 'db_owner', 'XXXXXX'";
//create new user login
try
{
ExecuteSql(connectionString, "master", setUserString);
}
catch { }
//set default database
try
{
ExecuteSql(connectionString, "XXXXXX", setAccessString);
}
catch { }
//set read role
try
{
ExecuteSql(connectionString, "XXXXXX", setRole);
}
catch { }
//create table,store produce......
Process osqlProcess = new Process();
osqlProcess.StartInfo.FileName = targetDir + "osql.exe";
osqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -S {2} -d {3} -i {4}createdb.sql",
user, password, server, database, targetDir);
osqlProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
osqlProcess.Start();
osqlProcess.WaitForExit();
osqlProcess.Close();
//add data
osqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -S {2} -d {3} -i {4}insertdata.sql",
user, password, server, database, targetDir);
osqlProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
osqlProcess.Start();
osqlProcess.WaitForExit();
osqlProcess.Close();
}
catch (Exception exception)
{
throw exception;
}
try
{
string configFile = targetDir + "/Web.config";
if (!File.Exists(configFile))
{
throw new InstallException("没有找到配置文件。");
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(configFile);
GC.Collect();
File.Delete(configFile);
GC.Collect();
foreach (XmlNode xmlNode in xmlDoc["configuration"]["connectionStrings"].ChildNodes)
{
if (xmlNode.Name == "add")
{
if (xmlNode.Attributes["name"].Value == "DBConnection")
{
xmlNode.Attributes["connectionString"].Value = String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=XXXXXX;Password=XXXXXX",
server, database);
}
if (xmlNode.Attributes["name"].Value == "UserManageServicesConnection")
{
xmlNode.Attributes["connectionString"].Value = String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=XXXXXX;Password=XXXXXX",
server, database);
}
}
}
xmlDoc.Save(configFile);
}
catch (Exception exception)
{
throw exception;
}
4.在“Web Setup Project”项目上点右键,选择“Add”->“Project Output”,选择Project“CreateDB”,选择“Primary Output”,点击OK。重复上述动作,将选择刚才添加的Web Site,选择“Content Files”,点击OK。
 
 
5.在“Web Setup Project”项目上点右键,选择“Add”->“File”,将创建数据库表、存储过程和视图的脚本createdb.sql加入。重复,将向数据表中添加基础数据的脚本insertdata.sql加入。重复,将程序osql.exe加入。
6.在“Web Setup Project”项目上点右键,选择“Add”->“Merge Module”,在弹出的对话框中选择“VC_User_CRT71_RTL_X86_---.msm”,点击OK。添加这个VC运行库是因为在一台干净的机器上测试的时候发现osql.exe这个程序需要这个库。
7.在“Web Setup Project”项目上点右键,选择“Properties”,在弹出的对话框中可以设置一些安装程序的属性。点击按钮“Prerequisites”,在弹出的对话框中选中“.NET Framework 2.0”和“Windows Installer 3.1”,选中“Download prerequisites from the same location as my application”。这样就可以把这些组件和应用程序打包在一起,安装的时候自动检测并安装了。如果需要部署的计算机如果没有打过最新的补丁的话,是没有“Windows Installer 3.1”的,如果没有这个组件,“.NET Framework 2.0”是不能安装的。
  
8.在“Web Setup Project”项目上点右键,选择“View”->“Custom Actions”,在出现的树状图的节点“Install”上点右键,选择“Add Custom Actions”。在弹出的对话框中“Look in”中选择“Web Application Folders”,在下面选择“Primary output from CreateDB (Active)”,点击OK。
 
9.在“Web Setup Project”项目上点右键,选择“View”->“User Interface”,在出现的树状图节点“Install”的子节点“Start”上点击右键,选择“Add Dialog”,在弹出的对话框中选择“TextBoxes(A)”。
 
在新添加的节点“TextBoxes (A)”上点击右键,选择“Properites Window”,依次设置Edit*Property属性为“CUSTOMTEXTA1”,“CUSTOMTEXTA2”,“CUSTOMTEXTA3”和“CUSTOMTEXTA4”。
10.在刚刚建立的“Primary output from CreateDB (Active)”节点上点右键,选择“Properties Window”,设置“CustomActionData”属性为“/dbname=[CUSTOMTEXTA1] /server=[CUSTOMTEXTA2] /user=[CUSTOMTEXTA3] /pwd=[CUSTOMTEXTA4] /targetdir="[TARGETDIR]/"”。
添加评论
单击隐藏此项的评论。
1月26日
用C#生成Excel文件的方法和Excel.dll组件生成的方法
 

一个示例:

class AppTest
 {
  private Excel.ApplicationClass _x;
  public static void Main0()
  {
   AppTest a = new AppTest();
   a._x = new Excel.ApplicationClass();
   a._x.UserControl = false;
   for (int i = 0 ;i < 4; i++)
   {
    
    a.SaveToXls("D://test//" + i + ".xls");  // 本例是在D盘下建立的test文件夹
   }
   a._x.Quit();
   System.Runtime.InteropServices.Marshal.ReleaseComObject((object) a._x);
   System.GC.Collect();
  }

  private void SaveToXls(string filename)
  {
   Excel.WorkbookClass wb = (Excel.WorkbookClass) this._x.Workbooks.Add(System.Reflection.Missing.Value);
   for(int i = 1;i <= 4; i++)
   {
    this._x.Cells[i,1]=i.ToString();
    this._x.Cells[i,2]="'bbb2";
    this._x.Cells[i,3]="'ccc3";
    this._x.Cells[i,4]="'aaa4";
   }
   
   wb.Saved = true;
   this._x.ActiveWorkbook.SaveCopyAs(filename);
  }
 }

【注:在VS.Net中运行是要添加Excel.dll组件的,Excel组件VS.Net本身是没有的,下面是生成Excel.dll的方法。】

1.要保证机器本身要安装OFFICE.

2.把[C:/Program Files/Microsoft Office/Office:默认安装路径]下的EXCEL9.OLB文件拷贝到[C:/Visual Studio.Net/SDK/v1.1/Bin:VS.Net安装路径]路径下。

3.打开Visual Studio .Net2003命令提示,运行TlbImp Excel9.olb Excel.dll ,就会在[C:/Visual Studio.Net/SDK/v1.1/Bin]下生成Excel.dll组件。

4.在项目中添加Excel.dll引用就OK了。

添加评论
单击隐藏此项的评论。
图片的版权保护(添加水印)
 

/**********************Created by Chen**************************

*如果你觉得本人的文章好,要引用请尊重著作人的劳动果实,说明

*出处以及原创作者,Thank you!!!   email:aishen944-sohu.com

*******************************************************************/

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace ImageDrawing
{
 /// <summary>
 /// 图片修改类,主要是用来保护图片版权的
 /// </summary>
 public class ImageModification
 {
  #region "member fields"
  private string modifyImagePath=null;
  private string drawedImagePath=null;
  private int rightSpace;
  private int bottoamSpace;
  private int lucencyPercent=70;
  private string outPath=null;
  #endregion
  public ImageModification()
  {
  }
  #region "propertys"
  /// <summary>
  /// 获取或设置要修改的图像路径
  /// </summary>
  public string ModifyImagePath
  {
   get{return this.modifyImagePath;}
   set{this.modifyImagePath=value;}
  }
  /// <summary>
  /// 获取或设置在画的图片路径(水印图片)
  /// </summary>
  public string DrawedImagePath
  {
   get{return this.drawedImagePath;}
   set{this.drawedImagePath=value;}
  }
  /// <summary>
  /// 获取或设置水印在修改图片中的右边距
  /// </summary>
  public int RightSpace
  {
   get{return this.rightSpace;}
   set{this.rightSpace=value;}
  }
  //获取或设置水印在修改图片中距底部的高度
  public int BottoamSpace
  {
   get{return this.bottoamSpace;}
   set{this.bottoamSpace=value;}
  }
  /// <summary>
  /// 获取或设置要绘制水印的透明度,注意是原来图片透明度的百分比
  /// </summary>
  public int LucencyPercent
  {
   get{return this.lucencyPercent;}
   set
   {
    if(value>=0&&value<=100)
     this.lucencyPercent=value;
   }
  }
  /// <summary>
  /// 获取或设置要输出图像的路径
  /// </summary>
  public string OutPath
  {
   get{return this.outPath;}
   set{this.outPath=value;}
  }
  #endregion
  #region "methods"
  /// <summary>
  /// 开始绘制水印
  /// </summary>
  public void DrawImage()
  {
   Image modifyImage=null;
   Image drawedImage=null;
   Graphics g=null;
   try
   {    
    //建立图形对象
    modifyImage=Image.FromFile(this.ModifyImagePath);
    drawedImage=Image.FromFile(this.DrawedImagePath);
    g=Graphics.FromImage(modifyImage);
    //获取要绘制图形坐标
    int x=modifyImage.Width-this.rightSpace;
    int y=modifyImage.Height-this.BottoamSpace;
    //设置颜色矩阵
    float[][] matrixItems ={
             new float[] {1, 0, 0, 0, 0},
             new float[] {0, 1, 0, 0, 0},
             new float[] {0, 0, 1, 0, 0},
             new float[] {0, 0, 0, (float)this.LucencyPercent/100f, 0},
             new float[] {0, 0, 0, 0, 1}};

    ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
    ImageAttributes imgAttr=new ImageAttributes();
    imgAttr.SetColorMatrix(colorMatrix,ColorMatrixFlag.Default,ColorAdjustType.Bitmap);
    //绘制阴影图像
    g.DrawImage(
     drawedImage,
     new Rectangle(x,y,drawedImage.Width,drawedImage.Height),
     0,0,drawedImage.Width,drawedImage.Height,
     GraphicsUnit.Pixel,imgAttr);
    //保存文件
    string[] allowImageType={".jpg",".gif",".png",".bmp",".tiff",".wmf",".ico"};
    FileInfo file=new FileInfo(this.ModifyImagePath);
    ImageFormat imageType=ImageFormat.Gif;
    switch(file.Extension.ToLower())
    {
     case ".jpg":
      imageType=ImageFormat.Jpeg;
      break;
     case ".gif":
      imageType=ImageFormat.Gif;
      break;
     case ".png":
      imageType=ImageFormat.Png;
      break;
     case ".bmp":
      imageType=ImageFormat.Bmp;
      break;
     case ".tif":
      imageType=ImageFormat.Tiff;
      break;
     case ".wmf":
      imageType=ImageFormat.Wmf;
      break;
     case ".ico":
      imageType=ImageFormat.Icon;
      break;
     default:
      break;
    }
    MemoryStream ms=new MemoryStream();
    modifyImage.Save(ms,imageType);
    byte[] imgData=ms.ToArray();
    modifyImage.Dispose();
    drawedImage.Dispose();
    g.Dispose();
    FileStream fs=null;
    if(this.OutPath==null || this.OutPath=="")
    {
     File.Delete(this.ModifyImagePath);
     fs=new FileStream(this.ModifyImagePath,FileMode.Create,FileAccess.Write);
    }
    else
    {
     fs=new FileStream(this.OutPath,FileMode.Create,FileAccess.Write);
    }
    if(fs!=null)
    {
     fs.Write(imgData,0,imgData.Length);
     fs.Close();
    }
   }
   finally
   {
    try
    {
     drawedImage.Dispose();
     modifyImage.Dispose();
     g.Dispose();
    }
    catch{;}
   }
  }
  #endregion
 }
}

添加评论
单击隐藏此项的评论。
简单的多人聊天(C#.Socket)
 

/********************************8ChatServer:*************************************************/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace Chat_Server
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  static int listenport=6666;
  Socket clientsocket;
  private System.Windows.Forms.ListBox lbClients;
  ArrayList clients;
  private System.Windows.Forms.Button button1;
  Thread clientservice;
  private System.Windows.Forms.Label label1;
  Thread threadListen;

  public Form1()
  {
   
   InitializeComponent();

  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    
    if(clientservice != null)
    {
     clientservice.Abort();
    }
    if(threadListen != null)
    {
     try
     {
      threadListen.Abort();
     }
     catch(Exception ex)
     {
      threadListen = null;
     }
    }    

    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
   
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.lbClients = new System.Windows.Forms.ListBox();
   this.button1 = new System.Windows.Forms.Button();
   this.label1 = new System.Windows.Forms.Label();
   this.SuspendLayout();
   //
   // lbClients
   //
   this.lbClients.ItemHeight = 12;
   this.lbClients.Location = new System.Drawing.Point(16, 24);
   this.lbClients.Name = "lbClients";
   this.lbClients.Size = new System.Drawing.Size(184, 268);
   this.lbClients.TabIndex = 0;
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(272, 56);
   this.button1.Name = "button1";
   this.button1.TabIndex = 1;
   this.button1.Text = "button1";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // label1
   //
   this.label1.Location = new System.Drawing.Point(240, 136);
   this.label1.Name = "label1";
   this.label1.Size = new System.Drawing.Size(120, 32);
   this.label1.TabIndex = 2;
   this.label1.Text = "label1";
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(368, 309);
   this.Controls.Add(this.label1);
   this.Controls.Add(this.button1);
   this.Controls.Add(this.lbClients);
   this.Name = "Form1";
   this.Text = "Form1";
   this.Load += new System.EventHandler(this.Form1_Load);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void StartListening()
  {
    TcpListener listener = new TcpListener(listenport);
    listener.Start();
   label1.Text = "listening....";
   while (true)
   {
    try
    {
    
     Socket s = listener.AcceptSocket();
     clientsocket = s;
     clientservice = new Thread(new ThreadStart(ServiceClient));
     clientservice.Start();
    }
    catch(Exception ex)
    {
     MessageBox.Show("listening Error: "+ex.Message);
    }
   }   
  }
  private void ServiceClient()
  {
   Socket client = clientsocket;
   bool keepalive = true;


   while (keepalive)
   {
    Byte[] buffer = new Byte[1024];
    int bufLen = 0;
    try
    {
     bufLen = client.Available ;
     
     client.Receive(buffer,0,bufLen,SocketFlags.None);
     if(bufLen==0)
      continue;    
    }
    catch(Exception ex)
    {
     MessageBox.Show("Receive Error:"+ex.Message);
     return;
    }
    
    string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0,bufLen);

    string[] tokens = clientcommand.Split(new Char[]{'|'});
    Console.WriteLine(clientcommand);

    if (tokens[0] == "CONN")
    {
     for(int n=0; n<clients.Count;n++)
     {
      Client cl = (Client)clients[n];
      SendToClient(cl, "JOIN|" + tokens[1]);
     }
     EndPoint ep = client.RemoteEndPoint;
     Client c = new Client(tokens[1], ep, clientservice, client);
     
     string message = "LIST|" + GetChatterList() +"/r/n";
     SendToClient(c, message);

     clients.Add(c);


     lbClients.Items.Add(c);


    }
    if (tokens[0] == "CHAT")
    {
     for(int n=0; n<clients.Count;n++)
     {
      Client cl = (Client)clients[n];
      SendToClient(cl, clientcommand);
     }
    }
    if (tokens[0] == "PRIV")
    {
     string destclient = tokens[3];
     for(int n=0; n<clients.Count;n++)
     {
      Client cl = (Client)clients[n];
      if(cl.Name.CompareTo(tokens[3]) == 0)
       SendToClient(cl, clientcommand);
      if(cl.Name.CompareTo(tokens[1]) == 0)
       SendToClient(cl, clientcommand);
     }
    }
    if (tokens[0] == "GONE")
    {
     int remove = 0;
     bool found = false;
     int c = clients.Count;
     for(int n=0; n<clients.Count;n++)
     {
      Client cl = (Client)clients[n];
      SendToClient(cl, clientcommand);
      if(cl.Name.CompareTo(tokens[1]) == 0)
      {
       remove = n;
       found = true;
       lbClients.Items.Remove(cl);
      }
     }
     if(found)
      clients.RemoveAt(remove);
     client.Close();
     keepalive = false;
    }
   }
  }

  private string GetChatterList()
  {
   string result = "";

   for(int i=0;i<clients.Count;i++)
   {
    result += ((Client)clients[i]).Name+"|";
   }
   return result;

  }

  private void SendToClient(Client cl,string clientCommand)
  {
   Byte[] message = System.Text.Encoding.ASCII.GetBytes(clientCommand);
   Socket s = cl.Sock;
   if(s.Connected)
   {
    s.Send(message,message.Length,0);
   }
  }

  private void Form1_Load(object sender, System.EventArgs e)
  {
   clients = new ArrayList();
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
   threadListen = new Thread(new ThreadStart(StartListening));
   threadListen.Start();  
  }
 }
}


/***************************** client类 ********************/

/************************** 放于 chatServer 项目中 *********/

using System;
using System.Threading;

namespace Chat_Server
{
 using System.Net.Sockets;
 using System.Net;

 ///
 /// Client 的摘要说明。
 ///
 public class Client
 {
  private Thread clthread;
  private EndPoint endpoint;
  private string name;
  private Socket sock;

  public Client(string _name, EndPoint _endpoint, Thread _thread, Socket _sock)
  {
   // TODO: 在此处添加构造函数逻辑
   clthread = _thread;
   endpoint = _endpoint;
   name = _name;
   sock = _sock;
  }

  public override string ToString()
  {
   return endpoint.ToString()+ " : " + name;
  }

  public Thread CLThread
  {
   get{return clthread;}
   set{clthread = value;}
  }

  public EndPoint Host
  {
   get{return endpoint;}
   set{endpoint = value;}
  }

  public string Name
  {
   get{return name;}
   set{name = value;}
  }

  public Socket Sock
  {
   get{return sock;}
   set{sock = value;}
  }
 }
}

/***************************** chatClient ************************************/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Chat_Client
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.CheckBox checkBox1;
  private System.Windows.Forms.StatusBar statusBar1;

  NetworkStream ns;
  StreamReader sr;
  TcpClient clientsocket;
  bool connected;
  Thread receive;
  string serveraddress = "219.228.231.85";
  int serverport = 6666;

  private System.Windows.Forms.RichTextBox rtbChatIn;
  private System.Windows.Forms.ListBox lbChatters;
  private System.Windows.Forms.TextBox ChatOut;
  private System.Windows.Forms.Button btnDisconnect;
  private System.Windows.Forms.Button btnSend;
  private System.Windows.Forms.TextBox clientName;

  string clientname;
  private System.Windows.Forms.Button btnConnect;

  private System.ComponentModel.Container components = null;

  public Form1()
  {
   
   InitializeComponent();

  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if(receive != null)
    {
     QuitChat();
    }
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.lbChatters = new System.Windows.Forms.ListBox();
   this.rtbChatIn = new System.Windows.Forms.RichTextBox();
   this.checkBox1 = new System.Windows.Forms.CheckBox();
   this.ChatOut = new System.Windows.Forms.TextBox();
   this.btnSend = new System.Windows.Forms.Button();
   this.statusBar1 = new System.Windows.Forms.StatusBar();
   this.btnDisconnect = new System.Windows.Forms.Button();
   this.clientName = new System.Windows.Forms.TextBox();
   this.btnConnect = new System.Windows.Forms.Button();
   this.SuspendLayout();
   //
   // lbChatters
   //
   this.lbChatters.ItemHeight = 12;
   this.lbChatters.Location = new System.Drawing.Point(32, 40);
   this.lbChatters.Name = "lbChatters";
   this.lbChatters.Size = new System.Drawing.Size(112, 172);
   this.lbChatters.TabIndex = 0;
   //
   // rtbChatIn
   //
   this.rtbChatIn.Location = new System.Drawing.Point(160, 40);
   this.rtbChatIn.Name = "rtbChatIn";
   this.rtbChatIn.Size = new System.Drawing.Size(208, 176);
   this.rtbChatIn.TabIndex = 2;
   this.rtbChatIn.Text = "";
   //
   // checkBox1
   //
   this.checkBox1.Location = new System.Drawing.Point(16, 248);
   this.checkBox1.Name = "checkBox1";
   this.checkBox1.TabIndex = 3;
   this.checkBox1.Text = "checkBox1";
   //
   // ChatOut
   //
   this.ChatOut.Location = new System.Drawing.Point(136, 248);
   this.ChatOut.Name = "ChatOut";
   this.ChatOut.Size = new System.Drawing.Size(136, 21);
   this.ChatOut.TabIndex = 4;
   this.ChatOut.Text = "message";
   //
   // btnSend
   //
   this.btnSend.Location = new System.Drawing.Point(336, 248);
   this.btnSend.Name = "btnSend";
   this.btnSend.TabIndex = 5;
   this.btnSend.Text = "send";
   this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
   //
   // statusBar1
   //
   this.statusBar1.Location = new System.Drawing.Point(0, 287);
   this.statusBar1.Name = "statusBar1";
   this.statusBar1.Size = new System.Drawing.Size(464, 22);
   this.statusBar1.TabIndex = 6;
   this.statusBar1.Text = "statusBar1";
   //
   // btnDisconnect
   //
   this.btnDisconnect.Enabled = false;
   this.btnDisconnect.Location = new System.Drawing.Point(392, 112);
   this.btnDisconnect.Name = "btnDisconnect";
   this.btnDisconnect.Size = new System.Drawing.Size(64, 32);
   this.btnDisconnect.TabIndex = 7;
   this.btnDisconnect.Text = "断开";
   this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
   //
   // clientName
   //
   this.clientName.Location = new System.Drawing.Point(96, 8);
   this.clientName.Name = "clientName";
   this.clientName.TabIndex = 8;
   this.clientName.Text = "name";
   //
   // btnConnect
   //
   this.btnConnect.Location = new System.Drawing.Point(392, 56);
   this.btnConnect.Name = "btnConnect";
   this.btnConnect.Size = new System.Drawing.Size(64, 32);
   this.btnConnect.TabIndex = 9;
   this.btnConnect.Text = "连接";
   this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(464, 309);
   this.Controls.Add(this.btnConnect);
   this.Controls.Add(this.clientName);
   this.Controls.Add(this.btnDisconnect);
   this.Controls.Add(this.statusBar1);
   this.Controls.Add(this.btnSend);
   this.Controls.Add(this.ChatOut);
   this.Controls.Add(this.checkBox1);
   this.Controls.Add(this.rtbChatIn);
   this.Controls.Add(this.lbChatters);
   this.Name = "Form1";
   this.Text = "Form1";
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void EstablishConnection()
  {
   statusBar1.Text = "正在连接到服务器";
   
   try
   {
    clientsocket = new TcpClient(serveraddress,serverport);
    ns = clientsocket.GetStream();
    sr = new StreamReader(ns);
    connected = true;
   
   }
   catch (Exception)
   {
    MessageBox.Show("不能连接到服务器!","错误",
     MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    statusBar1.Text = "已断开连接";
   }
  }

  private void RegisterWithServer()
  {
   lbChatters.Items.Clear();

   clientname = clientName.Text;
   try
   {
    string command = "CONN|" + clientname; //+"/r/n";
    Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
    ns.Write(outbytes,0,outbytes.Length);


    string serverresponse = sr.ReadLine();
    serverresponse.Trim();
    string[] tokens = serverresponse.Split('|');
    if(tokens[0] == "LIST")
    {
     statusBar1.Text = "已连接";
     btnDisconnect.Enabled = true;
    }
    if(tokens[1] != "")
    {
     for(int n=1; n<tokens.Length;n++)
      lbChatters.Items.Add(tokens[n].Trim(new char[]{'/r','/n'}));
    }
    this.Text = clientname + ":已连接到服务器";    

   }
   catch (Exception ex)
   {
    MessageBox.Show("注册时发生错误!"+ex.Message,"错误",
     MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    connected = false;
   }
  }

  private void ReceiveChat()
  {
   bool keepalive = true;
   while (keepalive)
   {
    try
    {
     Byte[] buffer = new Byte[1024];  // 2048???
     ns.Read(buffer,0,buffer.Length);
     string chatter = System.Text.Encoding.ASCII.GetString(buffer);
     string[] tokens = chatter.Split(new Char[]{'|'});

     if (tokens[0] == "CHAT")
     {
      rtbChatIn.AppendText(tokens[1]);
//      if(logging)
//       logwriter.WriteLine(tokens[1]);
     }
     if (tokens[0] == "PRIV")
     {
      rtbChatIn.AppendText("Private from ");
      rtbChatIn.AppendText(tokens[1].Trim() );
      rtbChatIn.AppendText(tokens[2] + "/r/n");
//      if(logging)
//      {
//       logwriter.Write("Private from ");
//       logwriter.Write(tokens[1].Trim() );
//       logwriter.WriteLine(tokens[2] + "/r/n");
//      }
     }
     if (tokens[0] == "JOIN")
     {
      rtbChatIn.AppendText(tokens[1].Trim() );
      rtbChatIn.AppendText(" has joined the Chat/r/n");
//      if(logging)
//      {
//       logwriter.WriteLine(tokens[1]+" has joined the Chat");
//      }
      string newguy = tokens[1].Trim(new char[]{'/r','/n'});
      lbChatters.Items.Add(newguy);
     }
     if (tokens[0] == "GONE")
     {
      rtbChatIn.AppendText(tokens[1].Trim() );
      rtbChatIn.AppendText(" has left the Chat/r/n");
//      if(logging)
//      {
//       logwriter.WriteLine(tokens[1]+" has left the Chat");
//      }
      lbChatters.Items.Remove(tokens[1].Trim(new char[]{'/r','/n'}));
     }
     if (tokens[0] == "QUIT")
     {
      ns.Close();
      clientsocket.Close();
      keepalive = false;
      statusBar1.Text = "服务器端已停止";
      connected= false;
      btnSend.Enabled = false;
      btnDisconnect.Enabled = false;
     }
    }
    catch(Exception){}
   }
  }

  private void QuitChat()
  {
   if(connected)
   {
    try
    {
     string command = "GONE|" + clientname;
     Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
     ns.Write(outbytes,0,outbytes.Length);
     clientsocket.Close();
    }
    catch(Exception ex)
    {
     MessageBox.Show(ex.Message);
    }
   }
//   if(logging)
//    logwriter.Close();
   if(receive != null && receive.IsAlive)
    receive.Abort();
   this.Text = "客户端";
   
   connected = false;

  }

  private void btnSend_Click(object sender, System.EventArgs e)
  {
   if(connected)
   {
    try
    {
     string command = "CHAT|" + clientname+": "+ChatOut.Text+"/r/n";
     Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
     ns.Write(outbytes,0,outbytes.Length);
     //clientsocket.Close();
    }
    catch(Exception ex)
    {
     MessageBox.Show(ex.Message);
    }
   }
  }

  private void btnConnect_Click(object sender, System.EventArgs e)
  {
   EstablishConnection();
   RegisterWithServer();
   if(connected)
   {   
    receive = new Thread(new ThreadStart(ReceiveChat));
    receive.Start();
   }
  }

  private void btnDisconnect_Click(object sender, System.EventArgs e)
  {
   QuitChat();
  }
 }
}

添加评论
单击隐藏此项的评论。
.net官方编码方法和命名规则
Visual Studio 

编码方法

编码方法合并了软件开发的许多方面。尽管它们通常对应用程序的功能没有影响,但它们对于改善对源代码的理解是有帮助的。这里考虑了所有形式的源代码,包括编程、脚本撰写、标记和查询语言。

不建议将这里定义的编码方法形成一套固定的编码标准。相反,它们旨在作为开发特定软件项目的编码标准的指南。

编码方法分为三部分:

命名

对于理解应用程序的逻辑流,命名方案是最有影响力的一种帮助。名称应该说明“什么”而不是“如何”。通过避免使用公开基础实现(它们会发生改变)的名称,可以保留简化复杂性的抽象层。例如,可以使用 GetNextStudent(),而不是 GetNextArrayElement()

命名原则是:选择正确名称时的困难可能表明需要进一步分析或定义项的目的。使名称足够长以便有一定的意义,并且足够短以避免冗长。唯一名称在编程上仅用于将各项区分开。表现力强的名称是为了帮助人们阅读;因此,提供人们可以理解的名称是有意义的。不过,请确保选择的名称符合适用语言的规则和标准。

以下几点是推荐的命名方法。

例程
  • 避免容易被主观解释的难懂的名称,如对于例程的 AnalyzeThis(),或者对于变量的 xxK8。这样的名称会导致多义性,而不仅仅是抽象。
  • 在面向对象的语言中,在类属性的名称中包含类名是多余的,如 Book.BookTitle。而是应该使用 Book.Title
  • 使用动词-名词的方法来命名对给定对象执行特定操作的例程,如 CalculateInvoiceTotal()
  • 在允许函数重载的语言中,所有重载都应该执行相似的函数。对于那些不允许函数重载的语言,建立使相似函数发生关系的命名标准。
变量
  • 只要合适,在变量名的末尾追加计算限定符(AvgSumMinMaxIndex)。
  • 在变量名中使用互补对,如 min/max、begin/end 和 open/close。
  • 鉴于大多数名称都是通过连接若干单词构造的,请使用大小写混合的格式以简化它们的阅读。另外,为了帮助区分变量和例程,请对例程名称使用 Pascal 大小写处理 (CalculateInvoiceTotal),其中每个单词的第一个字母都是大写的。对于变量名,请使用 camel 大小写处理 (documentFormatType),其中除了第一个单词外每个单词的第一个字母都是大写的。
  • 布尔变量名应该包含 Is,这意味着 Yes/No 或 True/False 值,如 fileIsFound
  • 在命名状态变量时,避免使用诸如 Flag 的术语。状态变量不同于布尔变量的地方是它可以具有两个以上的可能值。不是使用 documentFlag,而是使用更具描述性的名称,如 documentFormatType
  • 即使对于可能仅出现在几个代码行中的生存期很短的变量,仍然使用有意义的名称。仅对于短循环索引使用单字母变量名,如 ij
  • 不要使用原义数字或原义字符串,如 For i = 1 To 7。而是使用命名常数,如 For i = 1 To NUM_DAYS_IN_WEEK 以便于维护和理解。
  • 在命名表时,用单数形式表示名称。例如,使用 Employee,而不是 Employees
  • 在命名表的列时,不要重复表的名称;例如,在名为 Employee 的表中避免使用名为 EmployeeLastName 的字段。
  • 不要在列的名称中包含数据类型。如果后来有必要更改数据类型,这将减少工作量。
Microsoft SQL Server
  • 不要给存储过程加 sp 前缀,这个前缀是为标识系统存储过程保留的。
  • 不要给用户定义的函数加 fn_ 前缀,这个前缀是为标识内置函数保留的。
  • 不要给扩展存储过程加 xp_ 前缀,这个前缀是为标识系统扩展存储过程保留的。
杂项
  • 尽量减少使用缩写,而是使用以一致方式创建的缩写。缩写应该只有一个意思;同样,每个缩写词也应该只有一个缩写。例如,如果用 min 作为 minimum 的缩写,那么在所有地方都应这样做;不要将 min 又用作 minute 的缩写。
  • 在命名函数时包括返回值的说明,如 GetCurrentWindowName()
  • 与过程名一样,文件和文件夹的名称也应该精确地说明它们的用途。
  • 避免对不同的元素重用名称,如名为 ProcessSales() 的例程和名为 iProcessSales 的变量。
  • 在命名元素时避免同音异义词(如 write 和 right),以防在检查代码时发生混淆。
  • 在命名元素时,避免使用普遍拼错的词。另外,应清楚区域拼写之间存在的差异,如 color/colour 和 check/cheque。
  • 避免用印刷标记来标识数据类型,如用 $ 代表字符串或用 % 代表整数。

注释

软件文档以两种形式存在:外部的和内部的。外部文档(如规范、帮助文件和设计文档)在源代码的外部维护。内部文档由开发人员在开发时在源代码中编写的注释组成。

不考虑外部文档的可用性,由于硬拷贝文档可能会放错地方,源代码清单应该能够独立存在。外部文档应该由规范、设计文档、更改请求、错误历史记录和使用的编码标准组成。

内部软件文档的一个难题是确保注释的维护与更新与源代码同时进行。尽管正确注释源代码在运行时没有任何用途,但这对于必须维护特别复杂或麻烦的软件片段的开发人员来说却是无价的。

以下几点是推荐的注释方法:

  • 如果用 C# 进行开发,请使用 XML 文档功能。有关更多信息,请参见:XML 文档
  • 修改代码时,总是使代码周围的注释保持最新。
  • 在每个例程的开始,提供标准的注释样本以指示例程的用途、假设和限制很有帮助。注释样本应该是解释它为什么存在和可以做什么的简短介绍。
  • 避免在代码行的末尾添加注释;行尾注释使代码更难阅读。不过在批注变量声明时,行尾注释是合适的;在这种情况下,将所有行尾注释在公共制表位处对齐。
  • 避免杂乱的注释,如一整行星号。而是应该使用空白将注释同代码分开。
  • 避免在块注释的周围加上印刷框。这样看起来可能很漂亮,但是难于维护。
  • 在部署之前,移除所有临时或无关的注释,以避免在日后的维护工作中产生混乱。
  • 如果需要用注释来解释复杂的代码节,请检查此代码以确定是否应该重写它。尽一切可能不注释难以理解的代码,而应该重写它。尽管一般不应该为了使代码更简单以便于人们使用而牺牲性能,但必须保持性能和可维护性之间的平衡。
  • 在编写注释时使用完整的句子。注释应该阐明代码,而不应该增加多义性。
  • 在编写代码时就注释,因为以后很可能没有时间这样做。另外,如果有机会复查已编写的代码,在今天看来很明显的东西六周以后或许就不明显了。
  • 避免多余的或不适当的注释,如幽默的不主要的备注。
  • 使用注释来解释代码的意图。它们不应作为代码的联机翻译。
  • 注释代码中不十分明显的任何内容。
  • 为了防止问题反复出现,对错误修复和解决方法代码总是使用注释,尤其是在团队环境中。
  • 对由循环和逻辑分支组成的代码使用注释。这些是帮助源代码读者的主要方面。
  • 在整个应用程序中,使用具有一致的标点和结构的统一样式来构造注释。
  • 用空白将注释同注释分隔符分开。在没有颜色提示的情况下查看注释时,这样做会使注释很明显且容易被找到。

格式

格式化使代码的逻辑结构很明显。花时间确保源代码以一致的逻辑方式进行格式化,这对于您和必须解密源代码的其他开发人员都有帮助。

以下几点是推荐的格式化方法。

  • 建立标准的缩进大小(如四个空格),并一致地使用此标准。用规定的缩进对齐代码节。
  • 在发布源代码的硬拷贝版本时使用 monotype 字体。
  • 在括号对对齐的位置垂直对齐左括号和右括号,如:
    for (i = 0; i < 100; i++)
    {
       ...
    }

    还可以使用倾斜样式,即左括号出现在行尾,右括号出现在行首,如:

    for (i = 0; i < 100; i++){
       ...
    }

    无论选择哪种样式,请在整个源代码中使用那个样式。

  • 沿逻辑结构行缩进代码。没有缩进,代码将变得难以理解,如:
    If ... Then
    If ... Then
    ...
    Else
    End If
    Else
    ...
    End If

    缩进代码会产生出更容易阅读的代码,如:

    If ... Then
       If ... Then
       ...
       Else
       ...
       End If
    Else
    ...
    End If
  • 为注释和代码建立最大的行长度,以避免不得不滚动源代码编辑器,并且可以提供整齐的硬拷贝表示形式。
  • 在大多数运算符之前和之后使用空格,这样做时不会改变代码的意图。但是,C++ 中使用的指针表示法是一个例外。
  • 使用空白为源代码提供结构线索。这样做会创建代码“段”,有助于读者理解软件的逻辑分段。
  • 当一行被分为几行时,通过将串联运算符放在每一行的末尾而不是开头,清楚地表示没有后面的行是不完整的。
  • 只要合适,每一行上放置的语句避免超过一条。例外是 C、C++、C# 或 JScript 中的循环,如 for (i = 0; i < 100; i++)
  • 编写 HTML 时,建立标准的标记和属性格式,如所有标记都大写或所有属性都小写。另一种方法是,坚持 XHTML 规范以确保所有 HTML 文档都有效。尽管在创建 Web 页时需折中考虑文件大小,但应使用带引号的属性值和结束标记以方便维护。
  • 编写 SQL 语句时,对于关键字使用全部大写,对于数据库元素(如表、列和视图)使用大小写混合。
  • 在物理文件之间在逻辑上划分源代码。
  • 将每个主要的 SQL 子句放在不同的行上,这样更容易阅读和编辑语句,例如:
    SELECT FirstName, LastName
    FROM Customers
    WHERE State = 'WA'
  • 将大的复杂代码节分为较小的、易于理解的模块。
请参见

编码方法和编程做法 | 程序结构和代码约定 | XML 文档 | Visual Basic 命名约定

添加评论
单击隐藏此项的评论。
VB.NET多线程开发实例
VB.NET(Visual Basic.NET)是为适应Microsoft .NET框架的需要,对Visual Basic进行了重大改造后的开发工具。它比Visual Basic 6.0功能更强大,更易于使用。其中最重要的变化就是对象继承,在VB.NET中,所有可管理的类型都衍生自System.Object。作为编程工具,最重要的一个特性就是垃圾碎片的回收,它由CLR(Common Language Runtime)进行控制,并提供更好的内存管理功能。通用的类型定义可以提供更好的互操作性和协同工作能力,因此,VB.NET显得更强大、更具可靠性。
在VB.NET中,大多数CLR内建的类型都在System名字空间里已经定义了。比如:System.Object, System.Int32, 和 System.String。要注意的是:一个名字空间可能嵌在另一个名字空间内,象System.Data里就有System.Data.DataSet的类。
代表是CLR编程模型很重要的一个新概念。代表是一个特殊类型的可管理的类,当你创建一个代表的实例时,你必须提供一个带有匹配签名的方法执行的地址,一旦创建了一个代表的实例,调用方法将变的很容易。
过去,我们利用VB开发多线程的应用程序时,是一件很令人痛苦的事,经常是多线程的程序运行是会变成多错误的程序!但在VB.NET中,这种状况已经大为改观。现在,我们利用VB.NET处理多线程和利用JAVA处理多线程一样简单了。下面我们就举个例子,来看看VB.NET的多线程吧!
下面是多线程程序threadtest.vb的代码:
 
imports System
imports System.Threading
 
public class AClass
 
public sub Method1()
Dim i as integer
For i = 1 to 100
Console.Writeline("这是类AClass方法method1的内容",i)
next
end sub
 
public sub Method2()
Dim i as integer
For i = 1 to 100
Console.Writeline("这是类AClass方法method2的内容",i)
next
end sub
 
end class
 
public class ThreadTest
 
public shared sub Main()
dim obj as new aclass
dim th1,th2 as thread
 
th1=new Thread(new ThreadStart(addressof obj.method1))
th1.start
 
th2=new Thread(new ThreadStart(addressof obj.method2))
th2.start
 
dim i as integer
For i= 1 to 100
Console.WriteLine("Main方法里的内容",i)
Next
end sub
 
end class
 
现在,来让我们剖析一下上面的例子:
1.我们创建了我们自己的类AClass,并创建了两个方法:Method1和Method2。
2.这两个方法很简单,只有一个For循环,向输出设备输出一些信息。
3.我们还定义了另外一个类ThreadTest来使用上面创建的类AClass。
4.在Main()方法中,我们创建了类Thread的实例。
5.类Thread可以在System.Threading名字空间里得到,它定义了处理线程的属性和方法。
6.在类Thread的构造器中,我们使用了类ThreadStart,类ThreadStart是一个代表,标志着当一个线程开始时就开始执行定义的方法。
7.为了执行定义的方法,我们实际调用的是线程的Start()方法。
8用VBC来编译上面的程序:
vbc /out:threadtest.exe threadtest.vb
9.运行编译后的程序,我们将会看到我们定义的两个方法和main()方法的混合输出,这就说明每一个方法都在自己的线程下运行。
10.除了上面的方法,线程还有下面常用的方法:
Stop():停止线程的运行。
Suspend():暂停线程的运行。
Resume():继续线程的运行。
Sleep():停止线程一段时间(单位为毫秒)。
 
上面只是VB.NET多线程的一个简单的例子,希望对大家有所启发!
添加评论
单击隐藏此项的评论。
将.aspx文件和图片编译进dll

大家可以去看看做好的dll
http://www.bestaspx.net/down/allindll.zip

先简要说一下方法:

一、取得.aspx页面类的源代码

在C:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/Temporary ASP.NET Files目录下可看到你的站点和虚拟目录名,点进去就能找到你的页面类,但注意这个页面类的名字跟你原来的名字没多大联系,你也可以通过陷阱直接在错误页中找到:

源文件: c:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/Temporary ASP.NET Files/root/6e5a7fb1/54c3fdeb/ehrvxfn5.0.cs    行: 90

(在aspx页面任意位置添加即可设置陷阱,取得编译源文件)

二、编译

通过上面得到源文件,注释掉依赖项:如
//dependencies.Add("W://wwwroot//dlltest//ex2.aspx");
然后编译

方法一

打开VS,新建一个WEB项目,将这些页面类包含进来并注释掉页面依赖项,将图片的编译类型设置为嵌入即可。

方法二

没有VS的可以用csc/vbc编译器完成编译,关于如何用编译器编译项目可以参照:http://www.bestaspx.net/Articles/Show.aspx?ArticleID=21

当然图片也是可以打包进去的,这样所有的东东都打进dll了
下面要简单说一下如何在命令行将图片编进dll

用sdk 中自带的C:/Program Files/Microsoft Visual Studio .NET/FrameworkSDK/Samples/Tutorials/resourcesandlocalization/resxgen
resxgen.exe /i:logo.gif /o:test_res.resx /n:logo
得到资源文件test_res.resx,就可以在命令行引用资源编译了。
不能得到resxgen的可以到这里下载:http://www.bestaspx.net/down/ResXGen.zip
源码:http://www.bestaspx.net/down/ResXGen_Src.zip

那么项目中如何使用资源文件呢,诸位请看:
Assembly myAssem = Assembly.GetExecutingAssembly();
ResourceManager rm = new ResourceManager( "名字空间.test_res", myAssem );
System.Drawing.Image objGraphics = ( System.Drawing.Image )rm.GetObject("logo");
objGraphics.Save( Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif );
objGraphics.Dispose();

三、建立aspx到dll的映射

在Asp.Net应用程序配置文件web.config的system.web节的httpHandlers节添加aspx到dll的映射项,语法如下:

<add verb="*" path="aspx文件名" type="类名,dll文件" />

四、测试

通过以上3步,就已完成了所有的工作,下面就测试一下,打开IE,输入
http://localhost/虚拟目录名/aspx文件名查看效果。

因为是很久以前的试验了,现在是凭记忆写的,所以比较乱,如果有问题可以联系我。

添加评论
单击隐藏此项的评论。
用C#实现生成PDF文档
 
 
using  System;
using  System.IO;
using  System.Text;
using  System.Collections;

namespace  PDFGenerator
{

public class PDFGenerator
{
static float pageWidth = 594.0f;
static float pageDepth = 828.0f;
static float pageMargin = 30.0f;
static float fontSize = 20.0f;
static float leadSize = 10.0f;

static StreamWriter pPDF=new StreamWriter("E://myPDF.pdf");

static MemoryStream mPDF= new MemoryStream();

static void ConvertToByteAndAddtoStream(string strMsg)
{
    Byte[] buffer
=null;
    buffer
=ASCIIEncoding.ASCII.GetBytes(strMsg);
    mPDF.Write(buffer,
0,buffer.Length); 
    buffer
=null;
}


static string xRefFormatting(long xValue)
{
    
string strMsg =xValue.ToString();
    
int iLen=strMsg.Length;
    
if (iLen<10)
    
{
        StringBuilder s
=new StringBuilder();
        
int i=10-iLen;
        s.Append(
'0',i);
        strMsg
=s.ToString() + strMsg;
    }

    
return strMsg;
}


static void Main(string[] args)
{
    ArrayList xRefs
=new ArrayList();
    
//Byte[] buffer=null;
    float yPos =0f;
    
long streamStart=0;
    
long streamEnd=0;
    
long streamLen =0;
    
string strPDFMessage=null;
    
//PDF文档头信息
    strPDFMessage="%PDF-1.1/n";
    ConvertToByteAndAddtoStream(strPDFMessage);

    xRefs.Add(mPDF.Length);
    strPDFMessage
="1 0 obj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage
="<< /Length 2 0 R >>/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage
="stream/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    
/**/////PDF文档描述
    streamStart=mPDF.Length;
    
//字体
    strPDFMessage="BT/n/F0 " + fontSize +" Tf/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    
//PDF文档实体高度
    yPos = pageDepth - pageMargin;
    strPDFMessage
=pageMargin + " " + yPos +" Td/n" ;
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage
= leadSize+" TL/n" ;
    ConvertToByteAndAddtoStream(strPDFMessage);

    
//实体内容
    strPDFMessage= "(http://www.wenhui.org)Tj/n" ;
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage
= "ET/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    streamEnd
=mPDF.Length;

    streamLen
=streamEnd-streamStart;
    strPDFMessage
= "endstream/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    
//PDF文档的版本信息
    xRefs.Add(mPDF.Length);
    strPDFMessage
="2 0 obj/n"+ streamLen + "/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);

    xRefs.Add(mPDF.Length);
    strPDFMessage
="3 0 obj/n<</Type/Page/Parent 4 0 R/Contents 1 0 R>>/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);

    xRefs.Add(mPDF.Length);
    strPDFMessage
="4 0 obj/n<</Type /Pages /Count 1/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage
="/Kids[/n3 0 R/n]/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage
="/Resources<</ProcSet[/PDF/Text]/Font<</F0 5 0 R>> >>/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage
="/MediaBox [ 0 0 "+ pageWidth + " " + pageDepth + " ]/n>>/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);

    xRefs.Add(mPDF.Length);
    strPDFMessage
="5 0 obj/n<</Type/Font/Subtype/Type1/BaseFont/Courier/Encoding/WinAnsiEncoding>>/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);

    xRefs.Add(mPDF.Length);
    strPDFMessage
="6 0 obj/n<</Type/Catalog/Pages 4 0 R>>/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);

    streamStart
=mPDF.Length;
    strPDFMessage
="xref/n0 7/n0000000000 65535 f /n";
    
for(int i=0;i<xRefs.Count;i++)
    
{
        strPDFMessage
+=xRefFormatting((long) xRefs[i])+" 00000 n /n";
    }

    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage
="trailer/n<</n/Size "+ (xRefs.Count+1)+"/n/Root 6 0 R/n>>/n";
    ConvertToByteAndAddtoStream(strPDFMessage);

    strPDFMessage
="startxref/n" + streamStart+"/n%%EOF/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    mPDF.WriteTo(pPDF.BaseStream);

    mPDF.Close();
    pPDF.Close();
}

}

}
 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值