Dynamics crm 处理动态CRM自定义工作流,该工作流更新;修改为;字段--需要调试帮助吗

Dynamics crm 处理动态CRM自定义工作流,该工作流更新;修改为;字段--需要调试帮助吗,dynamics-crm,workflow,Dynamics Crm,Workflow,我正在开发一个Dynamics CRM CWA,它根据名为“准备人”的文本字段更新“修改人”字段。我目前有3个错误,我需要一些帮助调试(见下文)。它们可能很容易修复,但我对编码相当陌生。如有任何帮助,我们将不胜感激。谢谢 using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using

我正在开发一个Dynamics CRM CWA,它根据名为“准备人”的文本字段更新“修改人”字段。我目前有3个错误,我需要一些帮助调试(见下文)。它们可能很容易修复,但我对编码相当陌生。如有任何帮助,我们将不胜感激。谢谢

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Threading.Tasks;
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System.Runtime.Serialization;

namespace KED365.Workflows
{


    /// </summary>    
    public class ModifiedBy : WorkFlowActivityBase
    {
        private Guid contactid;

        [Input("User Full Name")]
        public InArgument<string> UserFullName { get; set; }


        /// <summary>
        /// Executes the WorkFlow.
        /// </summary>
        /// <param name="crmWorkflowContext">The <see cref="LocalWorkflowContext"/> which contains the
        /// <param name="executionContext" > <see cref="CodeActivityContext"/>
        /// </param>       
        /// <remarks>
        /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances.
        /// The WorkFlow's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the WorkFlow. Also, multiple system threads
        /// could execute the WorkFlow at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in WorkFlows.
        /// </remarks>
        protected override void Execute(CodeActivityContext activityContext, IWorkflowContext workflowContext, IOrganizationService orgService, ITracingService tracingService)
        {
            //get entity record for which plugin was fired
            Entity _target = (Entity)workflowContext.InputParameters["Target"];


            //check if portaluser name is to be obtained from custom createby or from custom modifiedby
            if (workflowContext.MessageName.ToUpper() == "CREATE")
            {
                contactid = _target.Attributes.Contains("new_createdby") ? _target.GetAttributeValue<EntityReference>("new_createdby").Id : Guid.Empty;
            }
            else
            {
                contactid = _target.Attributes.Contains("new_modifiedby") ? _target.GetAttributeValue<EntityReference>("new_modifiedby").Id : Guid.Empty;
            }

            //retrieve contact fullname from contactid
            var _contact = activityContext.CreateQuery("contact").Where(c => c.GetAttributeValue<Guid>("contactid").Equals(contactid)).FirstOrDefault();


            if (_contact != null)
            {
                if (_contact.Attributes.Contains("fullname"))
                {
                    fullname = _contact.GetAttributeValue<string>("fullname");
                }

                //retrieve Systemuser that has same name as that of new_portalcreatedby/ //new_portalmodifiedby
                Entity _user = context.CreateQuery("systemuser").Where(e => e.GetAttributeValue<string>("fullname").Equals(fullname)).FirstOrDefault();

                if (_user != null)
                {

                    //check if we need to update createdby or modifiedby
                    if (workflowContext.MessageName.ToUpper() == "CREATE")
                    {
                        _target["createdby"] = _user.ToEntityReference();
                    }
                    else
                    {
                        _target["modifiedby"] = _user.ToEntityReference();
                    }

                    //assign new target to plugin executioncontext
                    workflowContext.InputParameters["Target"] = _target;
                }
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
利用制度全球化;
使用System.Linq;
使用系统文本;
使用System.ServiceModel;
使用System.Threading.Tasks;
使用系统活动;
使用Microsoft.Xrm.Sdk;
使用Microsoft.Xrm.Sdk.Workflow;
使用System.Runtime.Serialization;
命名空间KED365.工作流
{
///     
修改的公共类:WorkFlowActivityBase
{
私人Guid联系人ID;
[输入(“用户全名”)]
公共InArgument UserFullName{get;set;}
/// 
///执行工作流。
/// 
///包含
///  
///        
/// 
///为了提高性能,Microsoft Dynamics 365缓存工作流实例。
///作为构造函数,工作流的Execute方法应该被写为无状态
///不是对工作流的每次调用都调用。此外,多个系统线程
///无法同时执行工作流。所有每次调用的状态信息
///存储在上下文中。这意味着您不应在工作流中使用全局变量。
/// 
受保护的重写无效执行(CodeActivityContext activityContext、IWorkflowContext workflowContext、IorOrganizationService orgService、ITracingService tracingService)
{
//获取触发插件的实体记录
实体_target=(实体)workflowContext.InputParameters[“target”];
//检查是否要从custom createby或custom modifiedby获取portaluser名称
if(workflowContext.MessageName.ToUpper()=“创建”)
{
contactid=_target.Attributes.Contains(“new_createdby”)?_target.GetAttributeValue(“new_createdby”).Id:Guid.Empty;
}
其他的
{
contactid=\u target.Attributes.Contains(“new\u modifiedby”)?\u target.GetAttributeValue(“new\u modifiedby”).Id:Guid.Empty;
}
//从contactid检索联系人全名
var_contact=activityContext.CreateQuery(“contact”)。其中(c=>c.GetAttributeValue(“contactid”).Equals(contactid)).FirstOrDefault();
如果(_contact!=null)
{
if(_contact.Attributes.Contains(“全名”))
{
全名=_contact.GetAttributeValue(“全名”);
}
//检索与new_portalcreatedby///new_portalmodifiedby同名的系统用户
实体_user=context.CreateQuery(“systemuser”).Where(e=>e.GetAttributeValue(“fullname”).Equals(fullname)).FirstOrDefault();
如果(_user!=null)
{
//检查是否需要更新createdby或modifiedby
if(workflowContext.MessageName.ToUpper()=“创建”)
{
_target[“createdby”]=“u user.ToEntityReference();
}
其他的
{
_目标[“modifiedby”]=“u user.ToEntityReference();
}
//将新目标分配给插件executioncontext
workflowContext.InputParameters[“目标”]=\u目标;
}
}
}
}
}
错误1:

严重性代码说明项目文件行抑制状态 错误CS1061“CodeActivityContext”不包含“CreateQuery”的定义,并且找不到接受“CodeActivityContext”类型的第一个参数的扩展方法“CreateQuery”(是否缺少using指令或程序集引用?)工作流C:\Users\tgiard\Downloads\GetUserByName master\GetUserByName master\Workflows\ModifiedBy.cs 68处于活动状态

错误2:

严重性代码说明项目文件行抑制状态 错误CS0103当前上下文工作流C:\Users\tgiard\Downloads\GetUserByName master\GetUserByName master\Workflows\ModifiedBy.cs 75中不存在名称“fullname”

错误3:

严重性代码说明项目文件行抑制状态 错误CS0103当前上下文工作流C:\Users\tgiard\Downloads\GetUserByName master\GetUserByName master\Workflows\ModifiedBy.cs 79中不存在名称“context”


以下是对您的问题的一些反馈:

错误1-“CodeActivityContext”不包含“CreateQuery”的定义
此问题与以下几行有关:

var _contact = activityContext.CreateQuery("contact").Where(c => c.GetAttributeValue<Guid>("contactid").Equals(contactid)).FirstOrDefault();
并为系统用户编写按全名过滤的QueryExpression:

var query = new QueryExpression("systemuser"):
query.Criteria.AddCondition("fullname", ConditionOperator.Equal, fullname);
var _user = orgService.RetrieveMultiple(query).Entities.FirstOrDefault();
错误2:当前上下文中不存在名称“fullname”
这是基本的C#,在使用变量之前必须实例化它:

string fullname;
错误3:当前上下文中不存在名称“context”
讽刺和真实。这应该是activityContext,但我们已经在为错误1所做的更改中修复了此问题

Entity _user = context.CreateQuery("systemuser").Where(e => e.GetAttributeValue<string>("fullname").Equals(fullname)).FirstOrDefault();
Entity\u user=context.CreateQuery(“系统用户”).Where(e=>e.GetAttributeValue(“全名”).Equals(全名)).FirstOrDefault();

正如扎克桅杆正确指出的那样,建议使用预操作。在检索联系人姓名并将其与用户匹配的情况下,这似乎也是一种奇怪的情况。相反,您可以将字段的类型更改为用户引用,将用户字段添加到您检索的联系人,或添加代码t
string fullname;
Entity _user = context.CreateQuery("systemuser").Where(e => e.GetAttributeValue<string>("fullname").Equals(fullname)).FirstOrDefault();
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Linq;

namespace KED365.Plugins
{
    public class CreateUpdateContact : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);
            tracingService.Trace("Start plugin");

            tracingService.Trace("Validate Target");
            if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                return;

            tracingService.Trace("Retrieve Target");
            var target = (Entity)context.InputParameters["Target"];

            String message = context.MessageName.ToLower();

            SetCreatedByAndModifiedBy(tracingService, service, target, message);
        }

        private void SetCreatedByAndModifiedBy(ITracingService tracingService, IOrganizationService service, Entity target, string message)
        {
            tracingService.Trace("Start SetPriceList");
            tracingService.Trace("Validate Message is Create or Update");
            if (!message.Equals("create", StringComparison.OrdinalIgnoreCase) && !message.Equals("update", StringComparison.OrdinalIgnoreCase))
                return;

            tracingService.Trace("Retrieve Attributes");
            var createdByReference = target.GetAttributeValue<EntityReference>("new_createdby");
            var modifiedByReference = target.GetAttributeValue<EntityReference>("new_modifiedby");

            tracingService.Trace("Retrieve And Set User for Created By");
            RetrieveAndSetUser(tracingService, service, target, createdByReference, "createdby");

            tracingService.Trace("Retrieve And Set User for Modified By");
            RetrieveAndSetUser(tracingService, service, target, modifiedByReference, "modifiedby");
        }

        private void RetrieveAndSetUser(ITracingService tracingService, IOrganizationService service, Entity target, EntityReference reference, string targetAttribute)
        {
            tracingService.Trace("Validating Reference");
            if (reference == null)
                return;

            tracingService.Trace("Retrieving and Validating User");
            var user = RetrieveUserByName(service, reference.Name, new ColumnSet(false));
            if (user == null)
                return;

            tracingService.Trace("Setting Target Attribute");
            target[targetAttribute] = user.ToEntityReference();
        }

        private Entity RetrieveUserByName(IOrganizationService service, string name, ColumnSet columns)
        {
            var query = new QueryExpression
            {
                EntityName = "systemuser",
                ColumnSet = columns,
                Criteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "fullname",
                            Operator = ConditionOperator.Equal,
                            Values = { name }
                        }
                    }
                }
            };

            var retrieveResponse = service.RetrieveMultiple(query);
            if (retrieveResponse.Entities.Count == 1)
            {
                return retrieveResponse.Entities.FirstOrDefault();
            }
            else
            {
                // Alternatively you can thrown an error as you have unexpectedly multiple matches
                return null;
            }
        }
    }
}