【问题标题】:Microsoft CRM 2011 Plugins - Simple IssueMicrosoft CRM 2011 插件 - 简单问题
【发布时间】:2013-08-06 15:50:25
【问题描述】:

我正在尝试编写一个插件来在 Microsoft CRM 2011 中创建一个新的联系人实体。我还没有在网上找到任何有用的信息,我觉得我整天都在用头撞砖墙。我在下面发布的代码给了我一个错误,说“当前上下文中不存在名称'服务'”。谁能告诉我这是怎么回事?

// <copyright file="PreValidateContactCreate.cs" company="">
// Copyright (c) 2013 All Rights Reserved
// </copyright>
// <author></author>
// <date>8/6/2013 4:22:10 PM</date>
// <summary>Implements the PreValidateContactCreate Plugin.</summary>
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
// </auto-generated>
namespace Plugins1
{
    using System;
    using System.ServiceModel;
    using System.Collections.Generic;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Crm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Discovery;
    using Microsoft.Xrm.Sdk.Metadata;
    using Microsoft.Xrm.Sdk.Query;


    /// <summary>
    /// PreValidateContactCreate Plugin.
    /// </summary>    
    public class PreValidateContactCreate: Plugin
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PreValidateContactCreate"/> class.
        /// </summary>
        public PreValidateContactCreate()
            : base(typeof(PreValidateContactCreate))
        {
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(10, "Create", "contact", new Action<LocalPluginContext>(ExecutePreValidateContactCreate)));

            // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination.
            // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change.
        }

        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePreValidateContactCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.


            Entity Contact = new Entity("contact");
            Contact.Attributes["firstname"] = "SomeName";
            Contact.Attributes["lastname"] = "SomeSurname";

            service.Create(Contact);
        }
    }
}

【问题讨论】:

    标签: plugins dynamics-crm-2011


    【解决方案1】:

    由于尚未定义服务而引发错误。在调用 service.Create 之前需要对其进行定义。

    以下是我用于插件的一些代码,您可能会发现它们很有用。似乎比你的例子简单一点。

    编辑:我已修改代码以显示创建和更新

    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Query;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;
    
    namespace PluginSample
    {
        public class ContactSample : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                // Get the context
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    
                try
                {
                    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = factory.CreateOrganizationService(context.UserId);
    
                    if (context.MessageName == "Create")
                    {
                        // Creates a contact
                        Entity contact = new Entity("contact");
                        contact.Attributes.Add("firstname", "SomeName");
                        contact.Attributes.Add("lastname", "SomeSurname");
                        service.Create(contact);
                    }
                    else if (context.MessageName == "Update")
                    {
                        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                        {
                            // Update contact
                            Entity contact = new Entity("contact");
                            contact.Id = new Guid("EBFB262C-5EFF-E211-8BEB-1CC1DEEAE7EC");
                            contact.Attributes.Add("firstname", "Name Changed");
                            service.Update(contact);
                        }
                    }
    
                }
                catch (Exception generalException)
                {
                    throw new InvalidPluginExecutionException("Plugin Failed - Execute :-(", generalException);
                }
            }
        }
    }
    

    【讨论】:

    • 非常感谢您的回复。我试过这段代码,它似乎没有创建记录。请问您(或其他任何人)有任何示例代码来说明如何创建记录吗?
    • 您是如何注册插件步骤的?您能否提供更多有关何时创建联系人的详细信息?我会调查我的回复并更新。
    • 是的,它都已注册,运行时不会出错,但没有创建联系人。创建联系人实际上只是一个培训练习,因为我完全是新手。很抱歉一直打扰您,但是如果您能够与我分享一些代码,这些代码可以获取刚刚创建的记录中字段的值,然后用其他值更新该字段,那将是惊人的。非常感谢您的帮助
    • 我已经修改了代码以显示创建(原样),然后添加到更新中。目前两者都失败了,我不知道为什么(这里是深夜!)明天早上会更新。
    • 非常感谢 Campey - 我非常感谢您为我付出的所有努力
    【解决方案2】:

    使用 localContext 参数进入组织服务。

    *<param name="localContext">The <see cref="LocalPluginContext"/> which contains the
            /// <see cref="IPluginExecutionContext"/>,
            /// <see cref="IOrganizationService"/>*
    

    【讨论】:

      【解决方案3】:
      public class CreateRecord : IPlugin
          {
              /// <summary>
              /// Execute Method
              /// </summary>
              /// <param name="serviceProvider">IServiceProvider object.</param>
              public void Execute(IServiceProvider serviceProvider)
              {
                  //Obtain the tracing service.
                  ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                  if (tracingService == null)
                      throw new Exception("Unable to obtain tracing service.");
      
                  //Obtain the execution context from the service provider.
                  IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                  if (context == null)
                      throw new Exception("Unable to obtain Plugin Execution context.");
      
                  //Obtain the organization service reference
                  IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                  if (serviceFactory == null)
                      throw new Exception("Unable to obtain Organization service factory.");
      
                  IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                  if (service == null)
                      throw new Exception("Unable to obtain organization service.");
      
                  Entity contact = new Entity("contact");
                  contact["firstname"] = "Your First Name";
                  contact["lastname"] = "Your Last Name";
                  Guid contactId = service.Create(contact);
              }
          }  
      

      以上代码是创建记录的示例,在本例中为 CRM 中的联系人。 contactid 应该保存创建的记录。您可以在活动联系人视图下与其他联系人一起找到创建的记录。

      希望这会有所帮助。如果您需要更多帮助,请告诉我。快乐学习!!! :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多