Esempio n. 1
0
        public IEnumerable <Entity> GetMatchingEntities(string type, IDictionary <string, object> fieldValues, string ignoreCacheFor = null)
        {
            var conditions = fieldValues.Select(fv =>
                                                fv.Value == null
                ? new ConditionExpression(fv.Key, ConditionOperator.Null)
                : new ConditionExpression(fv.Key, ConditionOperator.Equal, XrmService.ConvertToQueryValue(fv.Key, type, XrmService.ParseField(fv.Key, type, fv.Value)))
                                                ).ToList();

            var matchFilters = _matchFilters.ContainsKey(type)
                ? _matchFilters[type]
                : new ConditionExpression[0];

            if (type != ignoreCacheFor &&
                conditions.Count == 1 &&
                fieldValues.Values.First() != null)
            {
                CheckLoadCache(new[] { type });
                var fieldName = fieldValues.Keys.First();

                var matchString = XrmService.GetFieldAsMatchString(type, fieldName, fieldValues.Values.First());
                if (!_cachedRecords.ContainsKey(type))
                {
                    _cachedRecords.Add(type, new Dictionary <string, Dictionary <string, List <Entity> > >());
                }
                if (!_cachedRecords[type].ContainsKey(fieldName))
                {
                    var query          = XrmService.BuildQuery(type, null, matchFilters, null);
                    var recordsToCache = XrmService.RetrieveFirstX(query, _maxCacheCount);
                    _cachedRecords[type].Add(fieldName, new Dictionary <string, List <Entity> >());
                    foreach (var item in recordsToCache)
                    {
                        var cacheMatchString = XrmService.GetFieldAsMatchString(type, fieldName, item.GetFieldValue(fieldName));
                        if (!_cachedRecords[type][fieldName].ContainsKey(cacheMatchString))
                        {
                            _cachedRecords[type][fieldName].Add(cacheMatchString, new List <Entity>());
                        }
                        _cachedRecords[type][fieldName][cacheMatchString].Add(item);
                    }
                }
                //only use the cache if there were less than maxRecords
                //otherwise there may be dupicates not included
                if (_cachedRecords[type][fieldName].SelectMany(kv => kv.Value).Count() < _maxCacheCount &&
                    _cachedRecords[type][fieldName].ContainsKey(matchString))
                {
                    return(_cachedRecords[type][fieldName][matchString]);
                }
            }
            return(XrmService.RetrieveAllAndClauses(type, conditions.Union(matchFilters).ToArray(), null));
        }
Esempio n. 2
0
        protected IEnumerable <Entity> GetMatchingEntities(string type, IDictionary <string, object> fieldValues)
        {
            var conditions = fieldValues.Select(fv =>
                                                fv.Value == null
            ? new ConditionExpression(fv.Key, ConditionOperator.Null)
            : new ConditionExpression(fv.Key, ConditionOperator.Equal, XrmService.ConvertToQueryValue(fv.Key, type, XrmService.ParseField(fv.Key, type, fv.Value)))
                                                ).ToList();

            if (type == "workflow")
            {
                conditions.Add(new ConditionExpression("type", ConditionOperator.Equal, XrmPicklists.WorkflowType.Definition));
            }
            if (type == "account" || type == "contact")
            {
                conditions.Add(new ConditionExpression("merged", ConditionOperator.NotEqual, true));
            }
            if (type == "knowledgearticle")
            {
                conditions.Add(new ConditionExpression("islatestversion", ConditionOperator.Equal, true));
            }
            return(XrmService.RetrieveAllAndClauses(type, conditions, new String[0]));
        }
        private Entity GetOrCreate(Dictionary <string, object> theDictionary, IRecurseFieldCreation mappings)
        {
            var targetRecord = new Entity(mappings.TargetType);

            if (mappings.ExplicitValues != null)
            {
                foreach (var field in mappings.ExplicitValues)
                {
                    targetRecord.SetField(field.Name, XrmService.ParseField(field.Name, targetRecord.LogicalName, field.Value));
                }
            }
            foreach (var field in mappings.FieldMappings)
            {
                var type = field.TargetType;
                if (!string.IsNullOrWhiteSpace(type) && field.FieldMappings != null)
                {
                    var got = GetOrCreate(theDictionary, field);
                    targetRecord.SetLookupField(field.Name, got.Id, got.LogicalName);
                }
                else
                {
                    var value = theDictionary.ContainsKey(field.CsvName)
                        ? theDictionary[field.CsvName]
                        : null;
                    targetRecord.SetField(field.Name, XrmService.ParseField(field.Name, targetRecord.LogicalName, value));
                }
            }

            var matchExistingFields = mappings.KeyMappings.ToDictionary(m => m.Name, m => XrmService.ConvertToQueryValue(m.Name, targetRecord.LogicalName, targetRecord.GetField(m.Name)))
                                      .ToDictionary(kv => kv.Key, kv => (object)kv.Value);

            var emptyValues = matchExistingFields.Where(kv => kv.Value == null);

            if (emptyValues.Any())
            {
                throw new NullReferenceException(string.Format("The field {0} on type {1} is required", XrmService.GetFieldLabel(emptyValues.First().Key, targetRecord.LogicalName), XrmService.GetEntityLabel(targetRecord.LogicalName)));
            }

            matchExistingFields.Add("statecode", XrmPicklists.State.Active);
            var matches = GetMatchingEntities(targetRecord.LogicalName, matchExistingFields);

            if (matches.Any())
            {
                targetRecord.Id = matches.First().Id;
            }
            else
            {
                targetRecord.Id = XrmService.Create(targetRecord);
            }

            return(targetRecord);
        }
Esempio n. 4
0
        public QueryExpression GetMatchQueryExpression(Entity thisEntity)
        {
            var thisTypesConfig = XrmRecordService.GetTypeConfigs().GetFor(thisEntity.LogicalName);

            if (thisTypesConfig != null)
            {
                var matchQuery = XrmService.BuildQuery(thisTypesConfig.Type, null, null, null);
                var parentAndUniqueFieldsToMatch = new List <string>();
                if (thisTypesConfig.ParentLookupField != null)
                {
                    parentAndUniqueFieldsToMatch.Add(thisTypesConfig.ParentLookupField);
                }
                if (thisTypesConfig.UniqueChildFields != null)
                {
                    parentAndUniqueFieldsToMatch.AddRange(thisTypesConfig.UniqueChildFields);
                }
                if (!parentAndUniqueFieldsToMatch.Any())
                {
                    throw new Exception($"Type {thisTypesConfig.Type} has a type config but neither of {nameof(TypeConfigs.Config.ParentLookupField)} or {nameof(TypeConfigs.Config.UniqueChildFields)} has fields configured for matching");
                }

                AddUniqueFieldConfigJoins(thisEntity, matchQuery, parentAndUniqueFieldsToMatch);
                return(matchQuery);
            }
            else
            {
                var primaryKey  = XrmService.GetPrimaryKeyField(thisEntity.LogicalName);
                var primaryName = XrmService.GetPrimaryNameField(thisEntity.LogicalName);
                var matchQuery  = XrmService.BuildQuery(thisEntity.LogicalName, null, null, null);
                if (AltMatchKeyDictionary.ContainsKey(thisEntity.LogicalName))
                {
                    var matchKeyFieldDictionary = AltMatchKeyDictionary[thisEntity.LogicalName]
                                                  .Distinct().ToDictionary(f => f, f => thisEntity.GetField(f));

                    foreach (var matchKeyField in matchKeyFieldDictionary)
                    {
                        if (matchKeyField.Value is EntityReference er &&
                            er.Id == Guid.Empty &&
                            !string.IsNullOrWhiteSpace(er.Name) &&
                            !string.IsNullOrWhiteSpace(er.LogicalName) &&
                            XrmService.EntityExists(er.LogicalName))
                        {
                            var linkTo = matchQuery.AddLink(er.LogicalName, matchKeyField.Key, XrmService.GetPrimaryKeyField(er.LogicalName));
                            linkTo.LinkCriteria.AddCondition(new ConditionExpression(XrmService.GetPrimaryNameField(er.LogicalName), ConditionOperator.Equal, er.Name));
                        }
                        else
                        {
                            matchQuery.Criteria.Conditions.Add(new ConditionExpression(matchKeyField.Key, ConditionOperator.Equal, XrmService.ConvertToQueryValue(matchKeyField.Key, thisEntity.LogicalName, matchKeyField.Value)));
                        }
                    }
                }
        private void AddReferenceConfigJoins(LinkEntity linkToReferenced, Entity thisEntity, string field)
        {
            var referencedType       = XrmEntity.GetLookupType(thisEntity.GetFieldValue(field));
            var referencedTypeConfig = XrmRecordService.GetTypeConfigs().GetFor(referencedType);

            if (referencedTypeConfig != null && referencedTypeConfig.UniqueChildFields != null)
            {
                foreach (var uniqueField in referencedTypeConfig.UniqueChildFields)
                {
                    var theValue = thisEntity.GetFieldValue($"{field}.{uniqueField}");
                    if (theValue == null)
                    {
                        linkToReferenced.LinkCriteria.AddCondition(new ConditionExpression(uniqueField, ConditionOperator.Null));
                    }
                    else if (theValue is EntityReference)
                    {
                        var name = XrmEntity.GetLookupName(theValue);
                        var type = XrmEntity.GetLookupType(theValue);
                        var nextLinkToReferenced = linkToReferenced.AddLink(type, uniqueField, XrmService.GetPrimaryKeyField(type));
                        if (name == null)
                        {
                            nextLinkToReferenced.LinkCriteria.AddCondition(XrmService.GetPrimaryNameField(type), ConditionOperator.Null);
                        }
                        else
                        {
                            nextLinkToReferenced.LinkCriteria.AddCondition(XrmService.GetPrimaryNameField(type), ConditionOperator.Equal, name);
                            AddReferenceConfigJoins(nextLinkToReferenced, thisEntity, $"{field}.{uniqueField}");
                        }
                    }
                    else
                    {
                        linkToReferenced.LinkCriteria.AddCondition(new ConditionExpression(uniqueField, ConditionOperator.Equal, XrmService.ConvertToQueryValue(uniqueField, referencedType, theValue)));
                    }
                }
            }
        }
 public void AddUniqueFieldConfigJoins(Entity thisEntity, QueryExpression matchQuery, IEnumerable <string> uniqueFields, string prefixFieldInEntity = null)
 {
     foreach (var field in uniqueFields)
     {
         var theValue = thisEntity.GetFieldValue(prefixFieldInEntity + field);
         if (theValue == null)
         {
             matchQuery.Criteria.AddCondition(new ConditionExpression(field, ConditionOperator.Null));
         }
         else if (theValue is EntityReference)
         {
             var name             = XrmEntity.GetLookupName(theValue);
             var type             = XrmEntity.GetLookupType(theValue);
             var linkToReferenced = matchQuery.AddLink(type, field, XrmService.GetPrimaryKeyField(type));
             if (name == null)
             {
                 linkToReferenced.LinkCriteria.AddCondition(XrmService.GetPrimaryNameField(type), ConditionOperator.Null);
             }
             else
             {
                 linkToReferenced.LinkCriteria.AddCondition(XrmService.GetPrimaryNameField(type), ConditionOperator.Equal, name);
                 if (ContainsExportedConfigFields)
                 {
                     AddReferenceConfigJoins(linkToReferenced, thisEntity, field);
                 }
             }
         }
         else
         {
             matchQuery.Criteria.AddCondition(new ConditionExpression(field, ConditionOperator.Equal, XrmService.ConvertToQueryValue(field, matchQuery.EntityName, theValue)));
         }
     }
 }
        public QueryExpression GetMatchQueryExpression(Entity thisEntity)
        {
            var thisTypesConfig = XrmRecordService.GetTypeConfigs().GetFor(thisEntity.LogicalName);

            if (thisTypesConfig != null)
            {
                var matchQuery = XrmService.BuildQuery(thisTypesConfig.Type, null, null, null);
                var parentAndUniqueFieldsToMatch = new List <string>();
                if (thisTypesConfig.ParentLookupField != null)
                {
                    parentAndUniqueFieldsToMatch.Add(thisTypesConfig.ParentLookupField);
                }
                if (thisTypesConfig.UniqueChildFields != null)
                {
                    parentAndUniqueFieldsToMatch.AddRange(thisTypesConfig.UniqueChildFields);
                }
                if (!parentAndUniqueFieldsToMatch.Any())
                {
                    throw new Exception($"Type {thisTypesConfig.Type} has a type config but neither of {nameof(TypeConfigs.Config.ParentLookupField)} or {nameof(TypeConfigs.Config.UniqueChildFields)} has fields configured for matching");
                }

                AddUniqueFieldConfigJoins(thisEntity, matchQuery, parentAndUniqueFieldsToMatch);
                return(matchQuery);
            }
            else
            {
                var primaryKey  = XrmService.GetPrimaryKeyField(thisEntity.LogicalName);
                var primaryName = XrmService.GetPrimaryNameField(thisEntity.LogicalName);
                var matchQuery  = XrmService.BuildQuery(thisEntity.LogicalName, null, null, null);
                if (AltMatchKeyDictionary.ContainsKey(thisEntity.LogicalName))
                {
                    var matchKeyFieldDictionary = AltMatchKeyDictionary[thisEntity.LogicalName]
                                                  .Distinct().ToDictionary(f => f, f => thisEntity.GetField(f));
                    matchQuery.Criteria.Conditions.AddRange(matchKeyFieldDictionary.Select(kv =>
                                                                                           new ConditionExpression(kv.Key, ConditionOperator.Equal, XrmService.ConvertToQueryValue(kv.Key, thisEntity.LogicalName, kv.Value))));
                }
                else if (MatchOption == MatchOption.PrimaryKeyThenName || thisTypesConfig != null)
                {
                    matchQuery.Criteria.FilterOperator = LogicalOperator.Or;
                    matchQuery.Criteria.Conditions.Add(
                        new ConditionExpression(primaryKey, ConditionOperator.Equal, thisEntity.Id));
                    if (primaryName != null && thisEntity.GetStringField(primaryName) != null)
                    {
                        matchQuery.Criteria.Conditions.Add(
                            new ConditionExpression(primaryName, ConditionOperator.Equal, thisEntity.GetStringField(primaryName)));
                    }
                }
                else if (MatchOption == MatchOption.PrimaryKeyOnly)
                {
                    matchQuery.Criteria.Conditions.Add(
                        new ConditionExpression(primaryKey, ConditionOperator.Equal, thisEntity.Id));
                }
                return(matchQuery);
            }
        }