public void ModifyConfigShapeError()
        {
            ShapesConfigMockService shapesConfigMockService = new ShapesConfigMockService();
            ValidationController    validationController    = new ValidationController(shapesConfigMockService);
            ShapeConfig             shapeConfig             = ((List <ShapeConfig>)(((OkObjectResult)validationController.GetShape()).Value))[0];

            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write("ShapeError");
            writer.Flush();
            stream.Position = 0;
            var file = new FormFile(stream, 0, stream.Length, null, "rdf.xml");

            try
            {
                var response = validationController.ModifyShape(shapeConfig.ShapeConfigID, shapeConfig.Name, shapeConfig.RepositoryID, file);
                if (response is BadRequestObjectResult)
                {
                    Assert.True(true);
                }
                else
                {
                    Assert.True(false);
                }
            }
            catch (Exception)
            {
                Assert.True(true);
            }
        }
示例#2
0
        public Studiengangsverwaltung()
        {
            InitializeComponent();

            validationControllerStudiengang = new ValidationController(new bool[3], lbl_error_msg);
            validationControllerSemester    = new ValidationController(new bool[3], lbl_error_msg);
        }
示例#3
0
        private void InitializeForm()
        {
            InitializeComponent();

            _validateController = new ValidationController()
            {
                OKButton = _buttonOK,
            };

            _validateController.RegisterControl(_textObjectName, ValidateObjectName);
            _validateController.RegisterControl(_textSource, ValidateSourceFile);
            _validateController.RegisterControl(_numMaskLeft,
                                                ValidationController.ValidateLessEq("Left Mask Bound", _numMaskLeft, "Right Mask Bound", _numMaskRight));
            _validateController.RegisterControl(_numMaskRight,
                                                ValidationController.ValidateGreaterEq("Right Mask Bound", _numMaskRight, "Left Mask Bound", _numMaskLeft));
            _validateController.RegisterControl(_numMaskTop,
                                                ValidationController.ValidateLessEq("Top Mask Bound", _numMaskTop, "Bottom Mask Bound", _numMaskBottom));
            _validateController.RegisterControl(_numMaskBottom,
                                                ValidationController.ValidateGreaterEq("Bottom Mask Bound", _numMaskBottom, "Top Mask Bound", _numMaskTop));
            _validateController.RegisterControl(_numOriginX,
                                                ValidationController.ValidateNumericUpDownFunc("Origin X", _numOriginX));
            _validateController.RegisterControl(_numOriginY,
                                                ValidationController.ValidateNumericUpDownFunc("Origin Y", _numOriginY));

            InitializeObjectPreview();
        }
        internal void OnCheckModelValidity(object sender, EventArgs e)
        {
            ValidationController controller = this.CurrentData.ValidationController;
            ValidationCategory   category   = ValidationCategory.Menu;

            bool isValid = controller.Validate(this.CurrentData.Store, category);

            bool errorsOccurred = false;

            foreach (ValidationMessage message in controller.ValidationMessages)
            {
                if (message.Type == ViolationType.Error)
                {
                    errorsOccurred = true;
                    break;
                }
            }

            if (errorsOccurred)
            {
                System.Windows.Forms.MessageBox.Show("Cannot generate XML from model: There were validation errors!", "Model Invalidity", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            else
            {
                Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram = this.CurrentView.CurrentDiagram;
                ISpySoft.FeatureModelLanguage.Designer.Custom.XmlFileGenerator xmlFileGenerator = new ISpySoft.FeatureModelLanguage.Designer.Custom.XmlFileGenerator();
                xmlFileGenerator.GenerateXmlFile(diagram);
            }
        } // OnCheckModelValidity
        private void Revalidate()
        {
            var controller = new ValidationController();

            controller.RequestPropertyRevalidation(Context.VM, Property);
            controller.ProcessPendingValidations();
        }
示例#6
0
        public void TestController()
        {
            Mock <IReferenceDataCache> cacheMock = new Mock <IReferenceDataCache>();

            cacheMock.Setup(m => m.GetUlnLookup(It.IsAny <IList <long?> >(), It.IsAny <CancellationToken>())).Returns(new List <UniqueLearnerNumber>());

            Mock <IFcsCodeMappingHelper> mapperMock = new Mock <IFcsCodeMappingHelper>();

            mapperMock.Setup(m =>
                             m.GetFcsDeliverableCode(It.IsAny <SupplementaryDataModel>(), It.IsAny <CancellationToken>())).Returns(1);

            Mock <IPopulationService> popMock = new Mock <IPopulationService>();

            popMock.Setup(m => m.PrePopulateUlnCache(It.IsAny <IList <long?> >(), It.IsAny <CancellationToken>()));

            SupplementaryDataModelMapper mapper = new SupplementaryDataModelMapper();

            var looseValidation = GetLooseValidators();
            var validators      = GetValidators(cacheMock, mapperMock);
            var controller      = new ValidationController(looseValidation, validators, popMock.Object, mapper);

            var wrapper = new SupplementaryDataWrapper
            {
                SupplementaryDataLooseModels = GetSupplementaryDataList()
            };

            controller.ValidateData(wrapper, GetEsfSourceFileModel(), CancellationToken.None);

            //Assert.True(controller.Errors.Any());
        }
        public static IContainer UseFluentMessageValidator(this IContainer container)
        {
            var controller = new ValidationController(new StructureMapServiceProvider(container));

            controller.RegisterFromAssemblies(typeof(CreateTodoListValidator).Assembly);
            container.Configure(expression => expression.For <ValidationController>().Use(controller).Singleton());
            return(container);
        }
        public void GetShape()
        {
            ShapesConfigMockService shapesConfigMockService = new ShapesConfigMockService();
            ValidationController    validationController    = new ValidationController(shapesConfigMockService);
            List <ShapeConfig>      listaRepositorios       = (List <ShapeConfig>)(((OkObjectResult)validationController.GetShape()).Value);

            Assert.True(listaRepositorios.Count > 0);
        }
示例#9
0
            public void WhenValidating_ThenBindingContextHasElement()
            {
                var controller = new ValidationController();

                controller.ValidateCustom(this.element, ValidationConstants.RuntimeValidationCategory);

                this.bindingContext.Verify(x => x.AddExport <IProductElement>(this.element));
            }
示例#10
0
            public void WhenValidating_ThenBindingContextHasProperty()
            {
                var controller = new ValidationController();

                controller.ValidateCustom(this.Property, ValidationConstants.RuntimeValidationCategory);

                this.BindingContext.Verify(x => x.AddExport <IProperty>(this.Property));
            }
        public void Init()
        {
            _ormSettings = new OrmSettings(new AcmeSettings(ConnectionString));
            DataConnection.DefaultSettings = _ormSettings;
            var validator = new SerialRegistrationValidator(new SerialRegistrationRepository(), new SerialRepository());

            _sut = new ValidationController(validator);
        }
 public void Init()
 {
     mediator             = Substitute.For <IMediator>();
     logger               = Substitute.For <ILogger>();
     validationController = new ValidationController(mediator)
     {
         Logger = Substitute.For <ILogger>()
     };
 }
示例#13
0
        public static Validation <String> LongerThan(this Validation <String> item, int limit)
        {
            if (ValidationOn && item.Value.Length <= limit)
            {
                ValidationController.NewError(String.Format("{0} phải dài hơn {1} kí tự", item.ArgName, limit));
            }

            return(item);
        }
示例#14
0
        public static ValidationWithStruct <int> BeginFrom(this ValidationWithStruct <int> item, int begin)
        {
            if (ValidationOn && item.Value < begin)
            {
                ValidationController.NewError(String.Format("{0} phải bắt đầu từ {1}", item.ArgName, begin));
            }

            return(item);
        }
示例#15
0
        public static Validation <String> Between(this Validation <String> item, int from, int to)
        {
            if (ValidationOn && (item.Value.Length < from || item.Value.Length > to))
            {
                ValidationController.NewError(String.Format("{0} phải có chiều dài nằm trong khoảng từ {1} tới {2} kí tự", item.ArgName, from, to));
            }

            return(item);
        }
示例#16
0
        internal PatternModelSchema LoadModelAndDiagrams(
            DslModeling.SerializationResult serializationResult,
            DslModeling.Partition modelPartition,
            string modelFileName,
            DslModeling.Partition diagramPartition,
            IEnumerable <string> diagramFileNames,
            DslModeling.ISchemaResolver schemaResolver,
            ValidationController validationController,
            DslModeling.ISerializerLocator serializerLocator)
        {
            Guard.NotNull(() => serializationResult, serializationResult);
            Guard.NotNull(() => modelPartition, modelPartition);
            Guard.NotNullOrEmpty(() => modelFileName, modelFileName);
            Guard.NotNull(() => diagramPartition, diagramPartition);
            Guard.NotNull(() => diagramFileNames, diagramFileNames);
            Guard.NotNull(() => schemaResolver, schemaResolver);
            Guard.NotNull(() => serializerLocator, serializerLocator);

            PatternModelSchema modelRoot;

            if (!diagramPartition.Store.TransactionActive)
            {
                throw new InvalidOperationException(PatternModelDomainModel.SingletonResourceManager.GetString("MissingTransaction"));
            }

            modelRoot = this.LoadModel(serializationResult, modelPartition, modelFileName, schemaResolver, validationController, serializerLocator);

            if (serializationResult.Failed)
            {
                // don't try to deserialize diagram data if model load failed.
                return(modelRoot);
            }

            var directory         = this.GetDirectory(diagramPartition.Store);
            var diagramSerializer = directory.GetSerializer(PatternModelSchemaDiagram.DomainClassId);
            var views             = modelRoot.Store.ElementDirectory.AllElements.OfType <ViewSchema>().ToList();

            foreach (var view in views)
            {
                var diagramFileName = diagramFileNames.FirstOrDefault(file => Path.GetFileNameWithoutExtension(file).Contains(view.DiagramId));

                if (diagramFileName == null)
                {
                    PatternModelSerializationHelper.CreatePatternModelSchemaDiagram(serializationResult, diagramPartition, modelRoot, view.DiagramId);
                }
                else
                {
                    this.LoadDiagram(serializationResult, diagramPartition, modelRoot, directory, diagramSerializer, diagramFileName, schemaResolver, validationController);
                }
            }

            // Set tracking properties
            ResetTrackingProperties(modelPartition.Store);

            return(modelRoot);
        }
        public void WhenWordIsPassedByGetResultShouldBeNotNull()
        {
            var word = "teste";

            var ctrl = new ValidationController();

            var result = ctrl.Get(word);

            Assert.IsNotNull(result);
        }
        public void Revalidate(IBehaviorContext context, ValidationController controller)
        {
            RequireInitialized();

            ValidationResult result = controller.GetResult(ValidationStep.ViewModel, context.VM);

            _resultManager.UpdateValidationResult(context, result);

            this.ViewModelRevalidateNext(context, controller);
        }
示例#19
0
 public void SetupUnitTest()
 {
     controller = new ValidationController()
     {
         Request = new HttpRequestMessage()
         {
             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
         }
     };
 }
        public void DeleteConfigShape()
        {
            ShapesConfigMockService shapesConfigMockService = new ShapesConfigMockService();
            ValidationController    validationController    = new ValidationController(shapesConfigMockService);
            ShapeConfig             shapeConfig             = ((List <ShapeConfig>)(((OkObjectResult)validationController.GetShape()).Value))[0];

            validationController.DeleteShape(shapeConfig.ShapeConfigID);
            shapeConfig = (ShapeConfig)(((OkObjectResult)validationController.GetShape(shapeConfig.ShapeConfigID)).Value);
            Assert.Null(shapeConfig);
        }
示例#21
0
        public ValidationForm(IBrowser browser)
        {
            myBrowser = browser;

            InitializeComponent();

            myController = new ValidationController();

            myDatumLocators.View = View.List;
        }
示例#22
0
        public static void BeginValidationNext(
            this Behavior behavior,
            IBehaviorContext context,
            ValidationController controller
            )
        {
            IPropertyRevalidationBehavior next;

            if (behavior.TryGetBehavior(out next))
            {
                next.BeginValidation(context, controller);
            }
        }
        public void GetShapeByID()
        {
            ShapesConfigMockService shapesConfigMockService = new ShapesConfigMockService();
            ValidationController    validationController    = new ValidationController(shapesConfigMockService);
            List <ShapeConfig>      listaRepositorios       = (List <ShapeConfig>)(((OkObjectResult)validationController.GetShape()).Value);

            if (listaRepositorios.Count > 0)
            {
                ShapeConfig shapeConfig        = listaRepositorios[0];
                ShapeConfig shapeConfigGetByID = (ShapeConfig)(((OkObjectResult)validationController.GetShape(shapeConfig.ShapeConfigID)).Value);
                Assert.True(shapeConfig.Name.Equals(shapeConfigGetByID.Name));
            }
        }
 internal override EntityDesignerViewModel LoadModelAndDiagram(
     SerializationResult serializationResult, Partition modelPartition, string modelFileName, Partition diagramPartition,
     string diagramFileName, ISchemaResolver schemaResolver, ValidationController validationController,
     ISerializerLocator serializerLocator)
 {
     EntityDesignerViewModel evm = null;
     using (new VsUtils.HourglassHelper())
     {
         evm = LoadModel(serializationResult, modelPartition, modelFileName, schemaResolver, validationController, serializerLocator);
         var diagram = CreateDiagramHelper(diagramPartition, evm);
     }
     return evm;
 }
示例#25
0
        public static void ViewModelRevalidateNext(
            this Behavior behavior,
            IBehaviorContext context,
            ValidationController controller
            )
        {
            IViewModelRevalidationBehavior next;

            if (behavior.TryGetBehavior(out next))
            {
                next.Revalidate(context, controller);
            }
        }
        public void ModifyConfigShapeError2()
        {
            ShapesConfigMockService shapesConfigMockService = new ShapesConfigMockService();
            ValidationController    validationController    = new ValidationController(shapesConfigMockService);

            StringBuilder personShape = new StringBuilder();

            personShape.AppendLine("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>.");
            personShape.AppendLine("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.");
            personShape.AppendLine("@prefix xsd: <http://www.w3.org/2001/XMLSchema#>.");
            personShape.AppendLine("@prefix xml: <http://www.w3.org/XML/1998/namespace>.");
            personShape.AppendLine("@prefix ns: <http://www.w3.org/2003/06/sw-vocab-status/ns#>.");
            personShape.AppendLine("@prefix sh: <http://www.w3.org/ns/shacl#>.");
            personShape.AppendLine("@prefix roh: <http://purl.org/roh#>.");
            personShape.AppendLine("@prefix foaf: <http://purl.org/roh/mirror/foaf#>.");
            personShape.AppendLine("roh:foaf_PersonShape");
            personShape.AppendLine("	a sh:NodeShape ;");
            personShape.AppendLine("	sh:targetClass foaf:Person ;");
            personShape.AppendLine("	sh:property roh:someValuesDataType__foaf__Person__foaf__firstName.");
            personShape.AppendLine("roh:someValuesDataType__foaf__Person__foaf__firstName ");
            personShape.AppendLine("	sh:severity sh:Violation;");
            personShape.AppendLine("	sh:path foaf:firstName;");
            personShape.AppendLine("	sh:qualifiedMinCount  1;");
            personShape.AppendLine("	sh:qualifiedValueShape [");
            personShape.AppendLine("		sh:datatype xsd:string;");
            personShape.AppendLine("	].");
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write(personShape.ToString());
            writer.Flush();
            stream.Position = 0;
            var file = new FormFile(stream, 0, stream.Length, null, "rdf.xml");

            try
            {
                var response = validationController.ModifyShape(Guid.NewGuid(), "name", Guid.NewGuid(), file);
                if (response is BadRequestObjectResult)
                {
                    Assert.True(true);
                }
                else
                {
                    Assert.True(false);
                }
            }
            catch (Exception)
            {
                Assert.True(true);
            }
        }
        partial void SetValidationExtensionRegistrar(ValidationController validationController)
        {
            var validationExtensionRegistrar = new AuthoringValidationExtensionRegistrar();

            if (ModelingCompositionContainer.CompositionService != null)
            {
                ModelingCompositionContainer.CompositionService.SatisfyImportsOnce(validationExtensionRegistrar);
            }

            if (validationController != null)
            {
                validationController.ValidationExtensionRegistrar = validationExtensionRegistrar;
            }
        }
示例#28
0
        internal override EntityDesignerViewModel LoadModelAndDiagram(
            SerializationResult serializationResult, Partition modelPartition, string modelFileName, Partition diagramPartition,
            string diagramFileName, ISchemaResolver schemaResolver, ValidationController validationController,
            ISerializerLocator serializerLocator)
        {
            EntityDesignerViewModel evm = null;

            using (new VsUtils.HourglassHelper())
            {
                evm = LoadModel(serializationResult, modelPartition, modelFileName, schemaResolver, validationController, serializerLocator);
                var diagram = CreateDiagramHelper(diagramPartition, evm);
            }
            return(evm);
        }
        public void ValidateAccount()
        {
            var controller = new ValidationController();

            var accountDetails = new AccountDetails()
            {
                AccountNumber = "12345678", SortCode = "123456"
            };

            var actionResult  = controller.ValidateAccount(accountDetails);
            var contentResult = actionResult as OkNegotiatedContentResult <ValidationResult>;
            var obj           = contentResult.Content;

            Assert.AreEqual(false, obj.IsValid);
        }
示例#30
0
        public NameChangeForm(string name)
        {
            InitializeComponent();

            Name          = name;
            OriginalName  = name;
            ReservedNames = new List <string>();

            _validateController = new ValidationController()
            {
                OKButton = _buttonOK,
            };

            _validateController.RegisterControl(_fieldName,
                                                ValidationController.ValidateNonEmptyName("Name", _fieldName, ReservedNameEnumerator));
        }
示例#31
0
        public void TestPerformValidation_Length()
        {
            var customer = new Customer
            {
                Name = "Maryika",
                IsFinraMember = true
            };
            var validationController = new ValidationController();

            validationController.PerformValidation(customer);
            Assert.IsFalse(customer.Errors.All.Any());
            CollectionAssert.IsEmpty(customer.Errors.All);

            customer.Name = "";
            validationController.PerformValidation(customer);
            Assert.IsTrue(customer.Errors.All.Any());
            Assert.AreEqual(2, customer.Errors.Count);
            CollectionAssert.AreEquivalent(Customer.NameErrors, customer.Errors[() => customer.Name]);

            customer.Name = "Some long name exceeds max";
            validationController.PerformValidation(customer);
            Assert.IsTrue(customer.Errors.All.Any());
            Assert.AreEqual(1, customer.Errors.Count);
            Assert.AreEqual("Name is too long (maximum is 12).", customer.Errors[() => customer.Name].First());

            var account = new Account { Number = "A0000000001" };
            validationController.PerformValidation(account);
            Assert.IsTrue(account.Errors.All.Any());
            Assert.AreEqual(1, account.Errors.Count);
            Assert.AreEqual("Number is too long (maximum is 10).", account.Errors[() => account.Number].First());

            account.Number = null;
            validationController.PerformValidation(account);
            Assert.IsFalse(account.Errors.All.Any());
            CollectionAssert.IsEmpty(account.Errors.All);

            var address = new Address();
            validationController.PerformValidation(address);
            Assert.IsTrue(address.Errors.All.Any());
            Assert.AreEqual(1, address.Errors.Count);
            Assert.AreEqual("StateCode should be 2 characters.", address.Errors[() => address.StateCode].First());

            address.StateCode = "NY";
            validationController.PerformValidation(address);
            Assert.IsFalse(address.Errors.All.Any());
            CollectionAssert.IsEmpty(address.Errors.All);
        }
示例#32
0
        public void TestCreateFolder()
        {
            TreeNode el = new TreeNode(0, "Creating digital images folder");

            if (!Regex.IsMatch(el.Name, @"^[a-zA-Z ]+$"))
            {
                Assert.Fail();
            }
            ValidationController validation = new ValidationController();
            var isValid = validation.IsFolderNameUnique(el);

            isValid.Should().BeOfType <JsonResult>();
            if (!Convert.ToBoolean(isValid.Data))
            {
                Assert.Fail();
            }
        }
示例#33
0
		/// <summary>
		/// Validates the model element.
		/// </summary>
		/// <param name="modelElement">The model element.</param>
		/// <param name="validationController">The validation controller.</param>
		/// <returns></returns>
        public static bool ValidateModelElement(ModelElement modelElement, ValidationController validationController)
        {
            Guard.ArgumentNotNull(modelElement, "modelElement");
            Guard.ArgumentNotNull(validationController, "validationController");

            bool isValid = true;
            HashSet<ModelElement> elementList = new HashSet<ModelElement>();
            FullDepthElementWalker elementWalker =
                new FullDepthElementWalker(new ModelElementVisitor(elementList), new EmbeddingReferenceVisitorFilter(), false);

            elementWalker.DoTraverse(modelElement);
            validationController.ClearMessages();
            isValid = validationController.Validate(elementList, ValidationCategories.Menu);
            elementList.Clear();
            
            return isValid;
        }
		public void TestValidationWithOneMel()
		{
			Store store = new Store(new Type[] { typeof(MockDomainModel) });
			Partition partition = new Partition(store);

			using(Transaction t = store.TransactionManager.BeginTransaction())
			{
				ExtensibleMockModelElement mockModelElement = new ExtensibleMockModelElement(partition, "Foo");

				ValidationController controller = new ValidationController();

				bool Isvalid = ModelValidator.ValidateModelElement(mockModelElement, controller);

				Assert.AreEqual(true, Isvalid);

				t.Rollback();
			}
		}
        internal override EntityDesignerViewModel LoadModel(
            SerializationResult serializationResult, Partition partition, string fileName, ISchemaResolver schemaResolver,
            ValidationController validationController, ISerializerLocator serializerLocator)
        {
            var docData = VSHelpers.GetDocData(PackageManager.Package, fileName) as IEntityDesignDocData;
            docData.CreateAndLoadBuffer();

            EntityDesignerViewModel evm = null;

            var serializationContext = new SerializationContext(GetDirectory(partition.Store), fileName, serializationResult);
            var transactionContext = new TransactionContext();
            transactionContext.Add(SerializationContext.TransactionContextKey, serializationContext);

            using (var t = partition.Store.TransactionManager.BeginTransaction("Load Model from " + fileName, true, transactionContext))
            {
                var uri = Tools.XmlDesignerBase.Base.Util.Utils.FileName2Uri(fileName);
                var context = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(uri);
                evm =
                    ModelTranslatorContextItem.GetEntityModelTranslator(context).TranslateModelToDslModel(null, partition) as
                    EntityDesignerViewModel;

                if (evm == null)
                {
                    serializationResult.Failed = true;
                }
                else
                {
                    if (t.IsActive)
                    {
                        t.Commit();
                    }
                }
            }

            // Validate imported model
            if (!serializationResult.Failed
                && (validationController != null))
            {
                validationController.Validate(partition, ValidationCategories.Load);
            }
            return evm;
        }
        public override HostDesignerModel LoadModelAndDiagram(
            SerializationResult serializationResult, 
            Partition modelPartition, 
            string modelFileName, 
            Partition diagramPartition, 
            string diagramFileName, 
            ISchemaResolver schemaResolver, 
            ValidationController validationController, 
            ISerializerLocator serializerLocator)
        {
            ISchemaResolver resolver = new CustomModelingSchemaResolver(schemaResolver, "GeneratedCode\\HostDesignerSchema.xsd");

            return base.LoadModelAndDiagram(
                serializationResult,
                modelPartition,
                modelFileName,
                diagramPartition,
                diagramFileName,
                resolver,
                validationController,
                serializerLocator);
        }
示例#37
0
        public void TestPerformValidation_Presence()
        {
            var customer = new Customer();
            var validationController = new ValidationController();

            Assert.IsFalse(customer.Errors.All.Any());
            CollectionAssert.IsEmpty(customer.Errors.All);

            validationController.PerformValidation(customer);

            Assert.IsTrue(customer.Errors.All.Any());
            CollectionAssert.IsNotEmpty(customer.Errors.All);
            Assert.AreEqual(3, customer.Errors.Count);

            CollectionAssert.AreEquivalent(Customer.NameErrors, customer.Errors[() => customer.Name]);
            var finraError = customer.Errors.ForProperty(() => customer.IsFinraMember).First();
            Assert.AreEqual("IsFinraMember can't be empty.", finraError);

            customer.IsFinraMember = false;
            validationController.PerformValidation(customer);

            Assert.IsTrue(customer.Errors.All.Any());
            CollectionAssert.IsNotEmpty(customer.Errors.All);
            Assert.AreEqual(2, customer.Errors.Count);
            CollectionAssert.IsEmpty(customer.Errors.ForProperty(() => customer.IsFinraMember));
            CollectionAssert.IsNotEmpty(customer.Errors[() => customer.Name]);
            CollectionAssert.AreEquivalent(Customer.NameErrors, customer.Errors[() => customer.Name]);

            customer.Name = UnitTestHelper.CUSTOMER_NAME;
            validationController.PerformValidation(customer);

            Assert.IsFalse(customer.Errors.All.Any());
            CollectionAssert.IsEmpty(customer.Errors.All);
            CollectionAssert.IsEmpty(customer.Errors[() => customer.Name]);
        }
        /// <summary>
        /// Gets the error text.
        /// </summary>
        public virtual string this[string columnName]
        {
            get
            {
                // Should we validate InstanceName? if (columnName == "InstanceName")
                // TODO: verify if there is a cheaper way of getting errors without the need to revalidate each time, because some validation is
                // already happening elsewhere (for example, errors are being shown in the VS' Error List).
                var property = this.Properties.Find(p => p.DefinitionName == columnName);
                if (property != null)
                {
                    var validationController = new ValidationController();
                    if (!validationController.ValidateCustom(property, ValidationConstants.RuntimeValidationCategory))
                    {
                        var errors = validationController.ErrorMessages.Select(e => e.Description).Where(d => d != null).ToList();
                        if (errors.Count > 0)
                        {
                            return string.Join(Environment.NewLine, errors);
                        }
                    }
                }

                return null;
            }
        }
            public void WhenValidating_ThenBindingContextHasElement()
            {
                var controller = new ValidationController();

                controller.ValidateCustom(this.element, ValidationConstants.RuntimeValidationCategory);

                this.bindingContext.Verify(x => x.AddExport<IProductElement>(this.element));
            }
        private void LoadDiagram(
            DslModeling.SerializationResult serializationResult,
            DslModeling.Partition diagramPartition,
            PatternModelSchema modelRoot,
            DslModeling.DomainXmlSerializerDirectory directory,
            DslModeling.DomainClassXmlSerializer diagramSerializer,
            string diagramFileName,
            DslModeling.ISchemaResolver schemaResolver,
            ValidationController validationController)
        {
            if (diagramSerializer != null)
            {
                PatternModelSchemaDiagram diagram = null;

                using (FileStream fileStream = File.OpenRead(diagramFileName))
                {
                    var serializationContext = new DslModeling.SerializationContext(directory, fileStream.Name, serializationResult);
                    this.InitializeSerializationContext(diagramPartition, serializationContext, true);
                    var transactionContext = new DslModeling.TransactionContext();
                    transactionContext.Add(DslModeling.SerializationContext.TransactionContextKey, serializationContext);

                    using (var transaction = diagramPartition.Store.TransactionManager.BeginTransaction(Resources.PatternModelSerializationHelper_TransactionDescriptionLoadingDiagram, true, transactionContext))
                    {
                        // Ensure there is some content in the file. Blank (or almost blank, to account for encoding header bytes, etc.)
                        // files will cause a new diagram to be created and returned 
                        if (fileStream.Length > 5)
                        {
                            var settings = PatternModelSerializationHelper.Instance.CreateXmlReaderSettings(serializationContext, false);
                            try
                            {
                                using (var reader = XmlReader.Create(fileStream, settings))
                                {
                                    reader.MoveToContent();
                                    diagram = diagramSerializer.TryCreateInstance(serializationContext, reader, diagramPartition) as PatternModelSchemaDiagram;
                                    if (diagram != null)
                                    {
                                        this.ReadRootElement(serializationContext, diagram, reader, schemaResolver);
                                    }
                                }
                            }
                            catch (XmlException ex)
                            {
                                DslModeling.SerializationUtilities.AddMessage(serializationContext, DslModeling.SerializationMessageKind.Error, ex);
                            }

                            if (serializationResult.Failed)
                            {
                                // Serialization error encountered, rollback the transaction.
                                diagram = null;
                                transaction.Rollback();
                            }
                        }

                        if (diagram == null && !serializationResult.Failed)
                        {
                            // Create diagram if it doesn't exist
                            if (diagramFileName.EndsWith(DesignerConstants.DiagramFileExtension, StringComparison.OrdinalIgnoreCase))
                            {
                                diagram = new PatternModelSchemaDiagram(
                                    diagramPartition.Store,
                                    new DslModeling.PropertyAssignment(DslDiagrams.Diagram.NameDomainPropertyId, Guid.NewGuid()));
                            }
                            else
                            {
                                diagram = this.CreateDiagramHelper(diagramPartition, modelRoot);
                            }
                        }

                        if (transaction.IsActive)
                        {
                            transaction.Commit();
                        }
                    } // End inner Tx

                    // Do load-time validation if a ValidationController is provided.
                    if (!serializationResult.Failed && validationController != null)
                    {
                        using (new SerializationValidationObserver(serializationResult, validationController))
                        {
                            validationController.Validate(diagramPartition, ValidationCategories.Load);
                        }
                    }
                }

                if (diagram != null)
                {
                    if (!serializationResult.Failed)
                    {	// Succeeded.
                        diagram.ModelElement = modelRoot;
                        diagram.PostDeserialization(true);
                        this.CheckForOrphanedShapes(diagram, serializationResult);
                    }
                    else
                    {	// Failed.
                        diagram.PostDeserialization(false);
                    }
                }
            }
        }
        internal PatternModelSchema LoadModelAndDiagrams(
            DslModeling.SerializationResult serializationResult,
            DslModeling.Partition modelPartition,
            string modelFileName,
            DslModeling.Partition diagramPartition,
            IEnumerable<string> diagramFileNames,
            DslModeling.ISchemaResolver schemaResolver,
            ValidationController validationController,
            DslModeling.ISerializerLocator serializerLocator)
        {
            Guard.NotNull(() => serializationResult, serializationResult);
            Guard.NotNull(() => modelPartition, modelPartition);
            Guard.NotNullOrEmpty(() => modelFileName, modelFileName);
            Guard.NotNull(() => diagramPartition, diagramPartition);
            Guard.NotNull(() => diagramFileNames, diagramFileNames);
            Guard.NotNull(() => schemaResolver, schemaResolver);
            Guard.NotNull(() => serializerLocator, serializerLocator);

            PatternModelSchema modelRoot;

            if (!diagramPartition.Store.TransactionActive)
            {
                throw new InvalidOperationException(PatternModelDomainModel.SingletonResourceManager.GetString("MissingTransaction"));
            }

            modelRoot = this.LoadModel(serializationResult, modelPartition, modelFileName, schemaResolver, validationController, serializerLocator);

            if (serializationResult.Failed)
            {
                // don't try to deserialize diagram data if model load failed.
                return modelRoot;
            }

            var directory = this.GetDirectory(diagramPartition.Store);
            var diagramSerializer = directory.GetSerializer(PatternModelSchemaDiagram.DomainClassId);
            var views = modelRoot.Store.ElementDirectory.AllElements.OfType<ViewSchema>().ToList();

            foreach (var view in views)
            {
                var diagramFileName = diagramFileNames.FirstOrDefault(file => Path.GetFileNameWithoutExtension(file).Contains(view.DiagramId));

                if (diagramFileName == null)
                {
                    PatternModelSerializationHelper.CreatePatternModelSchemaDiagram(serializationResult, diagramPartition, modelRoot, view.DiagramId);
                }
                else
                {
                    this.LoadDiagram(serializationResult, diagramPartition, modelRoot, directory, diagramSerializer, diagramFileName, schemaResolver, validationController);
                }
            }

            // Set tracking properties
            ResetTrackingProperties(modelPartition.Store);

            return modelRoot;
        }
        /// <summary>
        /// Loads the model from a filename.
        /// </summary>
        /// <param name="serializationResult">The seriazation result.</param>
        /// <param name="partition">The state partition.</param>
        /// <param name="fileName">the filename of the model.</param>
        /// <param name="schemaResolver">The schemaresolver.</param>
        /// <param name="validationController">The validation controller.</param>
        /// <param name="serializerLocator">The serialization locator.</param>
        /// <remarks>This overload is called by teh T4Runner engine.</remarks>
        public override PatternModelSchema LoadModel(DslModeling.SerializationResult serializationResult, DslModeling.Partition partition, string fileName, DslModeling.ISchemaResolver schemaResolver, ValidationController validationController, DslModeling.ISerializerLocator serializerLocator)
        {
            var productLine = base.LoadModel(serializationResult, partition, fileName, schemaResolver, validationController, serializerLocator);

            // Set tracking properties
            if (partition != null)
            {
                ResetTrackingProperties(partition.Store);
            }

            return productLine;
        }
示例#43
0
            public void WhenValidating_ThenBindingContextHasProperty()
            {
                var controller = new ValidationController();

                controller.ValidateCustom(this.Property, ValidationConstants.RuntimeValidationCategory);

                this.BindingContext.Verify(x => x.AddExport<IProperty>(this.Property));
            }
示例#44
0
 public void TestPerformValidation_NullArg()
 {
     var validationController = new ValidationController();
     Assert.Throws<ArgumentNullException>(() => validationController.PerformValidation(null));
 }