• Dynamics CRM 常用 C# 方法集合


    Plugin(C#)

    分派

    AssignRequest assign = new AssignRequest();

                            assign.Assignee = prEntity["ownerid"] as EntityReference;

                            assign.Target = new EntityReference("new_budgetused", new_budgetusedId);

                            _service.Execute(assign);

    共享

    #region 插件中CRM共享共用方法

            /// <summary>

            /// 共享

            /// </summary>

            /// <param name="initentityName">要求共享的实体名称</param>

            /// <param name="userId">要求共享的实体GUID</param>

            /// <param name="entityName">指定共享的实体名称</param>

            /// <param name="entityId">指定共享的实体GUID</param>

            /// <param name="service">CRM组织服务</param>

            private void ShareEntity(string initentityName, Guid userId, string entityName, Guid entityId, IOrganizationService service)

            {

                GrantAccessRequest grant = new GrantAccessRequest();

                grant.PrincipalAccess = new PrincipalAccess

                {

                    //读、写、附加等权限共享

                    AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.AppendAccess,

                    Principal = new EntityReference(initentityName, userId)//共享给某个用户

                };

                grant.Target = new EntityReference(entityName, entityId);//要共享的对象

                service.Execute(grant);

            }

            #endregion

    取消共享

    public void RevokeShareRecords(string LogicName,string targetEntityName,string usedAttrName, IOrganizationService service, Guid targetEntityId,string[] attrs,object[] values,string[] columnSet)

            {

                QueryByAttribute query = new QueryByAttribute(LogicName);

                query.Attributes.AddRange(attrs);

                query.Values.AddRange(values);

                query.ColumnSet = new ColumnSet(columnSet);

                EntityCollection userCollection = service.RetrieveMultiple(query);

                foreach (Entity entity in userCollection.Entities)

                {

                    //Guid AttrId = (Guid)entity.Attributes[SegmentInfo.SystemUserId];

                    Guid UserId = (Guid)entity.Attributes[usedAttrName];

                    EntityReference er = new EntityReference("systemuser", UserId);

                    RevokeAccessRequest revokeAccessRequest = new RevokeAccessRequest {

                        Revokee = new EntityReference("systemuser", UserId),

                        Target = new EntityReference(targetEntityName, targetEntityId)

                    };

                    service.Execute(revokeAccessRequest);

                }

            }

    查询

    string fetchxml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

                                    <entity name='" + objecttype + @"'>

                                        <attribute name='new_name' />

                                        <filter type='and'>

                                            <condition attribute='statecode' operator='eq' value='0' />

                                            <condition attribute='new_name' operator='eq' value='" + name + @"' />

                                        </filter>

                                    </entity>

                                </fetch>";

                EntityCollection entityCollection = service.RetrieveMultiple(new FetchExpression(fetchxml));

    获取最顶级的上下文,用于获取当前操作用户

    public IPluginExecutionContext GetTopContext(IPluginExecutionContext currentContext)

            {

                IPluginExecutionContext topContext = currentContext;

                for (int i = 0; i <= currentContext.Depth; i++)

                {

                    if (topContext.ParentContext != null)

                    {

                        topContext = topContext.ParentContext;

                    }

                }

                return topContext;

            }

    获取sharepoint上的文档

        public static DataCollection<Entity> RetrieveSharepointNotes(IOrganizationService service)

        {

            QueryExpression query = new QueryExpression("annotation")

            {

                //ColumnSet = new ColumnSet(true),

                Criteria =

                {

                    Filters =

                        {

                            new FilterExpression(LogicalOperator.Or)

                            {

                                Conditions =

                                {

                                    new ConditionExpression("subject",ConditionOperator.Equal, "Attachment Error"),

                                },

                                Filters =

                                {

                                    new FilterExpression(LogicalOperator.And)

                                    {

                                        Conditions =

                                        {

                                           new ConditionExpression("subject", ConditionOperator.Equal, "File Attachment"),

                                            new ConditionExpression("notetext", ConditionOperator.Like, "http://spark.partners.extranet.microsoft.com%"),                       

                                        }

                                    }

                                }

                            }

                        }

                }

            };

            EntityCollection ec = service.RetrieveMultiple(query);

            return ec.Entities;

    }

    Query 转化为FetchXML/  FetchXML转化为Query

        public static string ConvertQueryToFetchXml(QueryExpression query, IOrganizationService crmService)

        {

            QueryExpressionToFetchXmlRequest request = new QueryExpressionToFetchXmlRequest();

            request.Query = query;

            QueryExpressionToFetchXmlResponse response

            = (QueryExpressionToFetchXmlResponse)crmService.Execute(request);

            return response.FetchXml;

        }

        public static QueryExpression ConvertFetchXmlToQuery(string fetchXml, IOrganizationService crmService)

        {

            FetchXmlToQueryExpressionRequest fetchXmlRequest = new FetchXmlToQueryExpressionRequest();

            fetchXmlRequest.FetchXml = fetchXml;

            FetchXmlToQueryExpressionResponse fetchXmlResponse

            = (FetchXmlToQueryExpressionResponse)crmService.Execute(fetchXmlRequest);

            return fetchXmlResponse.Query;

        }

    获取optionset字段的显示名

        //string name  = GetPickListText("opportunity", "new_opportunitystate", 0, service);

        public static string GetPickListText(string entityName, string attributeName, int optionSetValue, IOrganizationService service)

        {

            string AttributeName = attributeName;

            string EntityLogicalName = entityName;

            RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest();

            retrieveDetails.EntityFilters = EntityFilters.All;

            retrieveDetails.LogicalName = EntityLogicalName;

            RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);

            EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;

            PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as PicklistAttributeMetadata;

            OptionSetMetadata options = picklistMetadata.OptionSet;

            IList<OptionMetadata> picklistOption = (from o in options.Options where o.Value.Value == optionSetValue select o).ToList();

            string picklistLabel = (picklistOption.First()).Label.UserLocalizedLabel.Label;

            return picklistLabel;

        }

    改变记录的状态

    public static void ChangeRecordState(IOrganizationService service, EntityReference entityMoniker, OptionSetValue state, OptionSetValue status)

        {

            SetStateRequest req = new SetStateRequest

            {

                EntityMoniker = entityMoniker,

                State = state,

                Status = status

            };

            service.Execute(req);

        }

    从template创建邮件

        public static void CreateEmailFromTemplate(IOrganizationService service, EntityCollection sendFromCol, EntityCollection sendToCol, string emailSubject, string previewTriggerVaule, EntityReference regard, Guid contactId, Entity template, string btnOrder)

        {

            if (template != null)

            {

                // Use the InstantiateTemplate message to create an e-mail message using a template.

                InstantiateTemplateRequest instTemplateReq = new InstantiateTemplateRequest

                {

                    TemplateId = template.Id,

                    ObjectId = contactId,

                    ObjectType = "contact"

                };

                InstantiateTemplateResponse instTemplateResp = (InstantiateTemplateResponse)service.Execute(instTemplateReq);

                Entity email = instTemplateResp.EntityCollection.Entities[0];

                email.Attributes["new_campaigninvatationid"] = previewTriggerVaule;

                email.Attributes["subject"] = emailSubject;

                email.Attributes.Add("from", sendFromCol);

                service.Create(email);

            }

        }

    查询N:N记录

    public static EntityCollection RetrieveNNRecords(IOrganizationService service, Guid ToEntityId, string FromEntity, string ToEntity, string RelationShip)

        {

            QueryExpression qe = new QueryExpression()

            {

                EntityName = FromEntity,

                ColumnSet = new ColumnSet(true),

                Criteria =

                {

                    FilterOperator = LogicalOperator.And,

                    Conditions =

                            {

                                new ConditionExpression("statecode",ConditionOperator.Equal,0)

                            }

                },

                LinkEntities =

                        {

                           new LinkEntity()

                           {

                               LinkFromEntityName = FromEntity,

                               LinkToEntityName = RelationShip,

                               LinkFromAttributeName = FromEntity+"id",

                               LinkToAttributeName = FromEntity+"id",

                               EntityAlias = RelationShip,

                               Columns = new ColumnSet(),

                               JoinOperator = JoinOperator.Inner,

                               LinkEntities =

                               {

                                   new LinkEntity()

                                   {

                                       LinkFromEntityName = FromEntity,

                                       LinkToEntityName = ToEntity,

                                       LinkFromAttributeName = ToEntity+"id",

                                       LinkToAttributeName = ToEntity+"id",

                                       EntityAlias =ToEntity,

                                       Columns = new ColumnSet(),

                                       JoinOperator = JoinOperator.Inner,

                                       LinkCriteria = new FilterExpression

                                       {

                                           Conditions =

                                           {

                                               new ConditionExpression

                                               {

                                                   AttributeName = ToEntity+"id",

                                                   Operator = ConditionOperator.Equal,

                                                   Values = {

                                                       ToEntityId

                                                   }

                                               }

                                           }

                                       }

                                   }

                               }

                           }

                        }

            };

            return service.RetrieveMultiple(qe);

        }

    }

    用户是否有指定的security role

    public static bool UserHaveSpeficySecurityRole(IOrganizationService service, string roleName, Guid userID)

            {

                bool result = false;

                QueryExpression query = new QueryExpression()

                {

                    EntityName = "role",

                    ColumnSet = new ColumnSet(),

                    Criteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { newConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { roleName } } } },

                    LinkEntities =

                {

                  new LinkEntity

                  {

                    LinkFromEntityName = "role",

                    LinkFromAttributeName = "roleid",

                    LinkToEntityName = "systemuserroles",

                    LinkToAttributeName = "roleid",

                    LinkCriteria = new FilterExpression

                    {

                      FilterOperator = LogicalOperator.And,

                      Conditions =

                      {

                        new ConditionExpression

                        {

                          AttributeName = "systemuserid",

                          Operator = ConditionOperator.Equal,

                          Values = { userID}

                        }

                      }

                    }

                  }

                }

                };

                EntityCollection resultColl = service.RetrieveMultiple(query);

                result = resultColl.Entities.Count > 0 ? true : false;

                return result;

            }

    查询一条记录分派给哪些用户

    public static List<EntityReference> RetrieveSharedPrincipalsAndAccess(IOrganizationService service, EntityReference entityRef)

            {

                try

                {

                    var accessRequest = new RetrieveSharedPrincipalsAndAccessRequest

                    {

                        Target = entityRef

                    };

                    RetrieveSharedPrincipalsAndAccessResponse accessResponse = (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(accessRequest);

                    List<EntityReference> accessList = null;

                    if (accessResponse != null && accessResponse.PrincipalAccesses.Length > 0)

                    {

                        accessList = new List<EntityReference>();

                        for (int i = 0; i < accessResponse.PrincipalAccesses.Length; i++)

                        {

                            EntityReference accessOwner = accessResponse.PrincipalAccesses[i].Principal;

                            accessList.Add(accessOwner);

                        }

                    }

                    return accessList;

                }

                catch (Exception e)

                {

                    throw new Exception("Customized Plugin RetrieveSharedPrincipalsAndAccess Error: " + e.Message);

                }

            }

    拿到拥有指定security role的所有用户

            public static ArrayList getUsersinRole(string Role_Name, IOrganizationService service)

            {

                ArrayList usersinrole = new ArrayList();

                StringBuilder fetch2 = new StringBuilder();

                fetch2.Append("<fetch mapping='logical' count='50' version='1.0'> ");

                fetch2.Append(" <entity name='systemuser'>");

                fetch2.Append(" <attribute name='fullname'/> ");

                fetch2.Append("     <link-entity name='systemuserroles' to='systemuserid' from='systemuserid'> ");

                fetch2.Append("         <link-entity name='role' to='roleid' from='roleid'> ");

                fetch2.Append("                <filter> ");

                fetch2.Append("                     <condition attribute='name' operator='eq' value='" + Role_Name + "'/> ");

                fetch2.Append("                 </filter> ");

                fetch2.Append("         </link-entity> ");

                fetch2.Append("     </link-entity>");

                fetch2.Append(" </entity> ");

                fetch2.Append("</fetch>");

                EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetch2.ToString()));

                foreach (var c in result.Entities)

                {

                    usersinrole.Add(c.Attributes["fullname"].ToString());

                }

                return usersinrole;

            }

    判断用户是否是某团队的一员

    public bool IsMemberInTeam(IOrganizationService service, Guid teamId, Guid memberId)

            {

                OrganizationServiceContext context = new OrganizationServiceContext(service);

                var query = from relationship in context.CreateQuery("teammembership")

                            where relationship.GetAttributeValue<Guid>("teamid") == teamId

                            && relationship.GetAttributeValue<Guid>("systemuserid") == memberId

                            select relationship;

                return query.FirstOrDefault() != null;

            }

    添加用户到一个团队

    OrganizationRequest request = new AddMembersTeamRequest { MemberIds = new Guid[] { user.Id }, TeamId = team.Id };

                        var response = service.Execute(request) as AddMembersTeamResponse;

    C# 分页查询记录

    public static void DoTest(IOrganizationService service)

            {

                //  Query using the paging cookie.

                // Define the paging attributes.

                // The number of records per page to retrieve.

                int fetchCount = 20;

                // Initialize the page number.

                int pageNumber = 1;

                // Define the order expression to retrieve the records.

                OrderExpression order = new OrderExpression();

                order.AttributeName = "name";

                order.OrderType = OrderType.Ascending;

                // Create the query expression and add condition.

                QueryExpression pagequery = new QueryExpression();

                pagequery.EntityName = "opportunity";

               // pagequery.Criteria.AddCondition(pagecondition);

                pagequery.Orders.Add(order);

                pagequery.ColumnSet.AddColumns();

                // Assign the pageinfo properties to the query expression.

                pagequery.PageInfo = new PagingInfo();

                pagequery.PageInfo.Count = fetchCount;

                pagequery.PageInfo.PageNumber = pageNumber;

                // The current paging cookie. When retrieving the first page,

                // pagingCookie should be null.

                pagequery.PageInfo.PagingCookie = null;

                while (true)

                {

                    // Retrieve the page.

                    EntityCollection results = service.RetrieveMultiple(pagequery);

                    if (results.Entities != null)

                    {

                        for (int i = 0; i < results.Entities.Count;i++ )

                        {

                            Console.WriteLine(" {0} {1}", results.Entities[i].Id, i + 1);

                        }

                       

                    }

                    // Check for more records, if it returns true.

                    if (results.MoreRecords)

                    {

                        // Increment the page number to retrieve the next page.

                        pagequery.PageInfo.PageNumber++;

                        // Set the paging cookie to the paging cookie returned from current results.

                        pagequery.PageInfo.PagingCookie = results.PagingCookie;

                    }

                    else

                    {

                        // If no more records are in the result nodes, exit the loop.

                        break;

                    }

                }

            }

    更新用户所在的业务部门

    SetBusinessSystemUserRequest req = new SetBusinessSystemUserRequest();

               req.BusinessId = Guid.Parse("52A18602-09B8-E511-80C2-807DB137DB06"); BU的GUID

                    req.UserId = Guid.Parse("7F038A46-5BB4-E511-80C6-DD48FB4179EC"); User的GUID

                    req.ReassignPrincipal = new EntityReference("systemuser", Guid.Parse("7F038A46-5BB4-E511-80C6-DD48FB4179EC")); User的GUID

                    service.Execute(req);

  • 相关阅读:
    angularJS实现无刷新文件下载
    入门程序,hello world
    rabbitMQ概念详细介绍
    rabbitMQ安装
    truncate与delete的区别
    Java 并发编程:线程间的协作(wait/notify/sleep/yield/join)
    Java多线程编程:Callable、Future和FutureTask浅析
    定时任务 Crontab命令 详解
    使用Spring Session做分布式会话管理
    AngularJS ui-router (嵌套路由)
  • 原文地址:https://www.cnblogs.com/supersblog/p/5959505.html
Copyright © 2020-2023  润新知