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,新建項目,你看到了我們的模板項目已經在列表里了。你只需要給出一個新的項目名,其他一切重復性的工作就不用再做了,是不是效率提高了很多?

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM