private IRecord GetRecordToDeployInto(string recordType, string nameToMatch, string containingFolderParentName)
        {
            nameToMatch = nameToMatch?.Replace("∕", "/");

            var conditions = new List <Condition>
            {
                new Condition(Service.GetPrimaryField(recordType), ConditionType.Equal, nameToMatch)
            };

            if (recordType == Entities.adx_webpage)
            {
                conditions.Add(new Condition(Fields.adx_webpage_.adx_rootwebpageid, ConditionType.NotNull));
            }

            IRecord matchingRecord  = null;
            var     matchingRecords = Service.RetrieveAllAndClauses(recordType, conditions);

            if (matchingRecords.Count() == 0)
            {
                throw new NullReferenceException($"Could not find {Service.GetDisplayName(recordType)} named {nameToMatch} to update");
            }
            else if (matchingRecords.Count() == 1)
            {
                matchingRecord = matchingRecords.First();
            }
            else
            {
                if (containingFolderParentName == null)
                {
                    throw new NullReferenceException($"There are multiple {Service.GetCollectionName(recordType)} named {nameToMatch} and the parents parent folder does not provide the name of a {Service.GetDisplayName(Entities.adx_website)} to deploy into");
                }
                else
                {
                    var websiteLookupFields = Service
                                              .GetFields(recordType)
                                              .Where(f => Service.GetLookupTargetType(f, recordType) == Entities.adx_website)
                                              .ToArray();
                    if (websiteLookupFields.Count() != 1)
                    {
                        throw new NullReferenceException($"There are multiple {Service.GetCollectionName(recordType)} named {nameToMatch} but the type does not contain 1 lookup field referencing the {Service.GetDisplayName(Entities.adx_website)} to deploy into");
                    }
                    var websiteFieldName = websiteLookupFields.First();
                    matchingRecords = matchingRecords.Where(r => r.GetLookupName(websiteFieldName)?.ToLower() == containingFolderParentName.ToLower());
                    if (matchingRecords.Count() == 0)
                    {
                        throw new NullReferenceException($"There are multiple {Service.GetCollectionName(recordType)} named {nameToMatch} but none of them are linked to a {Service.GetDisplayName(Entities.adx_website)} named {containingFolderParentName}");
                    }
                    if (matchingRecords.Count() > 1)
                    {
                        throw new NullReferenceException($"There are multiple {Service.GetCollectionName(recordType)} named {nameToMatch} linked to a {Service.GetDisplayName(Entities.adx_website)} named {containingFolderParentName}");
                    }
                    matchingRecord = matchingRecords.First();
                }
            }

            return(matchingRecord);
        }
            private void LoadComponentItems(IEnumerable <string> ids, XrmRecordService xrmRecordService)
            {
                if (ComponentTypeKey == OptionSets.SolutionComponent.ObjectTypeCode.Entity)
                {
                    AllItems = xrmRecordService
                               .GetAllRecordTypes()
                               .Select(r => xrmRecordService.GetRecordTypeMetadata(r))
                               .Where(m => ids.Contains(m.MetadataId))
                               .Select(m => new AddToSolutionComponentItem(m.MetadataId, m.DisplayName))
                               .ToArray();
                }
                else if (ComponentTypeKey == OptionSets.SolutionComponent.ObjectTypeCode.OptionSet)
                {
                    AllItems = xrmRecordService
                               .GetSharedPicklists()
                               .Where(m => ids.Contains(m.MetadataId))
                               .Select(m => new AddToSolutionComponentItem(m.MetadataId, m.DisplayName))
                               .ToArray();
                }
                else
                {
                    var propTypeMaps = new Dictionary <int, string>();
                    propTypeMaps.Add(OptionSets.SolutionComponent.ObjectTypeCode.SystemForm, Entities.systemform);
                    propTypeMaps.Add(OptionSets.SolutionComponent.ObjectTypeCode.EmailTemplate, Entities.template);
                    propTypeMaps.Add(OptionSets.SolutionComponent.ObjectTypeCode.PluginAssembly, Entities.pluginassembly);
                    propTypeMaps.Add(OptionSets.SolutionComponent.ObjectTypeCode.SDKMessageProcessingStep, Entities.sdkmessageprocessingstep);
                    propTypeMaps.Add(OptionSets.SolutionComponent.ObjectTypeCode.Report, Entities.report);
                    propTypeMaps.Add(OptionSets.SolutionComponent.ObjectTypeCode.Role, Entities.role);
                    propTypeMaps.Add(OptionSets.SolutionComponent.ObjectTypeCode.WebResource, Entities.webresource);
                    propTypeMaps.Add(OptionSets.SolutionComponent.ObjectTypeCode.Workflow, Entities.workflow);
                    if (!propTypeMaps.ContainsKey(ComponentTypeKey))
                    {
                        throw new NotImplementedException($"Component Type {ComponentTypeKey} Is Not Implemented");
                    }

                    var recordType      = propTypeMaps[ComponentTypeKey];
                    var primaryKeyField = xrmRecordService.GetPrimaryKey(recordType);
                    var nameField       = xrmRecordService.GetPrimaryField(recordType);

                    AllItems = xrmRecordService
                               .RetrieveAllOrClauses(recordType, ids.Select(i => new Condition(primaryKeyField, ConditionType.Equal, i)))
                               .Select(e => new AddToSolutionComponentItem(e.Id, e.GetStringField(nameField)))
                               .OrderBy(c => c.Name)
                               .ToArray();
                }

                ItemsSelection = AllItems
                                 .Select(i => new SelectableAddToSolutionComponentItem(i.Id, i.Name))
                                 .ToArray();
            }
Esempio n. 3
0
        public static IEnumerable <string> GetComparisonFieldsFor(string type, XrmRecordService xrmRecordService)
        {
            var config = GetFor(type);
            var fields = new List <string>();

            if (config != null)
            {
                if (config.ParentLookupField != null)
                {
                    fields.Add(config.ParentLookupField);
                }
                if (config.UniqueChildFields != null)
                {
                    fields.AddRange(config.UniqueChildFields);
                }
                var parentComparisonFields = GetParentFieldsRequiredForComparison(type);
                if (parentComparisonFields != null)
                {
                    fields.AddRange(parentComparisonFields.Select(pc => config.ParentLookupField + "." + pc));
                }
            }
            fields.Add(xrmRecordService.GetPrimaryField(type));
            return(fields);
        }
        private void WriteToXml(Entity entity, string folder, bool association)
        {
            var lateBoundSerializer = new DataContractSerializer(typeof(Entity));
            var namesToUse          = association ? "association" : entity.GetStringField(XrmRecordService.GetPrimaryField(entity.LogicalName).Left(15));

            if (!namesToUse.IsNullOrWhiteSpace())
            {
                var invalidChars = Path.GetInvalidFileNameChars();
                foreach (var character in invalidChars)
                {
                    namesToUse = namesToUse.Replace(character, '_');
                }
            }
            var fileName = string.Format(@"{0}_{1}_{2}", entity.LogicalName, entity.Id, namesToUse);

            fileName = fileName.Replace('-', '_');
            //ensure dont exceed max filename length
            fileName = string.Format(@"{0}\{1}", folder, fileName).Left(240);
            fileName = fileName + ".xml";
            using (var fileStream = new FileStream(fileName, FileMode.Create))
            {
                lateBoundSerializer.WriteObject(fileStream, entity);
            }
        }
Esempio n. 5
0
        public IEnumerable <DataImportResponseItem> DoImport(IEnumerable <Entity> entities, LogController controller, bool maskEmails)
        {
            controller.LogLiteral("Preparing Import");
            var response = new List <DataImportResponseItem>();

            var fieldsToRetry = new Dictionary <Entity, List <string> >();
            var typesToImport = entities.Select(e => e.LogicalName).Distinct();

            var allNNRelationships = XrmService.GetAllNnRelationshipEntityNames();
            var associationTypes   = typesToImport.Where(allNNRelationships.Contains).ToArray();

            typesToImport = typesToImport.Where(t => !associationTypes.Contains(t)).ToArray();

            var orderedTypes = new List <string>();

            var idSwitches = new Dictionary <string, Dictionary <Guid, Guid> >();

            foreach (var item in typesToImport)
            {
                idSwitches.Add(item, new Dictionary <Guid, Guid>());
            }

            #region tryordertypes

            foreach (var type in typesToImport)
            {
                foreach (var type2 in orderedTypes)
                {
                    var thatType         = type2;
                    var thatTypeEntities = entities.Where(e => e.LogicalName == thatType).ToList();
                    var fields           = GetFieldsToImport(thatTypeEntities, thatType)
                                           .Where(f => XrmService.FieldExists(f, thatType) && XrmService.IsLookup(f, thatType));

                    foreach (var field in fields)
                    {
                        if (thatTypeEntities.Any(e => e.GetLookupType(field) == type))
                        {
                            orderedTypes.Insert(orderedTypes.IndexOf(type2), type);
                            break;
                        }
                    }
                    if (orderedTypes.Contains(type))
                    {
                        break;
                    }
                }
                if (!orderedTypes.Contains(type))
                {
                    orderedTypes.Add(type);
                }
            }

            #endregion tryordertypes

            var countToImport = orderedTypes.Count;
            var countImported = 0;
            foreach (var recordType in orderedTypes)
            {
                try
                {
                    var thisRecordType = recordType;
                    controller.UpdateProgress(countImported++, countToImport, string.Format("Importing {0} Records", recordType));
                    var primaryField     = XrmService.GetPrimaryNameField(recordType);
                    var thisTypeEntities = entities.Where(e => e.LogicalName == recordType).ToList();

                    var orConditions = thisTypeEntities
                                       .Select(
                        e =>
                        new ConditionExpression(XrmService.GetPrimaryKeyField(e.LogicalName),
                                                ConditionOperator.Equal, e.Id))
                                       .ToArray();
                    var existingEntities = XrmService.RetrieveAllOrClauses(recordType, orConditions);

                    var orderedEntities = new List <Entity>();

                    #region tryorderentities

                    var importFieldsForEntity = GetFieldsToImport(thisTypeEntities, recordType).ToArray();
                    var fieldsDontExist       = GetFieldsInEntities(thisTypeEntities)
                                                .Where(f => !XrmService.FieldExists(f, thisRecordType))
                                                .Where(f => !HardcodedIgnoreFields.Contains(f))
                                                .Distinct()
                                                .ToArray();
                    foreach (var field in fieldsDontExist)
                    {
                        response.Add(
                            new DataImportResponseItem(recordType, field, null,
                                                       string.Format("Field {0} On Entity {1} Doesn't Exist In Target Instance And Will Be Ignored", field, recordType),
                                                       new NullReferenceException(string.Format("Field {0} On Entity {1} Doesn't Exist In Target Instance And Will Be Ignored", field, recordType))));
                    }

                    var selfReferenceFields = importFieldsForEntity.Where(
                        f =>
                        XrmService.IsLookup(f, recordType) &&
                        XrmService.GetLookupTargetEntity(f, recordType) == recordType).ToArray();

                    foreach (var entity in thisTypeEntities)
                    {
                        foreach (var entity2 in orderedEntities)
                        {
                            if (selfReferenceFields.Any(f => entity2.GetLookupGuid(f) == entity.Id || (entity2.GetLookupGuid(f) == Guid.Empty && entity2.GetLookupName(f) == entity.GetStringField(primaryField))))
                            {
                                orderedEntities.Insert(orderedEntities.IndexOf(entity2), entity);
                                break;
                            }
                        }
                        if (!orderedEntities.Contains(entity))
                        {
                            orderedEntities.Add(entity);
                        }
                    }

                    #endregion tryorderentities
                    var countRecordsToImport = orderedEntities.Count;
                    var countRecordsImported = 0;
                    foreach (var entity in orderedEntities)
                    {
                        var thisEntity = entity;
                        try
                        {
                            controller.UpdateLevel2Progress(countRecordsImported++, countRecordsToImport, string.Format("Importing {0} Records", recordType));
                            var existingMatchingIds = GetMatchForExistingRecord(existingEntities, thisEntity);
                            if (existingMatchingIds.Any())
                            {
                                var matchRecord = existingMatchingIds.First();
                                idSwitches[recordType].Add(thisEntity.Id, matchRecord.Id);
                                thisEntity.Id = matchRecord.Id;
                                thisEntity.SetField(XrmService.GetPrimaryKeyField(thisEntity.LogicalName), thisEntity.Id);
                            }
                            var isUpdate = existingMatchingIds.Any();
                            foreach (var field in thisEntity.GetFieldsInEntity().ToArray())
                            {
                                if (importFieldsForEntity.Contains(field) &&
                                    XrmService.IsLookup(field, thisEntity.LogicalName) &&
                                    thisEntity.GetField(field) != null)
                                {
                                    var idNullable = thisEntity.GetLookupGuid(field);
                                    if (idNullable.HasValue)
                                    {
                                        var targetTypesToTry = GetTargetTypesToTry(thisEntity, field);
                                        var name             = thisEntity.GetLookupName(field);
                                        var fieldResolved    = false;
                                        foreach (var lookupEntity in targetTypesToTry)
                                        {
                                            var targetPrimaryKey   = XrmRecordService.GetPrimaryKey(lookupEntity);
                                            var targetPrimaryField = XrmRecordService.GetPrimaryField(lookupEntity);
                                            var matchRecord        = XrmService.GetFirst(lookupEntity, targetPrimaryKey,
                                                                                         idNullable.Value);
                                            if (matchRecord != null)
                                            {
                                                thisEntity.SetLookupField(field, matchRecord);
                                                fieldResolved = true;
                                            }
                                            else
                                            {
                                                var matchRecords = name.IsNullOrWhiteSpace() ?
                                                                   new Entity[0] :
                                                                   GetMatchingEntities(lookupEntity,
                                                                                       targetPrimaryField,
                                                                                       name);
                                                if (matchRecords.Count() == 1)
                                                {
                                                    thisEntity.SetLookupField(field, matchRecords.First());
                                                    fieldResolved = true;
                                                }
                                            }
                                            if (!fieldResolved)
                                            {
                                                if (!fieldsToRetry.ContainsKey(thisEntity))
                                                {
                                                    fieldsToRetry.Add(thisEntity, new List <string>());
                                                }
                                                fieldsToRetry[thisEntity].Add(field);
                                            }
                                        }
                                    }
                                }
                            }
                            var fieldsToSet = new List <string>();
                            fieldsToSet.AddRange(thisEntity.GetFieldsInEntity()
                                                 .Where(importFieldsForEntity.Contains));
                            if (fieldsToRetry.ContainsKey(thisEntity))
                            {
                                fieldsToSet.RemoveAll(f => fieldsToRetry[thisEntity].Contains(f));
                            }

                            if (maskEmails)
                            {
                                var emailFields = new[] { "emailaddress1", "emailaddress2", "emailaddress3" };
                                foreach (var field in emailFields)
                                {
                                    var theEmail = thisEntity.GetStringField(field);
                                    if (!string.IsNullOrWhiteSpace(theEmail))
                                    {
                                        thisEntity.SetField(field, theEmail.Replace("@", "_AT_") + "*****@*****.**");
                                    }
                                }
                            }

                            if (isUpdate)
                            {
                                var existingRecord = existingMatchingIds.First();
                                XrmService.Update(thisEntity, fieldsToSet.Where(f => !XrmEntity.FieldsEqual(existingRecord.GetField(f), thisEntity.GetField(f))));
                            }
                            else
                            {
                                PopulateRequiredCreateFields(fieldsToRetry, thisEntity, fieldsToSet);
                                CheckThrowValidForCreate(thisEntity, fieldsToSet);
                                thisEntity.Id = XrmService.Create(thisEntity, fieldsToSet);
                            }
                            if (!isUpdate && thisEntity.GetOptionSetValue("statecode") > 0)
                            {
                                XrmService.SetState(thisEntity, thisEntity.GetOptionSetValue("statecode"), thisEntity.GetOptionSetValue("statuscode"));
                            }
                            else if (isUpdate && existingMatchingIds.Any())
                            {
                                var matchRecord = existingMatchingIds.First();
                                var thisState   = thisEntity.GetOptionSetValue("statecode");
                                var thisStatus  = thisEntity.GetOptionSetValue("statuscode");
                                var matchState  = matchRecord.GetOptionSetValue("statecode");
                                var matchStatus = matchRecord.GetOptionSetValue("statuscode");
                                if ((thisState != -1 && thisState != matchState) ||
                                    (thisStatus != -1 && thisState != matchStatus))
                                {
                                    XrmService.SetState(thisEntity, thisEntity.GetOptionSetValue("statecode"), thisEntity.GetOptionSetValue("statuscode"));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            if (fieldsToRetry.ContainsKey(thisEntity))
                            {
                                fieldsToRetry.Remove(thisEntity);
                            }
                            response.Add(
                                new DataImportResponseItem(recordType, null, entity.GetStringField(primaryField),
                                                           string.Format("Error Importing Record Id={0}", entity.Id),
                                                           ex));
                        }
                    }
                }
                catch (Exception ex)
                {
                    response.Add(
                        new DataImportResponseItem(recordType, null, null, string.Format("Error Importing Type {0}", recordType), ex));
                }
            }
            controller.TurnOffLevel2();
            countToImport = fieldsToRetry.Count;
            countImported = 0;
            foreach (var item in fieldsToRetry)
            {
                var thisEntity = item.Key;
                controller.UpdateProgress(countImported++, countToImport, string.Format("Retrying Unresolved Fields {0}", thisEntity.LogicalName));
                var thisPrimaryField = XrmService.GetPrimaryNameField(thisEntity.LogicalName);
                try
                {
                    foreach (var field in item.Value)
                    {
                        if (XrmService.IsLookup(field, thisEntity.LogicalName) && thisEntity.GetField(field) != null)
                        {
                            try
                            {
                                var targetTypesToTry = GetTargetTypesToTry(thisEntity, field);
                                var name             = thisEntity.GetLookupName(field);
                                var idNullable       = thisEntity.GetLookupGuid(field);
                                var fieldResolved    = false;
                                foreach (var lookupEntity in targetTypesToTry)
                                {
                                    var targetPrimaryKey   = XrmRecordService.GetPrimaryKey(lookupEntity);
                                    var targetPrimaryField = XrmRecordService.GetPrimaryField(lookupEntity);
                                    var matchRecord        = idNullable.HasValue ? XrmService.GetFirst(lookupEntity, targetPrimaryKey,
                                                                                                       idNullable.Value) : null;
                                    if (matchRecord != null)
                                    {
                                        thisEntity.SetLookupField(field, matchRecord);
                                        fieldResolved = true;
                                    }
                                    else
                                    {
                                        var matchRecords = name.IsNullOrWhiteSpace() ?
                                                           new Entity[0] :
                                                           GetMatchingEntities(lookupEntity,
                                                                               targetPrimaryField,
                                                                               name);
                                        if (matchRecords.Count() == 1)
                                        {
                                            thisEntity.SetLookupField(field, matchRecords.First());
                                            fieldResolved = true;
                                        }
                                    }
                                    if (!fieldResolved)
                                    {
                                        throw new Exception(string.Format("Could not find matching record for field {0}.{1} {2}", thisEntity.LogicalName, field, name));
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                if (thisEntity.Contains(field))
                                {
                                    thisEntity.Attributes.Remove(field);
                                }
                                response.Add(
                                    new DataImportResponseItem(thisEntity.LogicalName, field, thisEntity.GetStringField(thisPrimaryField),
                                                               string.Format("Error Setting Lookup Field Id={0}", thisEntity.Id), ex));
                            }
                        }
                    }
                    XrmService.Update(thisEntity, item.Value);
                }
                catch (Exception ex)
                {
                    response.Add(
                        new DataImportResponseItem(thisEntity.LogicalName, null, thisEntity.GetStringField(thisPrimaryField),
                                                   string.Format("Error Importing Record Id={0}", thisEntity.Id),
                                                   ex));
                }
            }
            countToImport = associationTypes.Count();
            countImported = 0;
            foreach (var relationshipEntityName in associationTypes)
            {
                var thisEntityName = relationshipEntityName;
                controller.UpdateProgress(countImported++, countToImport, string.Format("Associating {0} Records", thisEntityName));
                var thisTypeEntities     = entities.Where(e => e.LogicalName == thisEntityName).ToList();
                var countRecordsToImport = thisTypeEntities.Count;
                var countRecordsImported = 0;
                foreach (var thisEntity in thisTypeEntities)
                {
                    try
                    {
                        controller.UpdateLevel2Progress(countRecordsImported++, countRecordsToImport, string.Format("Associating {0} Records", thisEntityName));
                        var relationship = XrmService.GetRelationshipMetadataForEntityName(thisEntityName);
                        var type1        = relationship.Entity1LogicalName;
                        var field1       = relationship.Entity1IntersectAttribute;
                        var type2        = relationship.Entity2LogicalName;
                        var field2       = relationship.Entity2IntersectAttribute;

                        //bit of hack
                        //when importing from csv just set the fields to the string name of the referenced record
                        //so either string when csv or guid when xml import/export
                        var value1 = thisEntity.GetField(relationship.Entity1IntersectAttribute);
                        var id1    = value1 is string
                                     ?GetUniqueMatchingEntity(type1, XrmRecordService.GetPrimaryField(type1), (string)value1).Id
                                     : thisEntity.GetGuidField(relationship.Entity1IntersectAttribute);

                        var value2 = thisEntity.GetField(relationship.Entity2IntersectAttribute);
                        var id2    = value2 is string
                                     ?GetUniqueMatchingEntity(type2, XrmRecordService.GetPrimaryField(type2), (string)value2).Id
                                     : thisEntity.GetGuidField(relationship.Entity2IntersectAttribute);

                        //add a where field lookup reference then look it up
                        if (idSwitches.ContainsKey(type1) && idSwitches[type1].ContainsKey(id1))
                        {
                            id1 = idSwitches[type1][id1];
                        }
                        if (idSwitches.ContainsKey(type2) && idSwitches[type2].ContainsKey(id2))
                        {
                            id2 = idSwitches[type2][id2];
                        }
                        XrmService.AssociateSafe(relationship.SchemaName, type1, field1, id1, type2, field2, new[] { id2 });
                    }
                    catch (Exception ex)
                    {
                        response.Add(
                            new DataImportResponseItem(
                                string.Format("Error Associating Record Of Type {0} Id {1}", thisEntity.LogicalName,
                                              thisEntity.Id),
                                ex));
                    }
                }
            }
            return(response);
        }
Esempio n. 6
0
        public void DeploymentCreateAndDeployPackageModuleTest()
        {
            DeleteAll(Entities.account);
            DeleteAll(Entities.contact);

            var account  = CreateAccount();
            var solution = XrmRecordService.GetFirst("solution", XrmRecordService.GetPrimaryField("solution"), "Test Components");

            Assert.IsNotNull(solution);

            FileUtility.DeleteFiles(TestingFolder);

            var createDeploymentPackageRequest = new CreatePackageRequest();

            createDeploymentPackageRequest.FolderPath            = new Folder(TestingFolder);
            createDeploymentPackageRequest.Solution              = solution.ToLookup();
            createDeploymentPackageRequest.ThisReleaseVersion    = "3.0.0.0";
            createDeploymentPackageRequest.SetVersionPostRelease = "4.0.0.0";
            createDeploymentPackageRequest.DataToInclude         = new[]
            {
                new ExportRecordType()
                {
                    RecordType = new RecordType(Entities.account, Entities.account), Type = ExportType.AllRecords,
                },
                new ExportRecordType()
                {
                    RecordType = new RecordType(Entities.contact, Entities.contact), Type = ExportType.AllRecords
                }
            };
            var createApplication = CreateAndLoadTestApplication <CreatePackageModule>();
            var response          = createApplication.NavigateAndProcessDialog <CreatePackageModule, CreatePackageDialog, ServiceResponseBase <DataImportResponseItem> >(createDeploymentPackageRequest);

            Assert.IsFalse(response.HasError);

            Assert.IsTrue(FileUtility.GetFiles(TestingFolder).First().EndsWith(".zip"));
            Assert.IsTrue(FileUtility.GetFolders(TestingFolder).First().EndsWith("Data"));
            Assert.IsTrue(FileUtility.GetFiles((FileUtility.GetFolders(TestingFolder).First())).Any());

            solution = XrmRecordService.Get(solution.Type, solution.Id);
            Assert.AreEqual("4.0.0.0", solution.GetStringField(Fields.solution_.version));

            //delete for recreation
            XrmService.Delete(account);

            //Okay now lets deploy it
            var deployRequest = new DeployPackageRequest();

            deployRequest.FolderContainingPackage = new Folder(TestingFolder);
            deployRequest.Connection = GetSavedXrmRecordConfiguration();

            var deployApplication = CreateAndLoadTestApplication <DeployPackageModule>();

            response = deployApplication.NavigateAndProcessDialog <DeployPackageModule, DeployPackageDialog, ServiceResponseBase <DataImportResponseItem> >(deployRequest);
            Assert.IsFalse(response.HasError);

            solution = XrmRecordService.Get(solution.Type, solution.Id);
            Assert.AreEqual("3.0.0.0", solution.GetStringField(Fields.solution_.version));

            //should be recreated
            account = Refresh(account);

            createDeploymentPackageRequest                       = new CreatePackageRequest();
            createDeploymentPackageRequest.FolderPath            = new Folder(TestingFolder);
            createDeploymentPackageRequest.Solution              = solution.ToLookup();
            createDeploymentPackageRequest.ThisReleaseVersion    = "3.0.0.0";
            createDeploymentPackageRequest.SetVersionPostRelease = "4.0.0.0";
            createDeploymentPackageRequest.DeployPackageInto     = GetSavedXrmRecordConfiguration();
            createDeploymentPackageRequest.DataToInclude         = new[]
            {
                new ExportRecordType()
                {
                    RecordType = new RecordType(Entities.account, Entities.account), Type = ExportType.AllRecords
                },
                new ExportRecordType()
                {
                    RecordType = new RecordType(Entities.contact, Entities.contact), Type = ExportType.AllRecords
                }
            };
            //error if already .zips on the folder
            FileUtility.WriteToFile(TestingFolder, "Fake.zip", "FakeContent");
            createApplication = CreateAndLoadTestApplication <CreatePackageModule>();
            try
            {
                createApplication.NavigateAndProcessDialog <CreatePackageModule, CreatePackageDialog, ServiceResponseBase <DataImportResponseItem> >(createDeploymentPackageRequest);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsFalse(ex is AssertFailedException);
            }
            FileUtility.DeleteFiles(TestingFolder);
            FileUtility.DeleteSubFolders(TestingFolder);
            response = createApplication.NavigateAndProcessDialog <CreatePackageModule, CreatePackageDialog, ServiceResponseBase <DataImportResponseItem> >(createDeploymentPackageRequest);
            Assert.IsFalse(response.HasError);

            solution = XrmRecordService.Get(solution.Type, solution.Id);
            Assert.AreEqual("3.0.0.0", solution.GetStringField(Fields.solution_.version));
        }
Esempio n. 7
0
        public override void ExecuteExtention(DeployIntoFieldRequest request, DeployIntoFieldResponse response,
                                              LogController controller)
        {
            var records = new List <IRecord>();

            var publishIds = new List <string>();

            var numberToDo = request.Files.Count();
            var numberDone = 0;

            foreach (var file in request.Files)
            {
                var fileInfo = new FileInfo(file);
                controller.UpdateProgress(++numberDone, numberToDo, "Importing " + fileInfo.Name);
                var thisResponseItem = new DeployIntoFieldResponseItem()
                {
                    Name = fileInfo.Name
                };
                response.AddResponseItem(thisResponseItem);
                try
                {
                    var containingFolderName = fileInfo.Directory.Name;
                    //get target record type
                    string recordType = null;
                    if (Service.GetAllRecordTypes().Any(r => r == containingFolderName))
                    {
                        recordType = Service.GetAllRecordTypes().First(r => r == containingFolderName);
                    }
                    else if (Service.GetAllRecordTypes().Any(r => Service.GetDisplayName(r)?.ToLower() == containingFolderName.ToLower()))
                    {
                        recordType = Service.GetAllRecordTypes().First(r => Service.GetDisplayName(r)?.ToLower() == containingFolderName.ToLower());
                    }
                    else
                    {
                        throw new NullReferenceException($"Could not find matching type by logical or display name for folder name of {containingFolderName}");
                    }

                    if (recordType == Entities.adx_webfile)
                    {
                        //this one goes into an attachment
                        var matchingRecord = Service.GetFirst(recordType, Service.GetPrimaryField(recordType), fileInfo.Name);
                        if (matchingRecord == null)
                        {
                            throw new NullReferenceException($"There is no {Service.GetDisplayName(recordType)} record name {fileInfo.Name} to load the file attachment into");
                        }
                        //get matching attachment by name else create a new one
                        var fileAttachments = Service.RetrieveAllAndClauses(Entities.annotation, new[]
                        {
                            new Condition(Fields.annotation_.filename, ConditionType.Equal, fileInfo.Name),
                            new Condition(Fields.annotation_.objectid, ConditionType.Equal, matchingRecord.Id)
                        }).OrderBy(n => n.GetDateTime(Fields.annotation_.createdon)).ToArray();

                        var contentBytes        = File.ReadAllBytes(file);
                        var contentBase64String = Convert.ToBase64String(contentBytes);
                        if (fileAttachments.Any())
                        {
                            //lets update the last modifed one
                            var attachmentToUpdate = fileAttachments.First();
                            if (attachmentToUpdate.GetStringField(Fields.annotation_.documentbody) != contentBase64String)
                            {
                                attachmentToUpdate.SetField(Fields.annotation_.documentbody, contentBase64String, Service);
                                Service.Update(attachmentToUpdate, new[] { Fields.annotation_.documentbody });
                                thisResponseItem.Updated = true;
                            }
                        }
                        else
                        {
                            //lets create a new attachment
                            var newAttachment = Service.NewRecord(Entities.annotation);
                            newAttachment.SetLookup(Fields.annotation_.objectid, matchingRecord.Id, matchingRecord.Type);
                            newAttachment.SetField(Fields.annotation_.subject, fileInfo.Name, Service);
                            newAttachment.SetField(Fields.annotation_.filename, fileInfo.Name, Service);
                            newAttachment.SetField(Fields.annotation_.documentbody, contentBase64String, Service);
                            Service.Create(newAttachment);
                            thisResponseItem.Created = true;
                        }
                    }
                    else
                    {
                        //get the record with the same name as the file
                        var fileNameSansExtention = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf("."));

                        var conditions = new List <Condition>
                        {
                            new Condition(Service.GetPrimaryField(recordType), ConditionType.Equal, fileNameSansExtention)
                        };
                        if (recordType == Entities.adx_webpage)
                        {
                            conditions.Add(new Condition(Fields.adx_webpage_.adx_rootwebpageid, ConditionType.NotNull));
                        }

                        var matchingRecords = Service.RetrieveAllAndClauses(recordType, conditions);
                        if (matchingRecords.Count() != 1)
                        {
                            throw new NullReferenceException($"Could not find {Service.GetDisplayName(recordType)} named {fileInfo.Name} to update");
                        }
                        var matchingRecord = matchingRecords.First();

                        var targetField = GetTargetField(fileInfo, recordType);

                        var contentText = File.ReadAllText(file);
                        if (matchingRecord.GetStringField(targetField) != contentText)
                        {
                            matchingRecord.SetField(targetField, contentText, Service);
                            Service.Update(matchingRecord, new[] { targetField });
                            thisResponseItem.Updated = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    thisResponseItem.Exception = ex;
                }
            }
        }