MS CRM 2011 插件(plugin)的快速开发 -- 创建模板

 

原创地址:http://www.cnblogs.com/jfzhu/archive/2012/09/25/2701900.html

转载请注明出处

 

如果你开发过很多MS CRM的插件的话,相信你一定会发现,如果每一次开发插件都从头做起的话,你会做很多重复性的工作。如果你发现你每天做着重复性的工作,你就要考虑怎样才能将重复降到最低,理想的情况就是只做一次。

开发CRM的插件(当然要使用Visual Studio)你需要做很多”准备性的工作”,比如添加引用,给插件签名。这些”准备性的工作”也就是重复性的工作,非常浪费时间。一个好的解决办法,就是创建一个你自己的插件模板。在这篇文章中,我为大家介绍两个方面的经验:一是如何建立一个CRM的插件,二是如何在Visual Studio中建立项目模板。

我使用的是Visual Studio 2010。首先创建一个新的Class Library项目,我们命名它为 mycompany.entity.plugin.template

接下来我们将我们常用到的两个assembly添加到解决方案中,Microsoft.Crm.Sdk.Proxy.dll与Microsoft.Xrm.Sdk.dll。这两个文件,你可以在sdk\bin文件夹中找到。

image

然后我们将这两个assembly添加到引用中。并且还有另外两个引用System.Runtime.Serialization和System.ServiceModel。

image

接下来,我们需要给插件签名。通常你的公司应该使用统一的签名文件,你可以去问一下你的项目经理。如果他不知道的话,那很遗憾,你们的公司不太正规。你只能自己生成一个签名文件了。

image

然后我们删除Class1.cs这个文件,创建你自己的类文件,我这里命名它为Plugin.cs,当然你可以命名它为其他你喜欢的文件名。

image

Plugin.cs的内容如下。不要忘记修改你的命名空间和类名。

using System.Linq; 
using System.Text; 
using Microsoft.Xrm.Sdk; 
using System.ServiceModel;

namespace mycompany.entity.plugin.template 
{ 
    public class Plugin : IPlugin 
    { 
        #region IPlugin Members

        public void Execute(IServiceProvider serviceProvider) 
        { 
            // Obtain the execution context from the service provider. 
            IPluginExecutionContext context = 
                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Get a reference to the organization service. 
            IOrganizationServiceFactory factory = 
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

            // Get a reference to the tracing service. 
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try 
            { 
                if (context.MessageName == "Create") 
                { 
                    Entity entity = (Entity)context.InputParameters["Target"]; 
                    
                    //********************* 
                    //add your code here 
                    //********************* 
                } 
            } 
            catch (FaultException<OrganizationServiceFault> ex) 
            { 
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex); 
            } 
            catch (Exception ex) 
            { 
                tracingService.Trace("Error: {0}", ex.ToString()); 
                throw; 
            } 
        }

        #endregion 
    } 
}

到这里我们的模板基本上建好了,接下来最关键的一步就是将它导出为模板。File –> Export Template

image

image

image

到这里模板就已经完全建好了。我们检验一下,重新打开Visual Studio,新建项目,你看到了我们的模板项目已经在列表里了。你只需要给出一个新的项目名,其他一切重复性的工作就不用再做了,是不是效率提高了很多?

 

 

posted @ 2012-09-25 17:28  AI观星台  阅读(2702)  评论(3编辑  收藏  举报