samsungsamsung 发表于 2015-9-11 11:30:56

WCF初体验(C#操作Exchange)

  最近再做一个Exchange的客户端维护工具,遇到了很多问题。
  由于刚接触C#和Exchange,所以还需要继续学习。在此记录一下,只是一个新手的记录。
  环境:
  服务器:Exchange2010,window server 2008R2
  本 机:Win7 32位,VS2008
  1.此计算机上未安装 Windows PowerShell 管理单元“Microsoft.Exchange.Management.PowerShell.E2010”。
  由于自己的电脑是Win7 32位系统,而Exchange Service的cmdlets模块是X64的,所以报错。
  为了解决此兼容问题,开始想远程调用服务器的powershell,但是由于自己才疏学浅,没有成功,哎。
  后来知道了C#还有WCF这种模式(原谅我的无知),然后开始各种Google,度娘。
  做了好多测试,都没成功。开始用的IIS发布,但是按照各种文章配置后,还是不能调用(对新手来说,这些配置确实够麻烦的,而且一个小细节可能就导致调用失败)
  后来直接写了控制台应用程序来调用:

namespace ExConsole
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost Host = new ServiceHost(typeof(Service1)))
{
//绑定
System.ServiceModel.Channels.Binding httpBinding = new BasicHttpBinding();
//终结点
Host.AddServiceEndpoint(typeof(WcfServiceLibrary1.IService1), httpBinding, "http://10.100.0.50:8888/");
if (Host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>() == null)
{
//行为
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
//元数据地址
behavior.HttpGetUrl = new Uri(&quot;http://10.100.0.50:8888/Service1&quot;);
Host.Description.Behaviors.Add(behavior);
//启动
                  Host.Open();
Console.WriteLine(&quot;WCF服务已经启动,请勿关闭本窗口&quot;);
Console.Read();
}
}
}
}
}
  调用的时候,添加服务引用,地址用http://10.100.0.50:8888/Service1这个就可以了
  2.Service中用到的,调用powershell的方法



public void AddExchangeUser(string loginname, string db)
{
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn(&quot;Microsoft.Exchange.Management.PowerShell.E2010&quot;, out snapInException);
Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
myRunSpace.Open();
Pipeline pipeLine = myRunSpace.CreatePipeline();
string cmd = &quot;Enable-Mailbox -Identity yourdomin\\&quot; + loginname + &quot; -Database &quot; + db;
Command myCommand = new Command(cmd, true);
pipeLine.Commands.Add(myCommand);
Collection<PSObject> commandResults = pipeLine.Invoke();   
}
  3.其他注意点:
  System.Management.Automation.dll一定要引用64位的,
  路径:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
  打开GAC_MSIL文件夹的方法:开始-运行-输入C:\Windows\assembly\GAC_MSIL\,然后我把dll文件复制到别的路径了,对不对不知道,确实能用了
  WCF服务端的程序:目标平台都要设为:x64
页: [1]
查看完整版本: WCF初体验(C#操作Exchange)