Business Unit Helper

using System;
using System.Linq;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using System.Collections.Generic;
using Microsoft.Xrm.Sdk.Messages;

/// <summary>
/// 操做業務部門
/// </summary>
public class BusinessUnitHelper
{
    public static readonly string entityName = "businessunit";
    public Guid businessunitId = Guid.Empty;

    /// <summary>
    /// 建立業務部門
    /// </summary> 
    public void CreateUnit(IOrganizationService service)
    {
        Entity en = new Entity() { LogicalName = entityName };
        en["name"] = "軟件開發部";
        businessunitId = service.Create(en);
    }

    /// <summary>
    /// 修改業務部門
    /// </summary> 
    public void UpdateUnit(IOrganizationService service)
    {
        Entity en = new Entity() { LogicalName = entityName, Id = businessunitId };
        en["name"] = "軟件開發事業部";
        service.Update(en);
    }

    /// <summary>
    /// 設置業務部門的上級部門
    /// </summary>
    /// <param name="service">服務</param>
    /// <param name="parentId">上級業務部門id</param>
    public void SetParentBusinessUnit(IOrganizationService service, Guid parentId)
    {
        SetParentBusinessUnitRequest request = new SetParentBusinessUnitRequest();
        //當前業務部門id
        request.BusinessUnitId = businessunitId;
        //上級業務部門id
        request.ParentId = parentId;
        service.Execute(request);
    }

    /// <summary>
    /// 檢索業務部門層次結構中的全部業務部門
    /// </summary> 
    public void SearchBusinessUnit(IOrganizationService service)
    {
        RetrieveBusinessHierarchyBusinessUnitRequest request = new RetrieveBusinessHierarchyBusinessUnitRequest();
        request.EntityId = businessunitId;
        request.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("name", "parentbusinessunitid");
        RetrieveBusinessHierarchyBusinessUnitResponse response =
            (RetrieveBusinessHierarchyBusinessUnitResponse)service.Execute(request);
        if (response != null && response.EntityCollection != null)
        {
            List<BusinessUnit> list = new List<BusinessUnit>();
            EntityCollection ecResult = response.EntityCollection;
            int index = 1;
            #region 獲取全部的部門
            foreach (Entity en in ecResult.Entities)
            {
                BusinessUnit unitE = new BusinessUnit();
                unitE.businessUnitId = en.Id;
                unitE.name = en.Contains("name") && en["name"] != null ? en["name"].ToString() : string.Empty;
                if (en.Contains("parentbusinessunitid") && en["parentbusinessunitid"] != null)
                {
                    EntityReference parEr = en["parentbusinessunitid"] as EntityReference;
                    unitE.parentBusinessUnitId = parEr.Id;
                }
                unitE.order = index;

                list.Add(unitE);
                index++;
            }
            #endregion
            #region 重置業務部門的順序
            foreach (BusinessUnit model in list)
            {
                var result = list.Where(a => a.parentBusinessUnitId == a.businessUnitId);
                if (result != null && result.Count() > 0)
                {
                    var parModel = result.FirstOrDefault();
                    if (model.order + 1 != parModel.order)
                    {
                        parModel.order = model.order + 1;
                    }
                }
            }
            #endregion
        }
    }

    public class BusinessUnit
    {
        public Guid businessUnitId { get; set; }
        public string name { get; set; }
        public Guid parentBusinessUnitId { get; set; }
        public int order { get; set; }
    }

    /// <summary>
    /// 添加用戶或者移除用戶
    /// </summary>
    /// <param name="service">服務</param>
    /// <param name="userId">用戶</param>
    public void AddAndRemoveUser(IOrganizationService service, Guid userId)
    {
        //添加用戶
        AddConnection(service, "business_unit_system_users",
            new EntityReference() { LogicalName = "systemuser", Id = userId });
        //移除用戶
        RemoveConnection(service, "business_unit_system_users",
            new EntityReference() { LogicalName = "systemuser", Id = userId });
    }

    /// <summary>
    /// 添加團隊或者移除團隊
    /// </summary>
    /// <param name="service">服務</param>
    /// <param name="teamId">團隊</param>
    public void AddAndRemoveTeam(IOrganizationService service, Guid teamId)
    {
        //添加團隊
        AddConnection(service, "business_unit_teams",
            new EntityReference() { LogicalName = "team", Id = teamId });
        //移除團隊
        RemoveConnection(service, "business_unit_teams",
            new EntityReference() { LogicalName = "team", Id = teamId });
    }

    /// <summary>
    /// 停用或者啓用業務部門
    /// </summary>
    public void SetBusinessUnitState(IOrganizationService service)
    {
        //啓用業務部門
        UpdateState(service, businessunitId, 0, -1);
        //停用業務部門
        UpdateState(service, businessunitId, -1, -1);
    }

    /// <summary>
    /// 刪除業務部門
    /// </summary> 
    public void DeleteUnit(IOrganizationService service)
    {
        service.Delete(entityName, businessunitId);
    }

    private void UpdateState(IOrganizationService service, Guid id, int state, int status)
    {
        SetStateRequest setState = new SetStateRequest()
        {
            EntityMoniker = new EntityReference()
            {
                Id = id,
                LogicalName = entityName
            },
            State = new OptionSetValue(state),
            Status = new OptionSetValue(status)
        };
        service.Execute(setState);
    }

    public void AddConnection(IOrganizationService service, string name, params EntityReference[] array)
    {
        Relationship ship = new Relationship(name);
        AssociateRequest request = new AssociateRequest();
        request.Relationship = ship;
        request.Target = new EntityReference()
        {
            LogicalName = entityName, Id = businessunitId
        };
        request.RelatedEntities = new EntityReferenceCollection();
        request.RelatedEntities.AddRange(array);
        service.Execute(request);
    }

    public void RemoveConnection(IOrganizationService service, string name, params EntityReference[] array)
    {
        Relationship ship = new Relationship(name);
        DisassociateRequest request = new DisassociateRequest();
        request.Relationship = ship; request.Target = new EntityReference()
        {
            LogicalName = entityName,
            Id = businessunitId
        };
        request.RelatedEntities = new EntityReferenceCollection();
        request.RelatedEntities.AddRange(array);
        service.Execute(request);
    }
}
相關文章
相關標籤/搜索