Dynamics CRM插件开发及调试

本文介绍Dynamics CRM插件开发及插件调试

工具:VS2015、Developer Toolkit for Microsoft Dynamics 365、PluginRegistration

需求:我需要用插件开发的方式给客户实体的客户编码字段赋值

步骤一:首先需要下载安装Developer Toolkit for Microsoft Dynamics 365工具,安装完成后在VS中会出现Dynamics 365模板, 在VS中添加Developer Toolkit 路径。

打开 Visual Studio > 工具 > 选项 ,找到Dynamics 365 Developer Toolkit中的Tool Paths,设定好自己的插件注册工具文件路径和CRM SDK的Bin目录,我这里分别设置为 C:\DynamicsCRM\SDK2016UR1\SDK\Tools\PluginRegistration 和 C:\DynamicsCRM\SDK2016UR1\SDK\Bin

步骤二:在VS中使用Dynamics 365模板新建项目,具体操作如下截图:

 1.新建解决方案也可以选择第一项,可创建多个类型的项目如插件和工作流。这里只选择插件项目

2.建立与CRM服务器的连接。也可以不用连接,放到后面的PluginRegistration工具连接,我这里主要是使用PluginRegistration工具,这个Developer Toolkit for Microsoft Dynamics 365工具我主要用来建解决方案

3.添加类,编写插件

4.这里将代码复制过来(我是参照石头居的博客)

using System;

// Microsoft Dynamics CRM的命名空间之一
using Microsoft.Xrm.Sdk;

namespace Microsoft.Crm.Sdk.Samples
{
    public class AccountNumberPlugin: IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // 获取执行上下文
            IPluginExecutionContext context =

                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // InputParameters属性包含所有输入参数数据
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // 从输入参数中获取Target参数
                Entity entity = (Entity)context.InputParameters["Target"];
                //检测输入的Target参数,判断其逻辑名称是否是account.
                if (entity.LogicalName == "account")
                {
                    // 判断客户记录的客户编码字段accountnumber是否有值
                    if (entity.Attributes.Contains("accountnumber") == false)
                    {
                        // 没有客户编码,那么赋一个随机数字
                        Random rndgen = new Random();
                        entity.Attributes.Add("accountnumber", rndgen.Next().ToString());
                    }
                    else
                    {
                        // 抛出一个错误,注意,错误的类型!
                        throw new InvalidPluginExecutionException("The account number can only be set by the system.");
                    }                    
                }
            }
        }
    }
}

 5.添加签名  右键解决方案>属性

 5.创建完成之后重新生成一下解决方案

 6.用pluginsRegistration工具进行注册。工具位置在SDK>Tools文件夹中。先注册项目然后新建步骤。

7.完成。看一下运行的效果看看插件是否生效

步骤三:插件调试  写的代码没有生效或者是出错,需要进行插件的调试

1.打开pluginRegistration工具安装分析器 profiler

 

2.选中要调试的插件,step,点击Start Profiling

3.去CRM中操作实体,下载日志文件

 4.回到插件注册器关掉profiling

5.点击Debug

6.到VS2015,设置断点,附加PluginRegistration进程

 7.再回到插件工具点击执行

8.这时就会看到断点生效,进行调试

猜你喜欢

转载自www.cnblogs.com/cuig/p/9077461.html