/// <inheritdoc/>
        protected override void Initialize()
        {
            base.Initialize();
            var comparisonRules = new ComparisonRules[Order.Count];

            for (int i = 0; i < Order.Count; i++)
            {
                var orderItem    = Order[i];
                var culture      = CultureInfo.InvariantCulture;
                var column       = Header.Columns[orderItem.Key];
                var mappedColumn = column as MappedColumn;
                if (mappedColumn != null && mappedColumn.ColumnInfoRef != null)
                {
                    culture = mappedColumn.ColumnInfoRef.CultureInfo;
                }
                comparisonRules[i] = new ComparisonRule(orderItem.Value, culture);
            }

            var fieldTypes = new Type[Order.Count];
            var map        = new int[Order.Count];

            for (var i = 0; i < Order.Count; i++)
            {
                var p = Order[i];
                fieldTypes[i] = Header.Columns[p.Key].Type;
                map[i]        = p.Key;
            }
            var orderKeyDescriptor = TupleDescriptor.Create(fieldTypes);

            OrderKeyExtractorTransform = new MapTransform(true, orderKeyDescriptor, map);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Creates a instance of NamespaceModelValidationPolicy Policy
 /// </summary>
 /// <param name="predicate">comparison predicate</param>
 /// <param name="shouldValidate">decides the result of evaluation. if true and if rule mathces then validation will occour, if false it will not do model validation</param>
 public NamespaceModelValidationPolicy(string namespaceToCompare, bool shouldValidate) : base(shouldValidate)
 {
     this.Rule = ComparisonRule.Equals;
     this.namespaceToCompare = namespaceToCompare;
     comparisonHandlers.Add(ComparisonRule.Contains, (type, toCompare) => !type.Namespace.Contains(toCompare.ToString()));
     comparisonHandlers.Add(ComparisonRule.EndWith, (type, toCompare) => !type.Namespace.EndsWith(toCompare.ToString()));
     comparisonHandlers.Add(ComparisonRule.StartWith, (type, toCompare) => !type.Namespace.StartsWith(toCompare.ToString()));
     comparisonHandlers.Add(ComparisonRule.Equals, (type, toCompare) => !type.Namespace.Equals(toCompare.ToString()));
 }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="thisListOfT"></param>
        /// <param name="comparingRule"></param>
        /// <param name="listOfT"></param>
        /// <param name="X"></param>
        /// <returns></returns>
        public static bool BelongsTo <T>(this IEnumerable <T> thisListOfT, ComparisonRule comparingRule, IEnumerable <T> listOfT, int X = 0)
        {
            if (thisListOfT == null && listOfT == null)
            {
                return(true);
            }

            if (thisListOfT == null || listOfT == null)
            {
                return(false);
            }

            bool result = false;

            switch (comparingRule)
            {
            case ComparisonRule.AllOf:
                result = thisListOfT.All(thisT => listOfT.Any(t => thisT.Equals(t)));
                break;

            case ComparisonRule.AnyOf:
                result = thisListOfT.Any(thisT => listOfT.Any(t => thisT.Equals(t)));
                break;

            case ComparisonRule.NoneOf:
                result = thisListOfT.All(thisT => listOfT.All(t => !thisT.Equals(t)));
                break;

            case ComparisonRule.ExactlyTheSame:
                result =
                    thisListOfT.Count() == listOfT.Count()
                    &&
                    thisListOfT.All(thisT => listOfT.All(t => thisT.Equals(t)));
                break;

            case ComparisonRule.ExactlyXof:
                result = thisListOfT.CounEqualItems(listOfT) == X;
                break;

            case ComparisonRule.MoreThanXof:
                result = thisListOfT.CounEqualItems(listOfT) > X;
                break;

            case ComparisonRule.LessThanXof:
                result = thisListOfT.CounEqualItems(listOfT) < X;
                break;

            default:
                throw new Exception("ComparisonRule is not valid!");
            }


            return(result);
        }
        public ComparisonRule CreateComparisonRule(string comparisonSymbol, string comparisonColumn, string comparedColumnDescription)
        {
            var r = new ComparisonRule()
            {
                ComparedColumn            = comparisonColumn,
                ComparedColumnDescription = comparedColumnDescription,
                ComparisonSymbol          = comparisonSymbol,
                IsActive = true,
            };

            SetNullValueTreatment(r);
            Assigner.AddErrorTypes(r);
            return(r);
        }
Ejemplo n.º 5
0
        private static ComparisonRule GetOrCreateComparisonRule(ComparisonRuleForUser comparisonRuleForUser,
                                                                long comparisonItemId,
                                                                int order,
                                                                StudyLanguageContext c)
        {
            ComparisonRule comparisonRule =
                c.ComparisonRule.FirstOrDefault(
                    e => e.ComparisonItemId == comparisonItemId && e.Description == comparisonRuleForUser.Description);

            if (comparisonRule == null)
            {
                comparisonRule = new ComparisonRule {
                    ComparisonItemId = comparisonItemId,
                    Description      = comparisonRuleForUser.Description
                };
                c.ComparisonRule.Add(comparisonRule);
            }

            comparisonRule.Order = order;
            c.SaveChanges();

            return(comparisonRule);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Получает группу сравнения по названию
        /// </summary>
        /// <param name="userLanguages">языковые настройки пользователя</param>
        /// <param name="title">название представления</param>
        /// <returns>представление или null если не найдено</returns>
        public ComparisonForUser GetWithFullInfo(UserLanguages userLanguages, string title)
        {
            long sourceLanguageId      = userLanguages.From.Id;
            long translationLanguageId = userLanguages.To.Id;

            ComparisonForUser result = Adapter.ReadByContext(c => {
                var comparisonsQuery = (from gc in c.GroupComparison
                                        join ci in c.ComparisonItem on gc.Id equals ci.GroupComparisonId
                                        join cr in c.ComparisonRule on ci.Id equals cr.ComparisonItemId
                                        join cre in c.ComparisonRuleExample on cr.Id equals cre.ComparisonRuleId
                                        join st in c.SentenceTranslation on cre.SentenceTranslationId equals st.Id
                                        join s1 in c.Sentence on st.SentenceId1 equals s1.Id
                                        join s2 in c.Sentence on st.SentenceId2 equals s2.Id
                                        where gc.Title == title && gc.LanguageId == _languageId &&
                                        ((s1.LanguageId == sourceLanguageId &&
                                          s2.LanguageId == translationLanguageId)
                                         ||
                                         (s1.LanguageId == translationLanguageId &&
                                          s2.LanguageId == sourceLanguageId))
                                        orderby ci.Order, cr.Order, cre.Order
                                        select new { gc, ci, cr, cre, st, s1, s2 });
                var comparisonsInfos = comparisonsQuery.AsEnumerable();
                var firstComparison  = comparisonsInfos.FirstOrDefault();
                if (firstComparison == null)
                {
                    return(null);
                }
                var innerResult           = new ComparisonForUser(firstComparison.gc);
                long prevComparisonItemId = IdValidator.INVALID_ID;
                long prevComparisonRuleId = IdValidator.INVALID_ID;
                ComparisonItemForUser comparisonItemForUser = null;
                ComparisonRuleForUser comparisonRuleForUser = null;
                foreach (var comparisonInfo in comparisonsInfos)
                {
                    ComparisonItem comparisonItem = comparisonInfo.ci;
                    if (prevComparisonItemId != comparisonItem.Id)
                    {
                        prevComparisonItemId = comparisonItem.Id;

                        if (comparisonItemForUser != null)
                        {
                            innerResult.AddItem(comparisonItemForUser);
                        }

                        comparisonItemForUser = new ComparisonItemForUser(comparisonItem);
                    }

                    ComparisonRule comparisonRule = comparisonInfo.cr;
                    if (comparisonRule.Id != prevComparisonRuleId)
                    {
                        prevComparisonRuleId = comparisonRule.Id;

                        comparisonRuleForUser = new ComparisonRuleForUser(comparisonRule);
                        comparisonItemForUser.AddRule(comparisonRuleForUser);
                    }

                    SourceWithTranslation sourceWithTranslation =
                        ConverterEntities.ConvertToSourceWithTranslation(comparisonInfo.st.Id,
                                                                         comparisonInfo.st.Image,
                                                                         comparisonInfo.s1.LanguageId,
                                                                         comparisonInfo.s1,
                                                                         comparisonInfo.s2);
                    sourceWithTranslation.IsCurrent = false;
                    var example = new ComparisonRuleExampleForUser(comparisonInfo.cre, sourceWithTranslation);
                    comparisonRuleForUser.AddExample(example);
                }

                if (comparisonItemForUser != null)
                {
                    innerResult.AddItem(comparisonItemForUser);
                }

                return(innerResult);
            });

            return(result);
        }
Ejemplo n.º 7
0
        public ComparisonForUser GetOrCreate(ComparisonForUser comparisonForUser)
        {
            if (!comparisonForUser.IsValid())
            {
                return(null);
            }

            bool isSuccess           = true;
            ComparisonForUser result = null;

            Adapter.ActionByContext(c => {
                GroupComparison groupComparison = GetOrCreateGroupComparison(comparisonForUser, c);
                if (IdValidator.IsInvalid(groupComparison.Id))
                {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                        "ComparisonsQuery.GetOrCreate не удалось создать! Название: {0}, описание: {1}",
                        comparisonForUser.Title,
                        comparisonForUser.Description);
                    isSuccess = false;
                    return;
                }
                result = new ComparisonForUser(groupComparison);

                int orderItem = 1;
                foreach (ComparisonItemForUser comparisonItemForUser in comparisonForUser.Items)
                {
                    ComparisonItem comparisonItem = GetOrCreateComparisonItem(comparisonItemForUser, groupComparison.Id,
                                                                              orderItem++, c);
                    if (IdValidator.IsInvalid(comparisonItem.Id))
                    {
                        LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                            "ComparisonsQuery.GetOrCreate не удалось создать пункт для сравнения! " +
                            "Id сравнения: {0}, название {1}, перевод названия {2}, описание {3}",
                            groupComparison.Id, comparisonItemForUser.Title, comparisonItemForUser.TitleTranslated,
                            comparisonItemForUser.Description);
                        isSuccess = false;
                        continue;
                    }

                    var newComparisonItemForUser = new ComparisonItemForUser(comparisonItem);
                    result.AddItem(newComparisonItemForUser);

                    int orderRule = 1;
                    foreach (ComparisonRuleForUser comparisonRuleForUser in comparisonItemForUser.Rules)
                    {
                        ComparisonRule comparisonRule = GetOrCreateComparisonRule(comparisonRuleForUser,
                                                                                  comparisonItem.Id, orderRule++, c);
                        long ruleId = comparisonRule.Id;
                        if (IdValidator.IsInvalid(ruleId))
                        {
                            LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                                "ComparisonsQuery.GetOrCreate не удалось создать правило для сравнения! " +
                                "Id пункта сравнения: {0}, описание {1}",
                                comparisonItem.Id, comparisonRule.Description);
                            isSuccess = false;
                            continue;
                        }

                        var newComparisonRuleForUser = new ComparisonRuleForUser(comparisonRule);
                        newComparisonItemForUser.AddRule(newComparisonRuleForUser);

                        isSuccess = EnumerableValidator.IsNotEmpty(comparisonRuleForUser.Examples) &&
                                    CreateExamples(comparisonRuleForUser.Examples, newComparisonRuleForUser, c);
                    }
                }

                if (isSuccess)
                {
                    //удалить пункты, правила, примеры, которые не были переданы в этот раз
                    DeleteOldInfos(c, result);
                }
            });
            return(isSuccess && result != null && result.IsValid() ? result : null);
        }
Ejemplo n.º 8
0
 public NamespaceModelValidationPolicy(string namespaceToCompare, ComparisonRule rule, bool shouldValidate = true) : this(namespaceToCompare, shouldValidate)
 {
     this.Rule = rule;
     this.namespaceToCompare = namespaceToCompare;
 }
Ejemplo n.º 9
0
 public ComparisonRuleForUser(ComparisonRule comparisonRule) : this(comparisonRule.Description)
 {
     Id = comparisonRule.Id;
 }
        public PropertyUnitTests(ITestOutputHelper testOutputHelper)
        {
            this.testOutputHelper = testOutputHelper;

            //Define the factories
            this.defaultObjectFactory = new ObjectFactory();

            this.proxyPropertyToObjectModelMapping = new List <ComparerPropertyMapping>()
            {
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "Statistics", "Stats"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "CurrentDedicatedComputeNodes", "CurrentDedicatedNodes"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "CurrentLowPriorityComputeNodes", "CurrentLowPriorityNodes"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"),

                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"),

                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "CurrentDedicatedComputeNodes", "CurrentDedicatedNodes"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "CurrentLowPriorityComputeNodes", "CurrentLowPriorityNodes"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"),

                new ComparerPropertyMapping(typeof(CloudServiceConfiguration), typeof(Protocol.Models.CloudServiceConfiguration), "OSFamily", "OsFamily"),
                new ComparerPropertyMapping(typeof(CloudServiceConfiguration), typeof(Protocol.Models.CloudServiceConfiguration), "OSVersion", "OsVersion"),

                new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "TaskExecutionInformation"),

                new ComparerPropertyMapping(typeof(AutoPoolSpecification), typeof(Protocol.Models.AutoPoolSpecification), "PoolSpecification", "Pool"),

                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeId", "NodeId"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeUrl", "NodeUrl"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobPreparationTaskExecutionInformation", "JobPreparationTaskExecutionInfo"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobReleaseTaskExecutionInformation", "JobReleaseTaskExecutionInfo"),

                new ComparerPropertyMapping(typeof(JobPreparationTaskExecutionInformation), typeof(Protocol.Models.JobPreparationTaskExecutionInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(JobPreparationTaskExecutionInformation), typeof(Protocol.Models.JobPreparationTaskExecutionInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(JobReleaseTaskExecutionInformation), typeof(Protocol.Models.JobReleaseTaskExecutionInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(JobReleaseTaskExecutionInformation), typeof(Protocol.Models.JobReleaseTaskExecutionInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(TaskExecutionInformation), typeof(Protocol.Models.TaskExecutionInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(TaskExecutionInformation), typeof(Protocol.Models.TaskExecutionInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(SubtaskInformation), typeof(Protocol.Models.SubtaskInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(SubtaskInformation), typeof(Protocol.Models.SubtaskInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(StartTaskInformation), typeof(Protocol.Models.StartTaskInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(StartTaskInformation), typeof(Protocol.Models.StartTaskInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "UsageStatistics", "UsageStats"),
                new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "ResourceStatistics", "ResourceStats"),

                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "KernelCpuTime", "KernelCPUTime"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "SucceededTaskCount", "NumSucceededTasks"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "FailedTaskCount", "NumFailedTasks"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "TaskRetryCount", "NumTaskRetries"),

                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "KernelCpuTime", "KernelCPUTime"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "SucceededTaskCount", "NumSucceededTasks"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "FailedTaskCount", "NumFailedTasks"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "TaskRetryCount", "NumTaskRetries"),

                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageCpuPercentage", "AvgCPUPercentage"),
                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageMemoryGiB", "AvgMemoryGiB"),
                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageDiskGiB", "AvgDiskGiB"),

                new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "KernelCpuTime", "KernelCPUTime"),

                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "PoolInformation", "PoolInfo"),
                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.JobAddParameter), "PoolInformation", "PoolInfo"),

                new ComparerPropertyMapping(typeof(JobSpecification), typeof(Protocol.Models.JobSpecification), "PoolInformation", "PoolInfo"),

                new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "AffinityInformation", "AffinityInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ComputeNodeInformation", "NodeInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "AffinityInformation", "AffinityInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "ComputeNodeInformation", "NodeInfo"),

                new ComparerPropertyMapping(typeof(ExitConditions), typeof(Protocol.Models.ExitConditions), "Default", "DefaultProperty"),

                new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "ExecutionInfo"),

                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "IPAddress", "IpAddress"),
                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "StartTaskInformation", "StartTaskInfo"),
                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "NodeAgentInformation", "NodeAgentInfo"),

                new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeId", "NodeId"),
                new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeUrl", "NodeUrl"),

                new ComparerPropertyMapping(typeof(JobPreparationTask), typeof(Protocol.Models.JobPreparationTask), "RerunOnComputeNodeRebootAfterSuccess", "RerunOnNodeRebootAfterSuccess"),

                new ComparerPropertyMapping(typeof(ImageReference), typeof(Protocol.Models.ImageReference), "SkuId", "Sku"),

                new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "NodeAgentSkuId", "NodeAgentSKUId"),
                new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "OSDisk", "OsDisk"),

                new ComparerPropertyMapping(typeof(TaskSchedulingPolicy), typeof(Protocol.Models.TaskSchedulingPolicy), "ComputeNodeFillType", "NodeFillType"),

                new ComparerPropertyMapping(typeof(PoolEndpointConfiguration), typeof(Protocol.Models.PoolEndpointConfiguration), "InboundNatPools", "InboundNATPools"),
                new ComparerPropertyMapping(typeof(InboundEndpoint), typeof(Protocol.Models.InboundEndpoint), "PublicFqdn", "PublicFQDN"),

                new ComparerPropertyMapping(typeof(ImageInformation), typeof(Protocol.Models.ImageInformation), "NodeAgentSkuId", "NodeAgentSKUId"),
                new ComparerPropertyMapping(typeof(ImageInformation), typeof(Protocol.Models.ImageInformation), "OSType", "OsType"),
            };

            Random rand = new Random();

            Func <object> omTaskRangeBuilder = () =>
            {
                int rangeLimit1 = rand.Next(0, int.MaxValue);
                int rangeLimit2 = rand.Next(0, int.MaxValue);

                return(new TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2)));
            };

            Func <object> iFileStagingProviderBuilder = () => null;

            Func <object> batchClientBehaviorBuilder = () => null;

            Func <object> taskRangeBuilder = () =>
            {
                int rangeLimit1 = rand.Next(0, int.MaxValue);
                int rangeLimit2 = rand.Next(0, int.MaxValue);

                return(new Protocol.Models.TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2)));
            };

            ObjectFactoryConstructionSpecification certificateReferenceSpecification = new ObjectFactoryConstructionSpecification(
                typeof(Protocol.Models.CertificateReference),
                () => BuildCertificateReference(rand));

            ObjectFactoryConstructionSpecification authenticationTokenSettingsSpecification = new ObjectFactoryConstructionSpecification(
                typeof(Protocol.Models.AuthenticationTokenSettings),
                () => BuildAuthenticationTokenSettings(rand));

            ObjectFactoryConstructionSpecification taskRangeSpecification = new ObjectFactoryConstructionSpecification(
                typeof(Protocol.Models.TaskIdRange),
                taskRangeBuilder);

            ObjectFactoryConstructionSpecification omTaskRangeSpecification = new ObjectFactoryConstructionSpecification(
                typeof(TaskIdRange),
                omTaskRangeBuilder);

            ObjectFactoryConstructionSpecification batchClientBehaviorSpecification = new ObjectFactoryConstructionSpecification(
                typeof(BatchClientBehavior),
                batchClientBehaviorBuilder);

            ObjectFactoryConstructionSpecification fileStagingProviderSpecification = new ObjectFactoryConstructionSpecification(
                typeof(IFileStagingProvider),
                iFileStagingProviderBuilder);

            this.customizedObjectFactory = new ObjectFactory(new List <ObjectFactoryConstructionSpecification>
            {
                certificateReferenceSpecification,
                authenticationTokenSettingsSpecification,
                taskRangeSpecification,
                omTaskRangeSpecification,
                fileStagingProviderSpecification,
                batchClientBehaviorSpecification,
            });

            // We need a custom comparison rule for certificate references because they are a different type in the proxy vs
            // the object model (string in proxy, flags enum in OM
            ComparisonRule certificateReferenceComparisonRule = ComparisonRule.Create <CertificateVisibility?, List <Protocol.Models.CertificateVisibility> >(
                typeof(CertificateReference),
                typeof(Protocol.Models.CertificateReference), // This is the type that hold the target property
                (visibility, proxyVisibility) =>
            {
                CertificateVisibility?convertedProxyVisibility = UtilitiesInternal.ParseCertificateVisibility(proxyVisibility);

                //Treat null as None for the purposes of comparison:
                bool areEqual = convertedProxyVisibility == visibility || !visibility.HasValue && convertedProxyVisibility == CertificateVisibility.None;

                return(areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("Certificate visibility doesn't match"));
            },
                type1PropertyName: "Visibility",
                type2PropertyName: "Visibility");

            ComparisonRule accessScopeComparisonRule = ComparisonRule.Create <AccessScope, List <Protocol.Models.AccessScope> >(
                typeof(AuthenticationTokenSettings),
                typeof(Protocol.Models.AuthenticationTokenSettings),  // This is the type that hold the target property
                (scope, proxyVisibility) =>
            {
                AccessScope convertedProxyAccessScope = UtilitiesInternal.ParseAccessScope(proxyVisibility);

                //Treat null as None for the purposes of comparison:
                bool areEqual = convertedProxyAccessScope == scope || convertedProxyAccessScope == AccessScope.None;

                return(areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("AccessScope doesn't match"));
            },
                type1PropertyName: "Access",
                type2PropertyName: "Access");

            this.objectComparer = new ObjectComparer(
                comparisonRules: new List <ComparisonRule>()
            {
                certificateReferenceComparisonRule, accessScopeComparisonRule
            },
                propertyMappings: this.proxyPropertyToObjectModelMapping,
                shouldThrowOnPropertyReadException: e => !(e.InnerException is InvalidOperationException) || !e.InnerException.Message.Contains("while the object is in the Unbound"));
        }
Ejemplo n.º 11
0
 public ComparisonRuleEditViewViewModel(ComparisonRule comparisonRule)
     : base(comparisonRule)
 {
     _rule = comparisonRule;
 }
Ejemplo n.º 12
0
        public PropertyUnitTests(ITestOutputHelper testOutputHelper)
        {
            this.testOutputHelper = testOutputHelper;

            //Define the factories
            this.defaultObjectFactory = new ObjectFactory();

            this.proxyPropertyToObjectModelMapping = new List <ComparerPropertyMapping>()
            {
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "Statistics", "Stats"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),

                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),

                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),

                new ComparerPropertyMapping(typeof(CloudServiceConfiguration), typeof(Protocol.Models.CloudServiceConfiguration), "OSFamily", "OsFamily"),

                new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "TaskExecutionInformation"),

                new ComparerPropertyMapping(typeof(AutoPoolSpecification), typeof(Protocol.Models.AutoPoolSpecification), "PoolSpecification", "Pool"),

                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeId", "NodeId"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeUrl", "NodeUrl"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobPreparationTaskExecutionInformation", "JobPreparationTaskExecutionInfo"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobReleaseTaskExecutionInformation", "JobReleaseTaskExecutionInfo"),

                new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "UsageStatistics", "UsageStats"),
                new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "ResourceStatistics", "ResourceStats"),

                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "KernelCpuTime", "KernelCPUTime"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "SucceededTaskCount", "NumSucceededTasks"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "FailedTaskCount", "NumFailedTasks"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "TaskRetryCount", "NumTaskRetries"),

                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "KernelCpuTime", "KernelCPUTime"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "SucceededTaskCount", "NumSucceededTasks"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "FailedTaskCount", "NumFailedTasks"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "TaskRetryCount", "NumTaskRetries"),

                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageCpuPercentage", "AvgCPUPercentage"),
                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageMemoryGiB", "AvgMemoryGiB"),
                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageDiskGiB", "AvgDiskGiB"),

                new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "KernelCpuTime", "KernelCPUTime"),

                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "PoolInformation", "PoolInfo"),
                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.JobAddParameter), "PoolInformation", "PoolInfo"),

                new ComparerPropertyMapping(typeof(JobSpecification), typeof(Protocol.Models.JobSpecification), "PoolInformation", "PoolInfo"),

                new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "AffinityInformation", "AffinityInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ComputeNodeInformation", "NodeInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "AffinityInformation", "AffinityInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "ComputeNodeInformation", "NodeInfo"),

                new ComparerPropertyMapping(typeof(ExitConditions), typeof(Protocol.Models.ExitConditions), "Default", "DefaultProperty"),

                new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "ExecutionInfo"),

                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "IPAddress", "IpAddress"),
                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "StartTaskInformation", "StartTaskInfo"),

                new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeId", "NodeId"),
                new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeUrl", "NodeUrl"),

                new ComparerPropertyMapping(typeof(JobPreparationTask), typeof(Protocol.Models.JobPreparationTask), "RerunOnComputeNodeRebootAfterSuccess", "RerunOnNodeRebootAfterSuccess"),

                new ComparerPropertyMapping(typeof(ImageReference), typeof(Protocol.Models.ImageReference), "SkuId", "Sku"),

                new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "NodeAgentSkuId", "NodeAgentSKUId"),

                new ComparerPropertyMapping(typeof(TaskSchedulingPolicy), typeof(Protocol.Models.TaskSchedulingPolicy), "ComputeNodeFillType", "NodeFillType"),
            };

            Random rand = new Random();

            Func <object> certificateReferenceBuilder = () =>
            {
                //Build cert visibility (which is a required property)
                IList          values         = Enum.GetValues(typeof(CertificateVisibility));
                IList <object> valuesToSelect = new List <object>();

                foreach (object value in values)
                {
                    valuesToSelect.Add(value);
                }

                int valuesToPick = rand.Next(0, values.Count);
                CertificateVisibility?visibility = null;

                // If valuesToPick is 0, we want to allow visibility to be null (since null is a valid value)
                // so only set visibility to be None if valuesToPick > 0
                if (valuesToPick > 0)
                {
                    visibility = CertificateVisibility.None;
                    for (int i = 0; i < valuesToPick; i++)
                    {
                        int    selectedValueIndex = rand.Next(valuesToSelect.Count);
                        object selectedValue      = valuesToSelect[selectedValueIndex];
                        visibility |= (CertificateVisibility)selectedValue;

                        valuesToSelect.RemoveAt(selectedValueIndex);
                    }
                }

                Protocol.Models.CertificateReference reference =
                    this.defaultObjectFactory.GenerateNew <Protocol.Models.CertificateReference>();

                //Set certificate visibility since it is required
                reference.Visibility = visibility == null ? null : UtilitiesInternal.CertificateVisibilityToList(visibility.Value);

                return(reference);
            };

            Func <object> omTaskRangeBuilder = () =>
            {
                int rangeLimit1 = rand.Next(0, int.MaxValue);
                int rangeLimit2 = rand.Next(0, int.MaxValue);

                return(new TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2)));
            };

            Func <object> iFileStagingProviderBuilder = () => { return(null); };

            Func <object> batchClientBehaviorBuilder = () => { return(null); };

            Func <object> taskRangeBuilder = () =>
            {
                int rangeLimit1 = rand.Next(0, int.MaxValue);
                int rangeLimit2 = rand.Next(0, int.MaxValue);

                return(new Protocol.Models.TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2)));
            };

            ObjectFactoryConstructionSpecification visibilitySpecification = new ObjectFactoryConstructionSpecification(
                typeof(Protocol.Models.CertificateReference),
                certificateReferenceBuilder);

            ObjectFactoryConstructionSpecification taskRangeSpecification = new ObjectFactoryConstructionSpecification(
                typeof(Protocol.Models.TaskIdRange),
                taskRangeBuilder);

            ObjectFactoryConstructionSpecification omTaskRangeSpecification = new ObjectFactoryConstructionSpecification(
                typeof(TaskIdRange),
                omTaskRangeBuilder);

            ObjectFactoryConstructionSpecification batchClientBehaviorSpecification = new ObjectFactoryConstructionSpecification(
                typeof(BatchClientBehavior),
                batchClientBehaviorBuilder);

            ObjectFactoryConstructionSpecification fileStagingProviderSpecification = new ObjectFactoryConstructionSpecification(
                typeof(IFileStagingProvider),
                iFileStagingProviderBuilder);

            this.customizedObjectFactory = new ObjectFactory(new List <ObjectFactoryConstructionSpecification>
            {
                visibilitySpecification,
                taskRangeSpecification,
                omTaskRangeSpecification,
                fileStagingProviderSpecification,
                batchClientBehaviorSpecification
            });

            // We need a custom comparison rule for certificate references because they are a different type in the proxy vs
            // the object model (string in proxy, flags enum in OM
            ComparisonRule certificateReferenceComparisonRule = ComparisonRule.Create <CertificateVisibility?, List <Protocol.Models.CertificateVisibility?> >(
                typeof(CertificateReference),
                typeof(Protocol.Models.CertificateReference),
                (visibility, proxyVisibility) =>
            {
                CertificateVisibility?convertedProxyVisibility = UtilitiesInternal.ParseCertificateVisibility(proxyVisibility);

                //Treat null as None for the purposes of comparison:
                bool areEqual = convertedProxyVisibility == visibility || !visibility.HasValue && convertedProxyVisibility == CertificateVisibility.None;

                return(areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("Certificate visibility doesn't match"));
            },
                type1PropertyName: "Visibility",
                type2PropertyName: "Visibility");

            this.objectComparer = new ObjectComparer(
                comparisonRules: new List <ComparisonRule>()
            {
                certificateReferenceComparisonRule
            },
                propertyMappings: this.proxyPropertyToObjectModelMapping,
                shouldThrowOnPropertyReadException: e => !(e.InnerException is InvalidOperationException) || !e.InnerException.Message.Contains("while the object is in the Unbound"));
        }