摘要: Web-Based Applications That Change the Way You Work and Collaborate Online.希望大家不要取笑.给大家看看http://sites.google.com/site/steventaoyongqiang阅读全文
posted @ 2009-09-08 11:20 陶勇强 阅读(40) 评论(1) 编辑

买了园子里面专家写的一本书,你必须知道的.NET把第2部分本质-.NET深入浅出.讲述CIL中间语言的部分详细认真的阅读完后,对.NETCLR的运行以及底层的了解随之加深,并把以前项目中运用到的需要产生动态程序集有熟悉了一遍!写了个简单的例子!只有对CIL有所熟悉之后才能对动态产生程序集这项技术下手,

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;
using System.Threading;
namespace _5_CIL
{
    /// <summary>
    /// 产生动态程序集
    /// 陶勇强
    /// </summary>
    ///要动态构造的程序集的类
    ///public class HelloWord
   /// {
   ///   private string theMessage;
   ///   public HelloWord()
   ///   { }
   ///   public HelloWord(string s)
   ///   {
   ///      theMessage = s;
   ///   }
   ///   public string GetMsg()
   ///   {
   ///      return theMessage;
  ///    }
  ///    public void SayHello()
  ///    {
  ///       Console.WriteLine("欢迎来到我的HelloWord类!");
  ///    }
  ///  }
   
    /// <summary>
    /// 下面的代码动态产生程序集<创建上面的类>
    /// </summary>
    class Program
    {
        /// <summary>
        /// 动态创建程序集,调用传入一个AppDomain类型
        /// </summary>
        /// <param name="args"></param>
        public static void CreateMyAsm(AppDomain curAppDomain)
        {
            //创建通用的程序集特征
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = "MyAssembly";
            assemblyName.Version = new Version("1.0.0.0");


            //在当前程序域中创建一个新的程序集
            AssemblyBuilder assembly = curAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);

            //本人创造的是一个单文件程序集,模块的名字就是程序集的名字
            ModuleBuilder module = assembly.DefineDynamicModule("MyAssembly", "MyAssembly.dll");
           
            //定义一个公共类HelloWord
            TypeBuilder helloWorldClass = module.DefineType("MyAssembly.HelloWorld", TypeAttributes.Public);
           
            //定义一个私有字符串类型成员
            FieldBuilder msgfield = helloWorldClass.DefineField("theMessage", Type.GetType("System.String"),
                FieldAttributes.Private);

            //构件一个自定义构造函数
            Type[] constructorAers = new Type[1];
            constructorAers[0] = typeof(string);
            ConstructorBuilder conster = helloWorldClass.DefineConstructor(MethodAttributes.Public,
            CallingConventions.Standard, constructorAers);

            //产生必要的CIL代码到构造函数
            ILGenerator contorIl = conster.GetILGenerator();
            contorIl.Emit(OpCodes.Ldarg_0);
            Type objectClass = typeof(object);
            ConstructorInfo super = objectClass.GetConstructor(new Type[0]);
            contorIl.Emit(OpCodes.Call, super);

            //加载对象的this指针到栈上
            contorIl.Emit(OpCodes.Ldarg_0);

            //加载输入参数到栈上
            contorIl.Emit(OpCodes.Ldarg_1);
            contorIl.Emit(OpCodes.Stfld, msgfield);
            contorIl.Emit(OpCodes.Ret);

            //创建默认构造函数
            helloWorldClass.DefineDefaultConstructor(MethodAttributes.Public);

            //创建GetMsg()方法
            MethodBuilder getMsgMethod = helloWorldClass.DefineMethod("GetMsg", MethodAttributes.Public, typeof(string), null);
            ILGenerator methodIl = getMsgMethod.GetILGenerator();
            methodIl.Emit(OpCodes.Ldarg_0);
            methodIl.Emit(OpCodes.Ldfld, msgfield);
            methodIl.Emit(OpCodes.Ret);

            //创建SayHello()方法
            MethodBuilder getSayHelloMothod = helloWorldClass.DefineMethod("SayHello", MethodAttributes.Public, null, null);
            methodIl = getSayHelloMothod.GetILGenerator();
            methodIl.EmitWriteLine("欢迎来到我的HelloWord类!\n");
            methodIl.Emit(OpCodes.Ret);

            //创建HelloWordClass类
            helloWorldClass.CreateType();

            //保存创建的程序集
            assembly.Save("MyAssembly.dll");

           

        }
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("动态生成程序集程序");

                //得到当前域
                AppDomain curApp = Thread.GetDomain();

                //构造创建动态程序集
                CreateMyAsm(curApp);
                Console.WriteLine("创建程序集,并加载新的程序集到文件\n");
                Assembly ass = Assembly.Load("MyAssembly");

                //得到HelloWord类型
                Type hello = ass.GetType("MyAssembly.HelloWorld");

                //创建HelloWord对象并调用构造函数        
                Console.Write("->请输入内容: ");
                string msg = Console.ReadLine();
                object[] cotro = new object[1];
                cotro[0] = msg;
                object obj = Activator.CreateInstance(hello, cotro);

                //调用方法动态创建的程序集里面的HelloWord类里面的SayHello方法
                Console.WriteLine("->执行方法SayHello\n");
                MethodInfo mt = hello.GetMethod("SayHello");
                mt.Invoke(obj, null);

                //调用GetMsg()方法
                Console.WriteLine("输出内容GetMsg()方法\n");
                mt = hello.GetMethod("GetMsg");
                Console.WriteLine(mt.Invoke(obj, null));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}

posted @ 2008-11-29 01:44 陶勇强 阅读(966) 评论(3) 编辑

项目需求,最近做一个WINFORMS的项目,需求里面要求打印出本机所有进程,以及查看单独进程信息和进程模块信息,还要通过程序来打开系统中的进程!其实项目是一个金融方面的管理项目,不知道本人做的对大家有没有什么用处!

1.显示全部进程

 

 

2.显示单个进程

 

 

 

3.显示进程线程集合时间跟优先级别

 

4.显示进程的模块信息

 

5.打开一个系统中的进程

 

以下个人代码

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace MyJinCheng
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //打印出本机进程
        public void ListAllRunningProcess()
        {
            Process[] proc = Process.GetProcesses(".");
            foreach (Process p in proc)
            {
                string info = string.Format("->进程ID:{0}\t进程名字:{1}",p.Id,p.ProcessName);
                this.listBox1.Items.Add(info);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            ListAllRunningProcess();
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = e.KeyChar < '0' || e.KeyChar > '9';
            if (e.KeyChar == (char)8)
            {
                e.Handled = false;
                MessageBox.Show("输入的字符不符合规定","错误");
            }
        }
        //显示单个正在运行的进程信息
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text.Length == 0)
            {
                MessageBox.Show("请输入您要查询的进程ID", "空值类型");
            }
            else
            {
                this.listBox1.Items.Clear();
                int PID = Convert.ToInt32(this.textBox1.Text);
                try
                {
                    Process proc;
                    proc = Process.GetProcessById(PID);
                    this.listBox1.Items.Add(proc.ToString());

                }
                catch
                {
                    MessageBox.Show("没有你要查看的进程", "错误");
                }
            }
        }
        //查看单个进程线程集合
        private void button2_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text.Length == 0)
            {
                MessageBox.Show("请输入您要查询的进程ID", "空值类型");
            }
            else
            {
                this.listBox1.Items.Clear();
                int PID = Convert.ToInt32(this.textBox1.Text);
                Process proc;
                try
                {
                    proc = Process.GetProcessById(PID);
                }
                catch
                {
                    MessageBox.Show("没有你要查看的进程线程集合!", "错误");
                    return;
                }
                this.listBox1.Items.Add("进程名:'" + proc.ProcessName + "'");
                ProcessThreadCollection threads = proc.Threads;
                foreach (ProcessThread p in threads)
                {
                    string info = string.Format("->线程ID:{0}\t开始时间:{1}\t优先级别:{2}", p.Id, p.StartTime, p.PriorityLevel);
                    this.listBox1.Items.Add(info);
                }
            }
        }
        //查看进程模块信息
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text.Length == 0)
            {
                MessageBox.Show("请输入您要查询的进程ID", "空值类型");
            }
            else
            {
                this.listBox1.Items.Clear();
                int PID = Convert.ToInt32(this.textBox1.Text);
                Process proc;
                try
                {
                    proc = Process.GetProcessById(PID);
                }
                catch
                {
                    MessageBox.Show("没有您要查询的进程模块信息", "错误");
                    return;
                }
                this.listBox1.Items.Add("模块话进程:'" + proc.ProcessName + "'");
                try
                {
                    ProcessModuleCollection module = proc.Modules;
                    foreach (ProcessModule m in module)
                    {
                        string info = string.Format("模块名字:{0}\t模块文件的完整路径:{1}\t模块的内存地址:{2}", m.ModuleName, m.FileName, m.BaseAddress);
                        this.listBox1.Items.Add(info);
                    }
                }
                catch
                {
                    MessageBox.Show("没有模块信息", "错误");
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Open op = new Open();
            op.Show();
        }
    }
}

 

 

打开一个进程的代码

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace MyJinCheng
{
    public partial class Open : Form
    {
        public Open()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string Name = this.textBox1.Text;
            try
            {
                Process proc;
                proc = Process.Start(Name);
            }
            catch
            {
                MessageBox.Show("没有你要打开的进程!", "输入错误");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.Opacity < 1)
            {
                this.Opacity = this.Opacity + 0.05;//随时间增加Opacity的值,每次增加0.05
            }
            else
            {
                this.timer1.Enabled = false;
            }


        }

        private void Open_Load(object sender, EventArgs e)
        {
            this.timer1.Enabled = true;//使时间控件生效
            this.Opacity = 0;//设置初始透明度 Opacity:0-1.0, 0为全透明,1.0为不透明
        }
    }
}

 

不知道需求为什么会有这个不过做的很开心与大家分享一下!

posted @ 2008-11-28 02:01 陶勇强 阅读(2734) 评论(9) 编辑

<项目需求中的>首先创建以下程序集

1.CommonSnappbleTyoes.dll:改程序集包含将每个插件实现的类型定义,插件将会在可扩展的Windows窗体应用程序中引用.

2.CSharpSnapIn.dll:一个C#插件它使用CommonSnappbleTyoes.dll类型.

3.VBNetSnapIn.dll:一个用VB.NET编写的插件,它也同样使用CommonSnappbleTyoes.dll类型.

4.MyPluggableApp.exe:这个Windows窗体应用程序将成为可以被每个插件功能扩展的实体.另外,这个应用程序可以使用动态加载,反射和晚期绑定来动态获取预先不知道的程序集功能.

部分WINDOWS界面窗体代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using CommonSnappableTyies;
using System.IO;
namespace MyExtendableApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private bool LoadExternalModule(string path)
        {
            bool foundSnapIn = false;
            IAppFunctionlity itfAppFx;
            //动态加载中的程序集
            Assembly asm = Assembly.LoadFrom(path);
            Type[] type = asm.GetTypes();
            for (int i = 0; i < type.Length; i++)
            {
                Type t = type[i].GetInterface("IAppFunctionlity");
                if (t != null)
                {
                    foundSnapIn = true;
                    //使用晚期绑定创建一个类型
                    object obj = asm.CreateInstance(type[i].FullName);
                    //脱离接口掉用接口的方法
                    itfAppFx = obj as IAppFunctionlity;
                    itfAppFx.DoIt();
                    this.listBox1.Items.Add(type[i].Name);
                    DisplyCommpanDate(type[i]);
                }
            }
            return foundSnapIn;
        }
        //得到[CompanyInfo]数据
        private void DisplyCommpanDate(Type t)
        {
            object[] obj = t.GetCustomAttributes(false);
            foreach (CompanyInfoAttribute c in obj)
            {
                MessageBox.Show(c.Url,string.Format("Nore info about{0} can be foud at",c.Name));
            }
        }
        private void snapInModuleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //允许用户加载一个程序集
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (LoadExternalModule(dlg.FileName) == false)
                {
                    MessageBox.Show("没有实现接口的方法");
                }
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Time.Text = DateTime.Now.ToString();
        }
        //反射程序集调用方法
        private void FanShe()
        {
             Assembly a ;
            try
            {
                a = Assembly.Load("CommonSnappableTyies");
            }
            catch (FileNotFoundException e)
            {
                MessageBox.Show(e.ToString());
                return;
            }
            Type b = a.GetType("CommonSnappableTyies.CompanyInfoAttribute");
            object obj = Activator.CreateInstance(b);
            MethodInfo mi = b.GetMethod("Show");
            mi.Invoke(obj,null);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.FanShe();
        }
    }
}

posted @ 2008-11-27 01:09 陶勇强 阅读(1859) 评论(6) 编辑
很高兴能加入这个大家庭!
posted @ 2008-11-13 15:06 陶勇强 阅读(57) 评论(4) 编辑