using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Xrm.Sdk; namespace XrmTools { public class XrmTools { public static List References { get; set; } private static string[] entityNames = null; public static string[] EntityNames { get { if (entityNames == null) { entityNames = EntityUtility.ReadEntityNames(); } return entityNames; } } public static bool CheckReference(Guid referenceId, Entity entity) { if (entity.Id == referenceId) return false; foreach (var value in entity.Attributes) { switch (value.Value.GetType().Name) { case "Guid": if ((Guid)value.Value == referenceId) { return true; } break; case "EntityReference": if (((EntityReference)value.Value).Id == referenceId) { return true; } break; case "EntityCollection": foreach (Entity innerEntity in ((EntityCollection)value.Value).Entities) { if (CheckReference(referenceId, innerEntity)) { return true; } } break; } } return false; } public static bool CheckReference(Guid referenceId, EntityCollection collection) { bool ret = false; foreach (Entity entity in collection.Entities) { if (CheckReference(referenceId, entity)) { References.Add(new EntityLink(entity.LogicalName, entity.Id)); ret = true; return true; } } return ret; } public static List CheckReference(string logicalName, Guid guid) { try { References = new List(); Entity referenceEntity = EntityUtility.ReadEntity(logicalName, guid); string[] entities = EntityNames; foreach (string entity in entities) { Debug.WriteLine(entity); EntityCollection collection = EntityUtility.ReadEntities(entity); CheckReference(referenceEntity.Id, collection); } } catch (Exception ex) { Debug.WriteLine(string.Format("Entity not found: {0}", ex.Message)); return null; } return References; } public static List CheckReference(Entity entity) { return CheckReference(entity.LogicalName, entity.Id); } } }