com+和消息队列结构是:
首先服务器端安装com+和消息队列服务器,而客户端安装com+服务的代理和消息队列服务器。
com+和消息队列的工作过程是:
客户端构造成个消息放到本机的发送消息队列中,客户端发送消息队列负责发该消息发送到com+服务器上,
com+ 服务器消息队列接受客户端的消息。com+负责侦听消息,如用消息到达,就处理。
代码如下:
一.
1.服务器端.新建类库项目ServerLibrary2
using System.Runtime.InteropServices;
using System.Messaging;
using System.EnterpriseServices;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Data.SqlClient;
namespace ServerLibrary2
{
[GuidAttribute("99FCA8DD-3B97-35C3-819B-CECADBFB7DDE")] //指定这个类的GUID,防止重复注册]
[InterfaceQueuing]
// 使用这一属性使得客户端的函数调用可以被放置到队列中去。
public interface IQComponent
{
void ComplicatedFunction(int num);
}
/**//// <summary>
/// 实现 com+ 的事件侦听
/// 队列组件必须继承ServicedComponent类。同时它还要实现IQComponent接口
/// </summary>
[Transaction(System.EnterpriseServices.TransactionOption.RequiresNew)]
public class QCSimpleDemo : ServicedComponent,IQComponent
{
public QCSimpleDemo()
{
}
public void ComplicatedFunction(int num)
{
//程序处理放在这里
string spath;
string content;
try
{
System.Data.SqlClient.SqlConnection Sqlcn=new SqlConnection("server=10.10.10.150;database=test;uid=sa;pwd=sa");
Sqlcn.Open();
System.Data.SqlClient.SqlCommand Sqlcomm=Sqlcn.CreateCommand();
Sqlcomm.CommandText="update com_test set num=num+"+num ;
Sqlcomm.ExecuteNonQuery();
Sqlcomm.CommandText="update com_test1 set num=num-"+num;
Sqlcomm.ExecuteNonQuery();
ContextUtil.SetComplete(); //提交
Sqlcn.Close();
//写日志文件
spath=(@"D:/VsCode/Dservice2/Com_Test/LOG.txt");
System.IO.StreamWriter sw;
sw=File.AppendText(spath);
content=System.DateTime.Now.ToString()+"表com_test中的num增加了"+num.ToString()+" 表com_test1中的num减少了"+num.ToString();
sw.WriteLine(content);
sw.Close();
// MessageBox.Show(num.ToString());
}
catch (Exception ex)
{
ContextUtil.SetAbort(); //取消
spath=(@"D:/VsCode/Dservice2/Com_Test/LOG.txt");
System.IO.StreamWriter sw;
sw=File.AppendText(spath);
content=System.DateTime.Now.ToString()+"操作错误;原因"+ex.Message;
sw.WriteLine(content);
sw.Close();
}
}
}
}
2, 用 sn -k "路径+文件名" 生成强类型的程序集,在AssemblyInfo.cs 文件中加[assembly: AssemblyKeyFile(@"c:/key.snk")]
2. 生成 Serverlibrary2.dll
3. 注册 regsvcs serverlibrary2.dll.
说明:机器上必须安装消息队列服务器。
二. 客户端
1.客户端代码
try
{
//用接口调用
ServerLibrary2.IQComponent IQC= (IQComponent)Marshal.BindToMoniker("queue:/new:ServerLibrary2.QCSimpleDemo");
int num=0;
num=int.Parse(this.textBox2.Text);
IQC.ComplicatedFunction(num);
Marshal.ReleaseComObject(IQC);
MessageBox.Show("转帐成功!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
说明:Marshal.BindToMoniker 是System.Runtime.InteropServices下的一个方法。它获取一个指针。
Marshal.ReleaseComObject(IQC); 释放对象引用数