【问题标题】:Retrieving custom entities in CRM 4 C#在 CRM 4 C# 中检索自定义实体
【发布时间】:2013-03-22 16:37:23
【问题描述】:

在我们的 CRM 环境中,用户与可用时间实体存在 1:N 关系,该实体表示他们一周的实际可用时间。我正在 C# 中寻找一种方法来检索本周特定团队的用户的所有可用时间。

我是 CRM 开发的新手,我环顾四周,但似乎有很多方法可以做到这一点,我不确定哪种方法最适合。

语言为 C#,CRM 版本为 MS CRM 4.0

【问题讨论】:

  • 看到没有人看过这个问题,所以我担心它有点迟钝......这会出现在插件或工作流程序集中吗?还是在需要访问 CRM 的外部应用程序中?
  • 我有一个外部网页,其中包含一个表格,该表格将保存过去 4 周(第 4 周、第 3 周、第 2 周、第 1 周)的总可用小时数,最后一列保存当前周总小时数。到目前为止,我只需要作为技术人员团队成员的可用时间。我的目标是检索每个成员每周的可用时间,以便我可以总结它们并将它们显示在我的表格中。
  • 好的,所以只是为了澄清我的理解,它将是一个调用 CRM 以检索某些用户的可用时间的外部应用程序?而您正在寻找最有效的方法来做到这一点?
  • 确实,对于每个技术用户,我想循环并获取他们的可用时间,通过这样做,我希望更好地了解如何在 CRM 中检索许多相同类型的实体。
  • 您好,很抱歉延迟联系您 - 我正在尝试以合理的方式将其写下来,但我应该能够在接下来的 24 小时内发布答案。抱歉,您的问题有点含糊。

标签: c# dynamics-crm-4 entities


【解决方案1】:

我将介绍这 3 位:一般方法、代码本身以及代码上的一些注释(代码被注释以引起对某些事情的注意,但其中一些将在代码之外进行进一步解释)。

一般方法

如您所见,有几种方法可以做事,但对于通过 Web 服务与 CRM 交互的外部应用程序,它归结为 3 个主要选项:

  1. 使用通过在 Web 服务调用中添加 Web 引用获得的强类型方法来检索您的自定义实体(我认为您在上一个问题中提到看到方法爆炸...当您有很多自定义实体)
  2. 在您的网络服务调用中使用DynamicEntity
  3. FetchXML

如果您的系统非常简单,您通常可以使用 (1),但我建议您选择 (2) 或 (3)。使用 (2) 意味着您只需要记住少数 Web 服务方法,如果您曾经使用插件或工作流程序集,因为这些概念可以很好地传播,那么它就很好。 (3) 如果您了解 FetchXML 并且可以形成适当的查询,则很好。

我通常使用常见的 (2) 来处理这些事情,这是一种很好的中间方法,而且,就像我说的那样,您的代码将相当容易转换为插件或工作流程序集。 FetchXML 执行得很好,但我从不擅长形成查询 - 我稍后会介绍一些技术,但让我们继续使用 (2)。

此外,如果您使用 DynamicEntity,则您不需要刷新您的网络引用,因为您使用它的方式及其 Property 对象数组(基本上,您会以强类型为代价获得灵活性),因为您'将在代码中看到。如果您选择 (1),您将获得针对您的自定义实体的强类型,但您必须根据人们对您的实体所做的更改的节奏不断刷新您的 WebReference。

代码

这是在一个小控制台应用程序中,我在其中向 CRM 服务添加了一个 WebReference,并进行了一些调用来模拟您的场景。代码应该传递到其他应用程序,如网络应用程序。我已尝试对其发表评论,因此在转到下一部分之前可能值得一读。

(注意。我不认为这是世界上最好的代码,但它似乎确实有效,应该让你开始)

(NB2.我犯了一个错误,将我的命名空间调用为网络引用CrmService - 请不要和我犯同样的错误......)

static void Main(string[] args)
{
        CrmService.CrmService svc = new CrmService.CrmService();
        svc.CrmAuthenticationTokenValue = GetToken();
        svc.UseDefaultCredentials = true;

        #region 1 - Retrieve users in team
        RetrieveMembersTeamRequest teamMembersReq = new RetrieveMembersTeamRequest()
        {
            EntityId = new Guid("D56E0E83-2198-E211-9900-080027BBBE99"), //You'll need the team GUID
            ReturnDynamicEntities = true
        };

        ColumnSet teamMembersReqColumnSet = new ColumnSet();
        teamMembersReqColumnSet.Attributes = new string[] { "systemuserid", "domainname" };

        teamMembersReq.MemberColumnSet = teamMembersReqColumnSet; //Don't use: teamMembersReq.MemberColumnSet = new AllColumns()

        List<Guid> userIdList = new List<Guid>();
        RetrieveMembersTeamResponse teamMembersResp = svc.Execute(teamMembersReq) as RetrieveMembersTeamResponse;
        if (teamMembersResp != null)
        {
            BusinessEntity[] usersInTeamAsBusinessEntity = teamMembersResp.BusinessEntityCollection.BusinessEntities;
            List<DynamicEntity> usersInTeamAsDynEntity = usersInTeamAsBusinessEntity.Select(be => be as DynamicEntity).ToList(); //BusinessEntity not too useful, cast to DynamicEntity

            foreach (DynamicEntity de in usersInTeamAsDynEntity)
            {
                Property userIdProp = de.Properties.Where(p => p.Name == "systemuserid").FirstOrDefault();
                Property domainNameProp = de.Properties.Where(p => p.Name == "domainname").FirstOrDefault();

                if (userIdProp != null)
                {
                    KeyProperty userIdKeyProp = userIdProp as KeyProperty; //Because it is the unique identifier of the entity
                    userIdList.Add(userIdKeyProp.Value.Value); //Chuck in a list for use later
                    Console.Write("Key: " + userIdKeyProp.Value.Value.ToString());
                }

                if (domainNameProp != null)
                {
                    StringProperty domainNameStringProp = domainNameProp as StringProperty; //Because its data type is varchar
                    Console.Write("| Domain Name: " + domainNameStringProp.Value);
                }

                Console.WriteLine();
            }
        }
        #endregion

        /*
         * For this example I have created a dummy entity called new_availablehours that is in a 1:N relationship with use (i.e. 1 user, many new_available hours). 
         * The test attributes are :
         *      - the relationship attribute is called new_userid...this obviously links across to the GUID from systemuser
         *      - there is an int data type attribute called new_hours
         *      - there is a datetime attribute called new_availabilityday
         */
        #region Retrieve From 1:N
        RetrieveMultipleRequest req = new RetrieveMultipleRequest();
        req.ReturnDynamicEntities = true; //Because we love DynamicEntity

        //QueryExpression says what entity to retrieve from, what columns we want back and what criteria we use for selection
        QueryExpression qe = new QueryExpression();
        qe.EntityName = "new_availablehours"; //the entity on the many side of the 1:N which we want to get data from

        qe.ColumnSet = new AllColumns(); //Don't do this in real life, limit it like we did when retrieving team members

        /*
         * In this case we have 1 x Filter Expression which combines multiple Condition Operators
         * Condition Operators are evaluated together using the FilterExpression object's FilterOperator property (which is either AND or OR)
         * 
         * So if we use AND all conditions need to be true and if we use OR then at least one of the conditions provided needs to be true
         * 
         */
        FilterExpression fe = new FilterExpression();
        fe.FilterOperator = LogicalOperator.And;

        ConditionExpression userCondition = new ConditionExpression();
        userCondition.AttributeName = "new_userid"; //The attribute of qe.EntityName which we want to test against
        userCondition.Operator = ConditionOperator.In; //Because we got a list of users previously, the appropriate check is to get records where new_userid is in the list of valid ones we generated earlier
        userCondition.Values = userIdList.Select(s => s.ToString()).ToArray(); //Flip the GUID's to strings (seems that CRM likes that) then set them as the values we want to evaulate
        //OK - so now we have this userCondition where valid records have their new_userid value in a collection of ID's we specify

        ConditionExpression dateWeekBound = new ConditionExpression();
        dateWeekBound.AttributeName = "new_availabilityday";
        dateWeekBound.Operator = ConditionOperator.ThisWeek; //ConditionOperator has a whole bunch of convenience operators to deal with dates (e.g. this week, last X days etc) - check them out as they are very handy

        /*
         * As an aside, if we didn't want to use the convenience operator (or if none was available) we would have to create a ConditionExpression like:
         * 
         * ConditionExpression dateLowerBound = new ConditionExpression();
         * dateLowerBound.AttributeName = "new_availabilityday";
         * dateLowerBound.Operator = ConditionOperator.OnOrAfter;
         * dateLowerBound.Values = new object[] { <Your DateTime object here> };
         * 
         * And a corresponding one for the upper bound using ConditionOperator.OnOrBefore
         * 
         * Another alternative is to use ConditionOperator.Between. This is flexible for any sort of data, but the format of the Values array will be something like:
         *      ce.Values = new object[] { <lower bound>, <upper bound> };
         */

        fe.Conditions = new ConditionExpression[] { userCondition, dateWeekBound }; //Add the conditions to the filter
        qe.Criteria = fe; //Tell the query what our filters are
        req.Query = qe; //Tell the request the query we want to use

        RetrieveMultipleResponse resp = svc.Execute(req) as RetrieveMultipleResponse;
        if (resp != null)
        {
            BusinessEntity[] rawResults = resp.BusinessEntityCollection.BusinessEntities;
            List<DynamicEntity> castedResults = rawResults.Select(r => r as DynamicEntity).ToList();

            foreach (DynamicEntity result in castedResults)
            {
                Property user = result.Properties.Where(p => p.Name == "new_userid").FirstOrDefault();
                Property hours = result.Properties.Where(p => p.Name == "new_hours").FirstOrDefault();

                if (user != null)
                {
                    LookupProperty relationshipProperty = user as LookupProperty; //Important - the relationship attribute casts to a LookupProperty
                    Console.Write(relationshipProperty.Value.Value.ToString() + ", ");
                }

                if (hours != null)
                {
                    CrmNumberProperty hoursAsCrmNumber = hours as CrmNumberProperty; //We also have CrmFloatProperty, CrmDecimalProperty etc if the attribute was of those data types
                    Console.Write(hoursAsCrmNumber.Value.Value);
                }

                Console.WriteLine();
            }
        }
        #endregion

        Console.ReadLine();
    }

    static CrmAuthenticationToken GetToken()
    {
        CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.AuthenticationType = 0; //Active Directory
        token.OrganizationName = "DevCRM";

        return token;
    }

那么..那是什么?

我不打算逐一介绍,而是重点介绍:

  1. 使用服务时的关键方法是Execute() 方法,我们向它传递一个请求对象并返回一个响应对象。请求都将是 &lt;Operation&gt;Request 类的对象,响应将是 &lt;Operation&gt;Response 类的对象。
  2. 您通常希望使用DynamicEntity - &lt;Operation&gt;Request 对象通常会公开一个名为ReturnDynamicEntities 的属性,您应该将其设置为true
  3. 大多数&lt;Operation&gt;Request 对象都有一个ColumnSet 属性,您可以在其中指定要返回的属性。指定AllColumns() 通常是不好的做法,相反,您应该明确说明要返回的数据。属性需要匹配它们在 CRM 中的名称(格式为 &lt;prefix&gt;_&lt;field name&gt;)并且全部小写
  4. 让用户加入团队并不太有趣,因为它是 CRM 中的预定义操作,没什么特别的......在这种情况下,SDK 是您的朋友,因为它会向您展示这些工作是如何工作的
  5. 检索一堆自定义实体是一个更有趣的用例,我们通常可以通过使用 RetrieveMultipleRequest 和 RetrieveMultipleResponse 方法来获取它们(如果您只想要一条记录,那么您可以使用 RetrieveRequest 和 @987654346 @...但您需要知道要输入到 RetreiveRequest 对象中的内容的 GUID。
  6. 对于RetrieveMultipleRequest,我们向它提供一个查询(QueryExpression),它说明我们想要获得多个实体(EntityName),我们想要返回的实体的属性(ColumnSet)和过滤器(Criteria) 用于选择我们想要的实际记录
  7. 关注QueryExpression、FilterExpression和ConditionExpression的使用。重要的是要知道ConditionExpression 中有哪些运算符可供您使用 - 我已尝试在代码中调用一些运算符,但 SDK 再次成为您了解可用运算符的最佳朋友
  8. 我没有涉及更复杂的过滤,例如 (x OR y) AND z。有一个相当好的例子here。这只是使用FilterExpression 和ConditionExpression 的不同方式
  9. 请注意,RetrieveMultipleResponse 包含一个 BusinessEntity 数组。 BusinessEntity 本身非常无用,因此我们将其转换为 DynamicEntity 的列表 - LINQ 在这里真的是你的朋友,对于 CRM 的一些东西,LINQ 派上用场
  10. 注意我们如何检查属性 - de.Properties.Where(p =&gt; p.Name == "systemuserid").FirstOrDefault();,然后检查它是否是 NULL。这是因为如果在 CRM 中记录的属性是 NULL,它将不会从服务调用中返回 - 所以仅仅因为您在 ColumnSet 中请求属性不要自动假设它存在(除非您已在 CRM 中将其设置为强制 - 然后可能没问题)...测试它,您的应用将变得不那么脆弱。
  11. Property 类本身的价值有限 - 要真正使用属性,您必须将其转换为实际存在的东西。我一直在喋喋不休,但 SDK 会告诉你类型是什么,但一段时间后它开始感觉很自然,例如记录的 GUID 在 KeyProperty,整数在 CrmNumberProperty,浮点数在 CrmFloatProperty,字符串在 StringProperty 等。请注意弱类型(我之前提到过),我们必须通过名称,转换为适当的值等

其他要点

  1. 通常情况下,您必须对服务调用非常健谈 - 据我所知,在针对 CRM 进行开发时,这很正常(不过我只能谈谈我自己的经验)
  2. 在编写代码时采取真正的防御措施很重要 - 检查属性是否存在,检查是否正在转换为正确的类型等。
  3. 如果您必须捕获异常,它将是 SoapException,而您通常需要的信息将在 Detail 属性中 - 记住这一点非常重要,否则您会查看异常并认为它不是告诉你一大堆
  4. 咨询 CRM 中的自定义项,以确定关系属性、数据类型等的名称。我喜欢在进行开发时为我需要的实体打开自定义窗口,以便于参考。
  5. FetchXML 非常强大,但非常繁琐。如果你擅长它,那么你会获得很多好的里程 - 像this 这样的工具很有用。此外,还有一个方便的技巧 - 如果您可以通过 CRM UI 构建您想要的(或您想要的示例)作为高级查找,那么您可以使用此 trick 来获取它使用的 FetchXML....您可能需要调整 GUID 等,但如果您想在代码中使用 FetchXML,它会为您提供一个构建块,因为大多数查询都是为您编写的。
  6. 根据您的部署环境,您可能不得不弄乱使用的凭据,是否通过代理等...典型的 Web 参考资料。只是值得注意的是,CRM 也不能幸免于这种事情 - 我在这里没有任何真正的建议,只是一个说明,因为它在过去给我带来了一些“乐趣”

【讨论】:

  • 我目前正在我们的 crm 中实现代码。我假设您使用 crm 使用这些;使用 System.Collections.Generic;使用 System.Linq;我遇到了一个内部授权问题,但一旦解决,我会向您更新结果并将此答案标记为正确。我非常感谢您为回答这个问题所付出的努力。
  • 没问题;是的,没错using System.Collections.Generic 和using System.Linq。我现在没有代码,但我会更新答案以包含控制台应用程序的所有 using 语句 - 抱歉,我最初没有包含这些。
  • 所以我已经实现了代码并根据我的需要对其进行了修改,它运行良好。从这个例子和你对它的深入解释,我从现在开始检索实体应该没有问题,非常感谢。
  • 有一个简单的问题,要检索 nvarchar 值,我将使用什么来代替 CrmNumberProperty hoursAsCrmNumber = hours as CrmNumberProperty;
  • 这是我见过的关于编码问题的最漂亮的答案之一。谢谢 nkvu!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多