public static void RunErrorMessages(Employee employee)
        {
            var engine = new Engine();
            engine.For<Person>()
                    .Setup(m => m.Name)
                        .MustNotBeNullOrEmpty()
                        .WithMessage("Name must not be empty") //Only when name is null or empty
                        .MustMatchRegex(@"^[a-z]+$")
                        .WithMessage("Name contains invalid characters") //Only when name contains invalid characters

                    .Setup(m => m.Email)
                        .WithMessage("Invalid email address") //For any rule breakers on the Email property.
                        .MustNotBeNullOrEmpty()
                        .MustMatchRegex(@"^[a-z]+@[a-z]+(\.[a-z]+)*$");

            engine.For<Employee>() //Member will inherit rules set for a Person.
                    .Setup(m => m.EmployeeNumber)
                        .WithMessage("Employee number is not valid")
                        .MustBeGreaterThan(0);

            var report = new ValidationReport(engine);
            var result = report.Validate(employee).ToString();
            var errors = report.GetErrorMessages(employee);
            employee.IsValid = result;
            string flatErrors = string.Empty;
            foreach (string s in errors)
                flatErrors += s;
            employee.Errors = flatErrors;
        }
 public PersonValidationTests()
 {
     personValidator = new PersonValidator();
     validator = new Validator();
        // personValidator.Define(engine);
     report = new ValidationReport(engine);
 }
        public ValidationReportModel(ValidationReport validationReport)
        {
            if (validationReport == null)
            {
                throw new ArgumentNullException(nameof(validationReport));
            }
            this.validationReport = validationReport;

            Initialize();
        }
        public void ShouldValidateAllItemsInEnumeration()
        {
            var member1 = new Member(null);
            var member2 = new Member(null);
            var club = new Club(new Member("president"), member1, member2);
            var report = new ValidationReport();
            _en1.Validate(club, report, ValidationReportDepth.FieldShortCircuit);

            var memberNameExp = new EquatableExpression(ExpressionHelper.New<Member, string>(mm => mm.Name));
            Assert.IsTrue(report.HasError(member1, memberNameExp), "Expected validation failure for member1. Name was null...");
            Assert.IsTrue(report.HasError(member2, memberNameExp), "Expected validation failure for member2. Name was null...");
        }
 public void DoggieReportNoError()
 {
     XmlDocument dogs = new XmlDocument();
      dogs.LoadXml(@"
     <dogs>
       <dog petname='spot'><nose/><ear/><bone/><ear/></dog>
     </dogs>");
      StringBuilder svrl = new StringBuilder();
      SchematronValidator validator = new SchematronValidator("Schematron/Samples/Dog.sch");
      ValidationReport report = new ValidationReport(validator, svrl);
      validator.Validate(dogs);
      Assert.IsFalse(report.HasValidationErrors);
 }
 public void DoggieConsoleReport()
 {
     XmlDocument dogs = new XmlDocument();
      dogs.LoadXml(@"
     <dogs>
       <dog petname='spot'><nose/><ear/><bone/><ear/></dog>
       <dog petname='hungry'><nose/><ear/><ear/></dog>
       <dog petname='emanon'><nose/><ear/><bone/></dog>
       <dog petname='smelly'><ear/><bone/><ear/></dog>
     </dogs>");
      SchematronValidator validator = new SchematronValidator("Schematron/Samples/Dog.sch");
      ValidationReport report = new ValidationReport(validator, Console.Out);
      validator.Validate(dogs);
 }
        public void ShouldShortCircuit()
        {
            var builder = new Fluent.FluentBuilder();
            builder.For<Member>()
                .MustPassGenericRule(m => { throw new AssertFailedException("Should have short-circuited."); });
            var en2 = builder.Build(_builder1);

            var member1 = new Member(null);
            var memberNameExp = ExpressionHelper.New<Member, string>(mm => mm.Name);
            var report = new ValidationReport();

            //Only short-circuit here would work...Others would throw exception...
            _en1.Validate(member1, report, ValidationReportDepth.ShortCircuit);
        }
        public void DoggieReport()
        {
            XmlDocument dogs = new XmlDocument();
             dogs.LoadXml(@"
            <dogs>
              <dog petname='spot'><nose/><ear/><bone/><ear/></dog>
              <dog petname='hungry'><nose/><ear/><ear/></dog>
              <dog petname='emanon'><nose/><ear/><bone/></dog>
              <dog petname='smelly'><ear/><bone/><ear/></dog>
            </dogs>");
             StringBuilder svrl = new StringBuilder();
             SchematronValidator validator = new SchematronValidator("Schematron/Samples/Dog.sch");
             ValidationReport report = new ValidationReport(validator, svrl);
             validator.Validate(dogs);
             Console.WriteLine(svrl.ToString());

             XmlDocument doggieReport = new XmlDocument();
             doggieReport.LoadXml(svrl.ToString());
             validator = new SchematronValidator(Schematron.Default.ValidationReportLanguage);
             validator.Validate(doggieReport);
        }
        public void ShouldFindErrorMessage2()
        {
            var builder = new Fluent.FluentBuilder();

            builder.For<CompositeClass>()
                    .Setup(c => c.Value)
                        .MustBeGreaterThan(0)
                    .Setup(c => c.C)
                        .MustNotBeNull()
                    .Setup(c => c.C.C)
                        .WithMessage("Composed value is not valid")
                        .MustBeBetween(1, 10, Rules.BetweenRuleBoundsOption.BothInclusive)
                        ;
            var engine = builder.Build();
            var o = new CompositeClass() { C = new ClassC() };
            var r = new ValidationReport(engine);
            r.Validate(o);
            Assert.AreEqual("Composed value is not valid", r.GetErrorMessage(o.C, f => f.C));
            //NOTE: There are no errors on ClassC! Should return null.
            Assert.IsNull(r.GetErrorMessage(o, f => f.C.C));

        }
        public void TestMessageForProperty()
        {
            var builder = new Fluent.FluentBuilder();
            builder.For<MyMessageTestClass>()
                .WithMessage("Object is not valid")
                .Setup(m => m.A)
                    .WithMessage("Property A is not valid.")
                    .MustBeLessThanOrEqualTo(10)
                    .MustNotEqual(5)
                    .MustNotEqual(0)
                    .WithMessage("Must not equal zero")
                .Setup(m => m.B)
                    .MustEqual(0);


            var engine = builder.Build();
            var report = new ValidationReport(engine);
            var obj = new MyMessageTestClass(11, 0);
            engine.Validate(obj, report, ValidationReportDepth.FieldShortCircuit);
            Assert.AreEqual("Property A is not valid.", report.GetErrorMessage(obj, o => o.A));

            report = new ValidationReport(engine);
            obj = new MyMessageTestClass(5, 0);
            engine.Validate(obj, report, ValidationReportDepth.FieldShortCircuit);
            Assert.AreEqual("Property A is not valid.", report.GetErrorMessage(obj, o => o.A));

            report = new ValidationReport(engine);
            obj = new MyMessageTestClass(0, 0);
            engine.Validate(obj, report, ValidationReportDepth.FieldShortCircuit);
            Assert.AreEqual("Must not equal zero", report.GetErrorMessage(obj, o => o.A));

            report = new ValidationReport(engine);
            obj = new MyMessageTestClass(9, 1);
            engine.Validate(obj, report, ValidationReportDepth.FieldShortCircuit);
            Assert.AreEqual("Object is not valid", report.GetErrorMessage(obj, o => o.B));
        }
Beispiel #11
0
 internal virtual void HandleCommandValidationFailure(ICommand command, ValidationReport validationReport)
 {
     throw new CommandValidationException(
               $"Validation error while applying {command.CommandName} to a {GetType().Name}.",
               validationReport);
 }
Beispiel #12
0
 void Because(Post post)
 {
     _report = _sut.Validate(post);
 }
		protected override void Because()
		{
			_report = _sut.Validate(_settings);
		}
        //-------------------------------------------------------------------------------------------------//
        /// <summary>
        /// Parse the XML specification string to check its validity. No exceptions are thrown back to the
        /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed
        /// in 'errorMessage' where it can be examined by the calling method.
        /// </summary>
        /// <param name="xmlSpecification"></param>
        public override ValidationReport Parse(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Parse";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Catch all exceptions and log errors, don't throw back to caller
            //
            ValidationReport validationReport = null;
            try
            {
                //
                // Call the base class to parse its part
                //
                validationReport = base.Parse(xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new Exception(validationReport.errorMessage);
                }

                // Create new validation report
                validationReport = new ValidationReport();

                //
                // Create an instance of the driver for the specified setup and then
                // get the driver's execution time for this specification
                //
                int executionTime = -1;
                if (this.SetupId.Equals(Consts.STRXML_SetupId_VoltageVsSpeed))
                {
                    //
                    // Get the speed range and validate
                    //
                    this.speed = new MinMaxStep();
                    this.speed.min = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedMin);
                    this.speed.max = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedMax);
                    this.speed.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedStep);

                    this.validation.ValidateSpeed(this.speed);

                    DriverVoltageVsSpeed driver = new DriverVoltageVsSpeed(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_VoltageVsField))
                {
                    //
                    // Get the field range and validate
                    //
                    this.field = new MinMaxStep();
                    this.field.min = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldMin);
                    this.field.max = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldMax);
                    this.field.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldStep);

                    this.validation.ValidateField(this.field);

                    DriverVoltageVsField driver = new DriverVoltageVsField(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_VoltageVsLoad))
                {
                    //
                    // Get the load range and validate
                    //
                    this.load = new MinMaxStep();
                    this.load.min = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_loadMin);
                    this.load.max = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_loadMax);
                    this.load.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_loadStep);

                    this.validation.ValidateLoad(this.load);

                    DriverVoltageVsLoad driver = new DriverVoltageVsLoad(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_SpeedVsVoltage))
                {
                    //
                    // Get the speed range and validate
                    //
                    this.speed = new MinMaxStep();
                    this.speed.min = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedMin);
                    this.speed.max = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedMax);
                    this.speed.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedStep);

                    this.validation.ValidateSpeed(this.speed);

                    DriverSpeedVsVoltage driver = new DriverSpeedVsVoltage(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_SpeedVsField))
                {
                    //
                    // Get the field range and validate
                    //
                    this.field = new MinMaxStep();
                    this.field.min = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldMin);
                    this.field.max = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldMax);
                    this.field.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldStep);

                    this.validation.ValidateField(this.field);

                    DriverSpeedVsField driver = new DriverSpeedVsField(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }

                //
                // Specification is valid
                //
                validationReport.estRuntime = executionTime + TIME_SECS_AdministrationExecution;
                validationReport.accepted = true;
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            string logMessage = STRLOG_Accepted + validationReport.accepted.ToString();
            if (validationReport.accepted == true)
            {
                logMessage += Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + validationReport.estRuntime.ToString() + STRLOG_seconds;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return validationReport;
        }
Beispiel #15
0
        //-------------------------------------------------------------------------------------------------//

        public override ExperimentInfo RunExperiment(ExperimentInfo experimentInfo)
        {
            const string STRLOG_MethodName = "RunExperiment";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            // Create a result report ready to fill in
            experimentInfo.resultReport = new ResultReport();

            try
            {
                //
                // Parse the XML specification string to generate a validation report (should be accepted!)
                //
                Specification    specification    = new Specification(this.configuration, this.equipmentServiceProxy);
                ValidationReport validationReport = specification.Parse(experimentInfo.xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new ArgumentException(validationReport.errorMessage);
                }
                experimentInfo.setupId = specification.SetupId;

                //
                // Create an instance of the driver for the specified setup and then
                // execute the experiment and return the result information
                //
                ResultInfo resultInfo = null;
                if (specification.SetupId.Equals(Consts.STRXML_SetupId_RadioactivityVsTime) ||
                    specification.SetupId.Equals(Consts.STRXML_SetupId_RadioactivityVsDistance))
                {
                    if (this.equipmentServiceProxy != null)
                    {
                        //
                        // Hardware is available to this unit, run it there
                        //
                        DriverRadioactivity driver = new DriverRadioactivity(this.equipmentServiceProxy, this.configuration, this.labExperimentInfo.cancelExperiment);
                        resultInfo = (ResultInfo)driver.Execute(specification);
                    }
                    else
                    {
                        //
                        // This unit does not have hardware available, run the simulation instead
                        //
                        DriverSimActivity driver = new DriverSimActivity(this.configuration, this.labExperimentInfo.cancelExperiment);
                        resultInfo = (ResultInfo)driver.Execute(specification);
                    }
                }
                else if (specification.SetupId.Equals(Consts.STRXML_SetupId_RadioactivityVsAbsorber))
                {
                    DriverAbsorbers driver = new DriverAbsorbers(this.equipmentServiceProxy, this.configuration, this.labExperimentInfo.cancelExperiment);
                    resultInfo = (ResultInfo)driver.Execute(specification);
                }
                else if (specification.SetupId.Equals(Consts.STRXML_SetupId_SimActivityVsTime) ||
                         specification.SetupId.Equals(Consts.STRXML_SetupId_SimActivityVsDistance))
                {
                    DriverSimActivity driver = new DriverSimActivity(this.configuration, this.labExperimentInfo.cancelExperiment);
                    resultInfo = (ResultInfo)driver.Execute(specification);
                }
                else if (specification.SetupId.Equals(Consts.STRXML_SetupId_SimActivityVsTimeNoDelay) ||
                         specification.SetupId.Equals(Consts.STRXML_SetupId_SimActivityVsDistanceNoDelay))
                {
                    DriverSimActivity driver = new DriverSimActivity(this.configuration, this.labExperimentInfo.cancelExperiment, false);
                    resultInfo = (ResultInfo)driver.Execute(specification);
                }

                //
                // Create an instance of LabExperimentResult to convert the experiment results to an XML string
                //
                ExperimentResult experimentResult = new ExperimentResult(
                    experimentInfo.experimentId, experimentInfo.sbName, DateTime.Now,
                    this.unitId, (Configuration)this.labConfiguration, specification, resultInfo);

                //
                // Fill in the result report
                //
                experimentInfo.resultReport.experimentResults = experimentResult.ToString();
                experimentInfo.resultReport.statusCode        = (int)resultInfo.statusCode;
                experimentInfo.resultReport.errorMessage      = resultInfo.errorMessage;
            }
            catch (Exception ex)
            {
                experimentInfo.resultReport.statusCode   = (int)StatusCodes.Failed;
                experimentInfo.resultReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName);

            return(experimentInfo);
        }
        public void ShouldCulpabiliseComposition()
        {
            var builder = new Fluent.FluentBuilder();
            builder.For<Foo>()
                    .Setup(f => f.Foo1.Value)
                        .MustEqual(1);

            var engine = builder.Build();
            var foo = new Foo(1) { Foo1 = new Foo(0) };
            var report = new ValidationReport(engine);
            
            Assert.IsFalse(report.Validate(foo));
            ValidationError[] errors;
            Assert.IsTrue(report.HasError(foo.Foo1, f => f.Value, out errors));

        }
Beispiel #17
0
        static void Main(string[] args)
        {
            string pathToSign      = Path.Combine("Resources", "test.pdf");
            string pathCertificate = Path.Combine("Resources", "test.p12");
            string pathSigned      = "test.pdf.p7m";

            Document             toBeSigned = new FileDocument(pathToSign);
            Pkcs12SignatureToken token      = new Pkcs12SignatureToken("password", pathCertificate);
            IDssPrivateKeyEntry  privateKey = token.GetKeys()[0];

            SignatureParameters parameters = new SignatureParameters();

            parameters.SignaturePackaging = SignaturePackaging.ENVELOPING;
            parameters.SigningCertificate = privateKey.GetCertificate();
            parameters.CertificateChain   = privateKey.GetCertificateChain();
            parameters.SigningDate        = DateTime.Now;
            parameters.DigestAlgorithm    = DigestAlgorithm.SHA256;

            CAdESService service = new CAdESService();

            parameters.SignatureFormat = EU.Europa.EC.Markt.Dss.Signature.SignatureFormat.CAdES_BES;

            /* CERTIFIED TIMESTAMP
             * var ocspSource1 = new OnlineOcspSource();
             * var crlSource1 = new FileCacheCrlSource();
             * var crlOnline1 = new OnlineCrlSource();
             * crlOnline1.IntermediateAcUrl = @"http://www.eci.bce.ec/CRL/cacrl.crl";
             * crlSource1.CachedSource = crlOnline1;
             * var verifier1 = new OCSPAndCRLCertificateVerifier(crlSource1, ocspSource1);
             * var estado = verifier1.Check(privateKey.GetCertificate(), privateKey.GetCertificateChain()[1], DateTime.Now);
             */

            /*
             * //parameters.SignatureFormat = SignatureFormat.CAdES_T; //Se añade TSA.
             * parameters.SignatureFormat = EU.Europa.EC.Markt.Dss.Signature.SignatureFormat.CAdES_C; //Se añade CRL y OCSP.
             * //parameters.SignatureFormat = SignatureFormat.CAdES_X; //No se añade nada más al código.
             * //parameters.SignatureFormat = EU.Europa.EC.Markt.Dss.Signature.SignatureFormat.CAdES_XL; //No se añade nada más al código.
             *
             * string urlTss = @"http://tsp.iaik.tugraz.at/tsp/TspRequest";
             * string username = "";
             * string password = "";
             *
             *
             * OnlineTspSource tspSource = new OnlineTspSource(urlTss, username, password);
             * service.TspSource = tspSource;
             *
             * OnlineOcspSource ocspSource = new OnlineOcspSource();
             * TrustedListCertificateVerifier verifier = new TrustedListCertificateVerifier();
             * FileCacheCrlSource crlSource = new FileCacheCrlSource();
             * OnlineCrlSource crlOnline = new OnlineCrlSource();
             * crlOnline.IntermediateAcUrl = @"http://www.eci.bce.ec/CRL/cacrl.crl";
             * //@"http://www.eci.bce.ec/CRL/pruebas/cacrl.crl"
             *
             * crlSource.CachedSource = crlOnline;
             * verifier.CrlSource = crlSource;
             * verifier.OcspSource = ocspSource;
             *
             * ValidationContext validationContext = verifier.ValidateCertificate(parameters.SigningCertificate, DateTime.Now,
             *  new EU.Europa.EC.Markt.Dss.Validation.Certificate.CompositeCertificateSource(
             *      new EU.Europa.EC.Markt.Dss.Validation.Certificate.ListCertificateSource(parameters.CertificateChain)), null, null);
             *
             * service.Verifier = verifier;
             */

            /* DOUBLE-SIGN
             * Document contentInCMS = null;
             *
             * try
             * {
             *  CmsSignedData cmsData = new CmsSignedData(toBeSigned.OpenStream());
             *  if (cmsData != null && cmsData.SignedContent != null
             *      && cmsData.SignedContent.GetContent() != null)
             *  {
             *      Stream buf = new MemoryStream();
             *      cmsData.SignedContent.Write(buf);
             *      buf.Seek(0, SeekOrigin.Begin);
             *      contentInCMS = new InMemoryDocument(Streams.ReadAll(buf));
             *  }
             * }
             * catch (CmsException)
             * {
             * }
             *
             * Stream iStream = service.ToBeSigned(contentInCMS ?? toBeSigned, parameters);
             * byte[] signatureValue = token.Sign(iStream, parameters.DigestAlgorithm, privateKey);
             *
             * // We invoke the service to sign the document with the signature value obtained in the previous step.
             * Document signedDocument = contentInCMS != null
             *  ? service.AddASignatureToDocument(toBeSigned, parameters, signatureValue)
             *  : service.SignDocument(toBeSigned, parameters, signatureValue);
             *
             * FileStream fs = new FileStream(pathParaFirmado, FileMode.OpenOrCreate);
             * Streams.PipeAll(signedDocument.OpenStream(), fs);
             * fs.Close();
             * return;
             */

            Document signedDocument = service.SignDocument(toBeSigned, parameters,
                                                           (hashbytes) => privateKey.Encrypt(hashbytes));

            FileStream fs = new FileStream(pathSigned, FileMode.OpenOrCreate);

            Streams.PipeAll(signedDocument.OpenStream(), fs);
            fs.Close();

            return;

            // Already signed document
            Document document = new FileDocument(pathSigned);

            SignedDocumentValidator validator;

            validator = SignedDocumentValidator.FromDocument(document);
            //validator.CertificateVerifier = verifier;
            validator.ExternalContent = document;

            ValidationReport     report = validator.ValidateDocument();
            SignatureInformation info   = report.SignatureInformationList[0];

            Console.WriteLine("--> Final_Conclusion: ");
            Console.WriteLine(info.FinalConclusion); // --> AdES
            Console.ReadKey();
        }
		void Because(Post post)
		{
			_report = _sut.Validate(post);
		}
Beispiel #19
0
        //-------------------------------------------------------------------------------------------------//

        public override ExperimentInfo RunExperiment(ExperimentInfo experimentInfo)
        {
            const string STRLOG_MethodName = "RunExperiment";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            // Create a result report ready to fill in
            experimentInfo.resultReport = new ResultReport();

            try
            {
                //
                // Parse the XML specification string to generate a validation report (should be accepted!)
                //
                Specification    specification    = new Specification(this.configuration, this.equipmentServiceProxy);
                ValidationReport validationReport = specification.Parse(experimentInfo.xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new ArgumentException(validationReport.errorMessage);
                }
                experimentInfo.setupId = specification.SetupId;

                //
                // Create an instance of the driver for the specified setup and then
                // execute the experiment and return the result information
                //
                ResultInfo resultInfo = null;
                if (specification.SetupId.Equals(Consts.STRXML_SetupId_LockedRotor))
                {
                    DriverLockedRotor driver = new DriverLockedRotor(this.equipmentServiceProxy, this.configuration, this.labExperimentInfo.cancelExperiment);
                    resultInfo = (ResultInfo)driver.Execute(specification);
                }
                else if (specification.SetupId.Equals(Consts.STRXML_SetupId_NoLoad))
                {
                    DriverNoLoad driver = new DriverNoLoad(this.equipmentServiceProxy, this.configuration, this.labExperimentInfo.cancelExperiment);
                    resultInfo = (ResultInfo)driver.Execute(specification);
                }
                else if (specification.SetupId.Equals(Consts.STRXML_SetupId_SynchronousSpeed))
                {
                    DriverSynchronousSpeed driver = new DriverSynchronousSpeed(this.equipmentServiceProxy, this.configuration, this.labExperimentInfo.cancelExperiment);
                    resultInfo = (ResultInfo)driver.Execute(specification);
                }
                else if (specification.SetupId.Equals(Consts.STRXML_SetupId_FullLoad))
                {
                    DriverFullLoad driver = new DriverFullLoad(this.equipmentServiceProxy, this.configuration, this.labExperimentInfo.cancelExperiment);
                    resultInfo = (ResultInfo)driver.Execute(specification);
                }

                //
                // Create an instance of LabExperimentResult to convert the experiment results to an XML string
                //
                ExperimentResult experimentResult = new ExperimentResult(
                    experimentInfo.experimentId, experimentInfo.sbName, DateTime.Now,
                    this.unitId, (Configuration)this.labConfiguration, specification, resultInfo);

                //
                // Fill in the result report
                //
                experimentInfo.resultReport.experimentResults = experimentResult.ToString();
                experimentInfo.resultReport.statusCode        = (int)resultInfo.statusCode;
                experimentInfo.resultReport.errorMessage      = resultInfo.errorMessage;
            }
            catch (Exception ex)
            {
                experimentInfo.resultReport.statusCode   = (int)StatusCodes.Failed;
                experimentInfo.resultReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName);

            return(experimentInfo);
        }
        //-------------------------------------------------------------------------------------------------//

        /// <summary>
        /// Parse the XML specification string to check its validity. No exceptions are thrown back to the
        /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed
        /// in 'errorMessage' where it can be examined by the calling method.
        /// </summary>
        /// <param name="xmlSpecification"></param>
        public override ValidationReport Parse(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Parse";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Catch all exceptions and log errors, don't throw back to caller
            //
            ValidationReport validationReport = null;

            try
            {
                //
                // Call the base class to parse its part
                //
                validationReport = base.Parse(xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new Exception(validationReport.errorMessage);
                }

                // Create new validation report
                validationReport = new ValidationReport();

                //
                // Create an instance of the driver for the specified setup and then
                // get the driver's execution time for this specification
                //
                int executionTime = -1;
                if (this.SetupId.Equals(Consts.STRXML_SetupId_LockedRotor))
                {
                    DriverLockedRotor driver = new DriverLockedRotor(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_NoLoad))
                {
                    DriverNoLoad driver = new DriverNoLoad(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_SynchronousSpeed))
                {
                    DriverSynchronousSpeed driver = new DriverSynchronousSpeed(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_FullLoad))
                {
                    DriverFullLoad driver = new DriverFullLoad(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }

                //
                // Specification is valid
                //
                validationReport.estRuntime = executionTime + TIMESECS_AdministrationExecution;
                validationReport.accepted   = true;
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            string logMessage = STRLOG_Accepted + validationReport.accepted.ToString();

            if (validationReport.accepted == true)
            {
                logMessage += Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + validationReport.estRuntime.ToString() + STRLOG_seconds;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return(validationReport);
        }
        public void ShouldFindErrorMessage3()
        {
            var builder = new Fluent.FluentBuilder();

            builder.For<ClassC>().WithMessage("ClassC is not valid")
                .Setup(c => c.C)
                    .MustBeBetween(1, 10);

            builder.For<CompositeClass>()
                    .Setup(c => c.C)
                        .CallValidate();
            
            var engine = builder.Build();
            var o = new CompositeClass() { C = new ClassC() };
            var r = new ValidationReport(engine);
            r.Validate(o);
            Assert.AreEqual("ClassC is not valid", r.GetErrorMessage(o, f => f.C));
        }
Beispiel #22
0
        //-------------------------------------------------------------------------------------------------//

        public override ExecuteCommandInfo ProcessCommand(ExecuteCommandInfo executeCommandInfo)
        {
            const string STRLOG_MethodName = "ProcessCommand";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            CommandInfo commandInfo = (CommandInfo)executeCommandInfo;

            bool   success      = false;
            string errorMessage = null;

            try
            {
                //
                // Process the execute command
                //
                ExecuteCommands executeCommand = (ExecuteCommands)commandInfo.command;

                switch (executeCommand)
                {
                case ExecuteCommands.StartExecution:
                    //
                    // Get the specification in XML format from the parameters and parse
                    //
                    string           xmlSpecification = (string)commandInfo.parameters[0];
                    Specification    specification    = new Specification(this.xmlNodeEquipmentConfig);
                    ValidationReport validationReport = specification.Parse(xmlSpecification);
                    if (validationReport.accepted == false)
                    {
                        errorMessage = validationReport.errorMessage;
                        break;
                    }

                    //
                    // Create an instance of the driver for the specified setup
                    // and then start the driver with the specification
                    //
                    if (specification.SetupId.Equals(Consts.STRXML_SetupId_OpenCircuitVaryField) == true)
                    {
                        this.driverMachine = new DriverMachine_OCVF(this.xmlNodeEquipmentConfig, specification);
                    }
                    else if (specification.SetupId.Equals(Consts.STRXML_SetupId_OpenCircuitVarySpeed) == true)
                    {
                        this.driverMachine = new DriverMachine_OCVS(this.xmlNodeEquipmentConfig, specification);
                    }
                    else if (specification.SetupId.Equals(Consts.STRXML_SetupId_ShortCircuitVaryField) == true)
                    {
                        this.driverMachine = new DriverMachine_SCVF(this.xmlNodeEquipmentConfig, specification);
                    }
                    else if (specification.SetupId.Equals(Consts.STRXML_SetupId_PreSynchronisation) == true)
                    {
                        this.driverMachine = new DriverMachine_PreSync(this.xmlNodeEquipmentConfig, specification);
                    }
                    else if (specification.SetupId.Equals(Consts.STRXML_SetupId_Synchronisation) == true)
                    {
                        this.driverMachine = new DriverMachine_Sync(this.xmlNodeEquipmentConfig, specification);
                    }
                    else
                    {
                        //
                        // Unknown SetupId
                        //
                        throw new Exception(STRERR_UnknownSetupId + specification.SetupId);
                    }

                    //
                    // Start execution of the specified setup
                    //
                    if ((success = this.driverMachine.Start()) == false)
                    {
                        errorMessage = this.driverMachine.LastError;
                    }
                    break;

                default:
                    //
                    // Unknown command
                    //
                    throw new Exception(STRERR_UnknownCommand + executeCommand.ToString());
                }
            }
            catch (Exception ex)
            {
                success      = false;
                errorMessage = ex.Message;
            }

            //
            // Update success of command execution
            //
            executeCommandInfo.success = success;

            string logMessage = STRLOG_Success + success.ToString();

            if (success == false)
            {
                executeCommandInfo.errorMessage = errorMessage;
                logMessage += Logfile.STRLOG_Spacer + STRLOG_ErrorMessage + errorMessage;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return(executeCommandInfo);
        }
Beispiel #23
0
 protected void ThrowCommandValidationException(ICommand command, ValidationReport validationReport) => HandleCommandValidationFailure(command, validationReport);
Beispiel #24
0
        //-------------------------------------------------------------------------------------------------//

        /// <summary>
        /// Parse the XML specification string to check its validity. No exceptions are thrown back to the
        /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed
        /// in 'errorMessage' where it can be examined by the calling method.
        /// </summary>
        /// <param name="xmlSpecification"></param>
        public override ValidationReport Parse(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Parse";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Catch all exceptions and log errors, don't throw back to caller
            //
            ValidationReport validationReport = null;

            try
            {
                //
                // Call the base class to parse its part
                //
                validationReport = base.Parse(xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new Exception(validationReport.errorMessage);
                }

                // Create new validation report
                validationReport = new ValidationReport();

                //
                // Get the time format name and check that it is valid - search is case-sensitive
                //
                string formatName = XmlUtilities.GetXmlValue(this.xmlNodeSpecification, Consts.STRXML_formatName, false);
                int    index      = Array.IndexOf(this.configuration.TimeFormats, formatName);
                if (index < 0)
                {
                    throw new ArgumentException(STRERR_InvalidTimeFormat, formatName);
                }
                this.formatName = this.configuration.TimeFormats[index];

                //
                // Create an instance of the driver for the specified setup and then
                // get the driver's execution time for this specification
                //
                int executionTime = -1;
                if (this.setupId.Equals(Consts.STRXML_SetupId_LocalClock))
                {
                    DriverLocal driver = new DriverLocal(this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.setupId.Equals(Consts.STRXML_SetupId_NTPServer))
                {
                    // Get the server URL from the specification
                    this.serverUrl = XmlUtilities.GetXmlValue(this.xmlNodeSpecification, Consts.STRXML_serverUrl, false);

                    DriverNetwork driver = new DriverNetwork(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }

                //
                // Specification is valid
                //
                validationReport.estRuntime = executionTime;
                validationReport.accepted   = true;
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            string logMessage = STRLOG_Accepted + validationReport.accepted.ToString();

            if (validationReport.accepted == true)
            {
                logMessage += Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + validationReport.estRuntime.ToString() + STRLOG_seconds;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return(validationReport);
        }
 internal virtual void HandleCommandValidationFailure(ICommand command, ValidationReport validationReport)
 {
     throw new CommandValidationException(
         string.Format("Validation error while applying {0} to a {1}.",
                       command.CommandName,
                       GetType().Name),
         validationReport);
 }
Beispiel #26
0
 public Validator()
 {
     InitRuleEngine();
     report = new ValidationReport(rulesEngine);
 }
 internal virtual void Validate(StyleSheet styleSheet, ValidationReport report)
 {
     Report = report;
     VisitStyleSheet(styleSheet);
 }
Beispiel #28
0
 public void Validate(QuestionForm form, ValidationReport report)
 {
     Report = report;
     Visit(form);
 }
        //-------------------------------------------------------------------------------------------------//
        /// <summary>
        /// Parse the XML specification string to check its validity. No exceptions are thrown back to the
        /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed
        /// in 'errorMessage' where it can be examined by the calling method.
        /// </summary>
        /// <param name="xmlSpecification"></param>
        public override ValidationReport Parse(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Parse";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Catch all exceptions and log errors, don't throw back to caller
            //
            ValidationReport validationReport = null;
            try
            {
                //
                // Call the base class to parse its part
                //
                validationReport = base.Parse(xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new Exception(validationReport.errorMessage);
                }

                // Create new validation report
                validationReport = new ValidationReport();

                //
                // Validate the specification
                //
                //
                // Nothing to do here
                //

                //
                // Create an instance of the driver for the specified setup and then
                // get the driver's execution time for this specification
                //
                int executionTime = -1;

                //
                // All setups use the equipment driver
                //
                DriverEquipment driver = new DriverEquipment(this.equipmentServiceProxy, this.configuration);
                executionTime = driver.GetExecutionTime(this);

                //
                // Specification is valid
                //
                validationReport.estRuntime = executionTime + TIME_SECS_AdministrationExecution;
                validationReport.accepted = true;
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            string logMessage = STRLOG_Accepted + validationReport.accepted.ToString();
            if (validationReport.accepted == true)
            {
                logMessage += Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + validationReport.estRuntime.ToString() + STRLOG_seconds;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return validationReport;
        }
Beispiel #30
0
 public Task UploadReport(ValidationReport report)
 {
     return(Task.CompletedTask);
 }
        //-------------------------------------------------------------------------------------------------//
        public virtual ValidationReport Validate(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Validate";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            ValidationReport validationReport = new ValidationReport(false);

            //
            // Parse the XML specification string to generate a validation report
            //
            try
            {
                ExperimentSpecification experimentSpecification = new ExperimentSpecification(this.labConfiguration, this.equipmentServiceProxy);
                validationReport = experimentSpecification.Parse(xmlSpecification);
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName);

            return validationReport;
        }
 internal virtual void HandleCommandValidationFailure(ICommand command, ValidationReport validationReport)
 {
     throw new CommandValidationException(
         $"Validation error while applying {command.CommandName} to a {GetType().Name}.",
         validationReport);
 }
        public void TestMessagesCount()
        {
            var builder = new Fluent.FluentBuilder();
            builder.For<MyMessageTestClass>()
                .WithMessage("Object is not valid")
                .Setup(m => m.A)
                    .WithMessage("Property A is not valid.")
                    .MustBeBetween(1, 10)
                .Setup(m => m.B)
                    .WithMessage("Property B is not valid.")
                    .MustBeBetween(1, 10);

            var engine = builder.Build();
            var report = new ValidationReport(engine);
            var obj = new MyMessageTestClass(0, 0);
            engine.Validate(obj, report, ValidationReportDepth.FieldShortCircuit);
            Assert.AreEqual(2, report.GetErrorMessages(obj).Length);

            obj = new MyMessageTestClass(0, 0);
            engine.Validate(obj, report, ValidationReportDepth.FieldShortCircuit);
            Assert.AreEqual(2, report.GetErrorMessages(obj).Length);

            //There should be a total of 4 error messages...
            Assert.AreEqual(4, report.GetErrorMessages().Length);
        }
        //-------------------------------------------------------------------------------------------------//
        /// <summary>
        /// Parse the XML specification string to check its validity. No exceptions are thrown back to the
        /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed
        /// in 'errorMessage' where it can be examined by the calling method.
        /// </summary>
        /// <param name="xmlSpecification"></param>
        public override ValidationReport Parse(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Parse";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Catch all exceptions and log errors, don't throw back to caller
            //
            ValidationReport validationReport = null;
            try
            {
                //
                // Call the base class to parse its part
                //
                validationReport = base.Parse(xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new Exception(validationReport.errorMessage);
                }

                // Create new validation report
                validationReport = new ValidationReport();

                //
                // Validate the specification
                //

                //
                // Get the source name and check that it is valid - search is case-sensitive
                //
                string strSourceName = XmlUtilities.GetXmlValue(this.xmlNodeSpecification, Consts.STRXML_sourceName, false);
                int index = Array.IndexOf(this.configuration.SourceNames, strSourceName);
                if (index < 0)
                {
                    throw new ArgumentException(STRERR_InvalidSource, strSourceName);
                }
                this.sourceName = this.configuration.SourceNames[index];
                this.sourceLocation = this.configuration.SourceLocations[index];

                //
                // Get the absorber list and validate - search is case-sensitive
                //
                string csvAbsorbers = XmlUtilities.GetXmlValue(this.xmlNodeSpecification, Consts.STRXML_absorberName, false);
                string[] csvAbsorbersSplit = csvAbsorbers.Split(new char[] { Consts.CHR_CsvSplitter });
                this.absorberList = new Absorber[csvAbsorbersSplit.Length];
                for (int i = 0; i < csvAbsorbersSplit.Length; i++)
                {
                    index = Array.IndexOf(this.configuration.AbsorberNames, csvAbsorbersSplit[i]);
                    if (index < 0)
                    {
                        throw new ArgumentException(STRERR_InvalidAbsorber, csvAbsorbersSplit[i]);
                    }
                    string name = this.configuration.AbsorberNames[index];
                    char location = this.configuration.AbsorberLocations[index];
                    this.absorberList[i] = new Absorber(name, location);
                }

                //
                // Get duration and validate
                //
                this.duration = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_duration);
                this.validation.ValidateDuration(this.duration);

                //
                // Get repeat count and validate
                //
                this.repeat = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_repeat);
                this.validation.ValidateRepeat(this.repeat);

                //
                // Get distance list and validate
                //
                string csvDistances = XmlUtilities.GetXmlValue(this.xmlNodeSpecification, Consts.STRXML_distance, false);
                string[] csvDistancesSplit = csvDistances.Split(new char[] { Consts.CHR_CsvSplitter });
                this.distanceList = new int[csvDistancesSplit.Length];
                for (int i = 0; i < csvDistancesSplit.Length; i++)
                {
                    try
                    {
                        this.distanceList[i] = Int32.Parse(csvDistancesSplit[i]);
                    }
                    catch (Exception ex)
                    {
                        throw new ArgumentException(ex.Message, Consts.STRXML_distance);
                    }
                    this.validation.ValidateDistance(this.distanceList[i]);
                }

                //
                // Sort the distance list with smallest distance first keeping duplicates
                //
                Array.Sort(this.distanceList);

                //
                // Create an instance of the driver for the specified setup and then
                // get the driver's execution time for this specification
                //
                int executionTime = -1;
                if (this.SetupId.Equals(Consts.STRXML_SetupId_RadioactivityVsTime) ||
                    this.SetupId.Equals(Consts.STRXML_SetupId_RadioactivityVsDistance))
                {
                    if (this.equipmentServiceProxy != null)
                    {
                        //
                        // Hardware is available to this unit, run it there
                        //
                        DriverRadioactivity driver = new DriverRadioactivity(this.equipmentServiceProxy, this.configuration);
                        executionTime = driver.GetExecutionTime(this);
                    }
                    else
                    {
                        //
                        // This unit does not have hardware available, run the simulation instead
                        //
                        DriverSimActivity driver = new DriverSimActivity(this.configuration);
                        executionTime = driver.GetExecutionTime(this);
                    }
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_RadioactivityVsAbsorber))
                {
                    if (this.equipmentServiceProxy != null)
                    {
                        //
                        // Hardware is available to this unit, run it there
                        //
                        DriverAbsorbers driver = new DriverAbsorbers(this.equipmentServiceProxy, this.configuration);
                        executionTime = driver.GetExecutionTime(this);
                    }
                    else
                    {
                        throw new ArgumentException(STRERR_EquipmentServiceNotAvailable, this.setupId);
                    }
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_SimActivityVsTime) ||
                    this.SetupId.Equals(Consts.STRXML_SetupId_SimActivityVsDistance))
                {
                    DriverSimActivity driver = new DriverSimActivity(this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_SimActivityVsTimeNoDelay) ||
                    this.SetupId.Equals(Consts.STRXML_SetupId_SimActivityVsDistanceNoDelay))
                {
                    DriverSimActivity driver = new DriverSimActivity(this.configuration, false);
                    executionTime = driver.GetExecutionTime(this);
                }
                else
                {
                    throw new ArgumentException(STRERR_SetupIdInvalid, this.SetupId);
                }

                // Validate total execution time
                this.validation.ValidateTotalTime(executionTime);

                //
                // Specification is valid
                //
                validationReport.estRuntime = executionTime;
                validationReport.accepted = true;
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            string logMessage = STRLOG_Accepted + validationReport.accepted.ToString();
            if (validationReport.accepted == true)
            {
                logMessage += Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + validationReport.estRuntime.ToString() + STRLOG_seconds;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return validationReport;
        }
Beispiel #35
0
 protected override void Because()
 {
     _report = _sut.Validate(_settings);
 }
        public ValidationReport Validate(string experimentSpecification, string userGroup)
        {
            const string STRLOG_MethodName = "Validate";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            ValidationReport validationReport = null;

            // Get the identity of the caller
            string sbName = GetCallerName(authHeader);

            // Check caller access is authorised
            if (sbName != null)
            {
                // Pass on to experiment manager
                validationReport = Global.experimentManager.Validate(experimentSpecification, userGroup);
            }
            else
            {
                validationReport = new ValidationReport(false);
                validationReport.errorMessage = STRLOG_AccessDenied;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName);

            return (validationReport);
        }
Beispiel #37
0
        //-------------------------------------------------------------------------------------------------//

        /// <summary>
        /// Parse the XML specification string to check its validity. No exceptions are thrown back to the
        /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed
        /// in 'errorMessage' where it can be examined by the calling method.
        /// </summary>
        /// <param name="xmlSpecification"></param>
        public override ValidationReport Parse(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Parse";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Catch all exceptions and log errors, don't throw back to caller
            //
            ValidationReport validationReport = null;

            try
            {
                //
                // Call the base class to parse its part
                //
                validationReport = base.Parse(xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new Exception(validationReport.errorMessage);
                }

                // Create new validation report
                validationReport = new ValidationReport();

                //
                // Create an instance of the driver for the specified setup and then
                // get the driver's execution time for this specification
                //
                int executionTime = -1;
                if (this.SetupId.Equals(Consts.STRXML_SetupId_VoltageVsSpeed))
                {
                    //
                    // Get the speed range and validate
                    //
                    this.speed      = new MinMaxStep();
                    this.speed.min  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedMin);
                    this.speed.max  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedMax);
                    this.speed.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedStep);

                    this.validation.ValidateSpeed(this.speed);

                    DriverVoltageVsSpeed driver = new DriverVoltageVsSpeed(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_VoltageVsField))
                {
                    //
                    // Get the field range and validate
                    //
                    this.field      = new MinMaxStep();
                    this.field.min  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldMin);
                    this.field.max  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldMax);
                    this.field.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldStep);

                    this.validation.ValidateField(this.field);

                    DriverVoltageVsField driver = new DriverVoltageVsField(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_VoltageVsLoad))
                {
                    //
                    // Get the load range and validate
                    //
                    this.load      = new MinMaxStep();
                    this.load.min  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_loadMin);
                    this.load.max  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_loadMax);
                    this.load.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_loadStep);

                    this.validation.ValidateLoad(this.load);

                    DriverVoltageVsLoad driver = new DriverVoltageVsLoad(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_SpeedVsVoltage))
                {
                    //
                    // Get the speed range and validate
                    //
                    this.speed      = new MinMaxStep();
                    this.speed.min  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedMin);
                    this.speed.max  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedMax);
                    this.speed.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_speedStep);

                    this.validation.ValidateSpeed(this.speed);

                    DriverSpeedVsVoltage driver = new DriverSpeedVsVoltage(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_SpeedVsField))
                {
                    //
                    // Get the field range and validate
                    //
                    this.field      = new MinMaxStep();
                    this.field.min  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldMin);
                    this.field.max  = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldMax);
                    this.field.step = XmlUtilities.GetIntValue(this.xmlNodeSpecification, Consts.STRXML_fieldStep);

                    this.validation.ValidateField(this.field);

                    DriverSpeedVsField driver = new DriverSpeedVsField(this.equipmentServiceProxy, this.configuration);
                    executionTime = driver.GetExecutionTime(this);
                }

                //
                // Specification is valid
                //
                validationReport.estRuntime = executionTime + TIME_SECS_AdministrationExecution;
                validationReport.accepted   = true;
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            string logMessage = STRLOG_Accepted + validationReport.accepted.ToString();

            if (validationReport.accepted == true)
            {
                logMessage += Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + validationReport.estRuntime.ToString() + STRLOG_seconds;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return(validationReport);
        }
 protected void ThrowCommandValidationException(ICommand command, ValidationReport validationReport)
 {
     HandleCommandValidationFailure(command, validationReport);
 }
 public void SetUp()
 {
     this.validator = new TestValidator();
     this.report    = this.validator.Validate(new TestClass()).Result;
 }
 public void ShouldValidate()
 {
     var builder = new Fluent.FluentBuilder();
     builder.For<ClassA>().Setup(a => a.A).MustBeGreaterThan(0);
     var engine = builder.Build();
     var report = new ValidationReport(engine);
     Assert.IsFalse(report.Validate(new ClassA()));
 }
        public void TestMessageInheritedClass3()
        {
            var builder = new Fluent.FluentBuilder();
            builder.For<ClassA>()
                .Setup(m => m.A)
                    .MustBeLessThanOrEqualTo(1)
                    .WithMessage("ClassA validation for A");

            builder.For<ClassB>()
                .Setup(m => m.A)
                    .WithMessage("ClassB validation for A");

            builder.For<ClassC>()
                .Setup(m => m.A)
                    .WithMessage("ClassC validation for A.1")
                    .MustBeLessThan(-1)
                    .WithMessage("ClassC validation for A.2");

            var engine = builder.Build();
            var report = new ValidationReport(engine);
            var obj = new ClassC(2, 0, 0);
            report.Validate(obj);
            //m=>m.A will hit A.1 because the rules for base types are executed first. m=>m.A will fail because of rule defined on ClassA!.
            Assert.AreEqual("ClassC validation for A.1", report.GetErrorMessage(obj, o => o.A));

            obj = new ClassC(1, 0, 0);
            report.Validate(obj);
            //m=>m.A will hit A.2 because the rules for base types are fine. m=>m.A will fail because of rule defined on ClassC!.
            Assert.AreEqual("ClassC validation for A.2", report.GetErrorMessage(obj, o => o.A));
        }
        //-------------------------------------------------------------------------------------------------//
        /// <summary>
        /// Parse the XML specification string to check its validity. No exceptions are thrown back to the
        /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed
        /// in 'errorMessage' where it can be examined by the calling method. Return 'accepted'.
        /// </summary>
        /// <param name="xmlSpecification"></param>
        public virtual ValidationReport Parse(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Parse";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Create a new validation report ready to fill in
            //
            ValidationReport validationReport = new ValidationReport();

            //
            // Process the XML specification string
            //
            try
            {
                // Load XML specification string
                XmlDocument xmlDocument = XmlUtilities.GetXmlDocument(xmlSpecification);

                //
                // Get a copy of the specification XML node
                //
                XmlNode xmlNode = XmlUtilities.GetXmlRootNode(xmlDocument, Consts.STRXML_experimentSpecification);
                this.xmlNodeSpecification = xmlNode.Clone();

                //
                // Get the setup id and check that it exists - search is case-sensitive
                //
                this.setupId = XmlUtilities.GetXmlValue(this.xmlNodeSpecification, Consts.STRXML_setupId, false);
                int setupIndex = Array.IndexOf(this.labConfiguration.SetupIds, this.setupId);
                if (setupIndex < 0)
                {
                    throw new ArgumentException(STRERR_SetupIdInvalid, this.setupId);
                }

                //
                // Get the specified setup XML node
                //
                XmlNodeList xmlNodeList = XmlUtilities.GetXmlNodeList(this.xmlNodeConfiguration, Consts.STRXML_setup, true);
                this.xmlNodeSetup = xmlNodeList.Item(setupIndex);

                //
                // Create an instance of the driver for the specified setup and then
                // get the driver's execution time for this specification
                //
                int executionTime = -1;
                if (this.SetupId.Equals(Consts.STRXML_SetupId_EquipmentGeneric))
                {
                    if (this.equipmentServiceProxy == null)
                    {
                        throw new ArgumentException(STRERR_EquipmentServiceNotAvailable, this.setupId);
                    }

                    DriverEquipmentGeneric driver = new DriverEquipmentGeneric(this.equipmentServiceProxy, this.labConfiguration);
                    executionTime = driver.GetExecutionTime(this);
                }
                else if (this.SetupId.Equals(Consts.STRXML_SetupId_ModuleGeneric))
                {
                    DriverModuleGeneric driver = new DriverModuleGeneric(this.labConfiguration);
                    executionTime = driver.GetExecutionTime(this);
                }

                //
                // Specification is valid
                //
                validationReport.estRuntime = executionTime;
                validationReport.accepted = true;
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName);

            return validationReport;
        }
        public void TestMessageInheritedClass4()
        {
            //NOTE: This test is the same as No.3, with definition of rules order changed.
            var builder = new Fluent.FluentBuilder();

            builder.For<ClassA>()
                .Setup(m => m.A)
                    .MustBeLessThanOrEqualTo(1)
                    .WithMessage("ClassA validation for A");

            builder.For<ClassB>()
                .Setup(m => m.A)
                    .WithMessage("ClassB validation for A");

            builder.For<ClassC>()
                .Setup(m => m.A)
                    .WithMessage("ClassC validation for A.1")
                    .MustBeLessThan(-1)
                    .WithMessage("ClassC validation for A.2");


            var engine = builder.Build();
            var report = new ValidationReport(engine);
            var obj = new ClassC(2, 0, 0);
            report.Validate(obj);
            //m=>m.A will hit A.1 because the rules for base types are executed first. m=>m.A will fail because of rule defined on ClassA!.
            Assert.AreEqual("ClassC validation for A.1", report.GetErrorMessage(obj, o => o.A));

            report = new ValidationReport(engine);
            obj = new ClassC(1, 0, 0);
            engine.Validate(obj, report, ValidationReportDepth.FieldShortCircuit);
            //m=>m.A will hit A.2 because the rules for base types are fine. m=>m.A will fail because of rule defined on ClassC!.
            Assert.AreEqual("ClassC validation for A.2", report.GetErrorMessage(obj, o => o.A));

        }
        public void TestMessageInheritedClass6()
        {
            var builder = new Fluent.FluentBuilder();

            builder.For<ClassA>()
                .Setup(m => m.A)
                    .MustBeLessThanOrEqualTo(1)
                    .WithMessage("ClassA validation for A");

            builder.For<ClassB>()
                .Setup(m => m.A)
                    .WithMessage("ClassB validation for A");

            var engine = builder.Build();
            var report = new ValidationReport(engine);
            var obj = new ClassB(2, 0);
            report.Validate(obj);
            Assert.AreEqual("ClassB validation for A", report.GetErrorMessage(obj, o => o.A));
            Assert.AreEqual("ClassB validation for A", report.GetErrorMessage((ClassA)obj, o => o.A));
        }
        public void TestMessageInheritedClass2()
        {
            //NOTE: Same as TestMessageInheritedClass, with order of registrations changed.

            var builder = new Fluent.FluentBuilder();

            builder.For<ClassC>()
                .Setup(m => m.A)
                    .WithMessage("ClassC validation for A");

            builder.For<ClassB>()
                .Setup(m => m.A)
                    .WithMessage("ClassB validation for A");

            builder.For<ClassA>()
                .Setup(m => m.A)
                    .MustBeLessThanOrEqualTo(1)
                    .WithMessage("ClassA validation for A");

            var engine = builder.Build();
            var report = new ValidationReport(engine);
            var obj = new ClassC(2, 0, 0);
            report.Validate(obj);
            Assert.AreEqual("ClassC validation for A", report.GetErrorMessage(obj, o => o.A));
        }
        //-------------------------------------------------------------------------------------------------//
        private ValidationReport ConvertType(Proxy.ValidationReport proxyValidationReport)
        {
            ValidationReport validationReport = null;

            if (proxyValidationReport != null)
            {
                validationReport = new ValidationReport();
                validationReport.Accepted = proxyValidationReport.accepted;
                validationReport.ErrorMessage = proxyValidationReport.errorMessage;
                validationReport.EstimatedRuntime = proxyValidationReport.estRuntime;
                validationReport.WarningMessages = proxyValidationReport.warningMessages;
            }

            return validationReport;
        }
        //-------------------------------------------------------------------------------------------------//

        /// <summary>
        /// Parse the XML specification string to check its validity. No exceptions are thrown back to the
        /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed
        /// in 'errorMessage' where it can be examined by the calling method. Return 'accepted'.
        /// </summary>
        /// <param name="xmlSpecification"></param>
        public override ValidationReport Parse(string xmlSpecification)
        {
            const string STRLOG_MethodName = "Parse";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Catch all exceptions and log errors, don't throw back to caller
            //
            ValidationReport validationReport = null;

            try
            {
                //
                // Call the base class to parse its part
                //
                validationReport = base.Parse(xmlSpecification);
                if (validationReport.accepted == false)
                {
                    throw new Exception(validationReport.errorMessage);
                }

                //
                // Create an instance of the driver for the specified setup and then
                // get the driver's execution time for this specification
                //
                if (this.setupId.Equals(Consts.STRXML_SetupId_OpenCircuitVaryField))
                {
                    DriverMachine_OCVF driver = new DriverMachine_OCVF(this.xmlNodeEquipmentConfig, this);
                    validationReport.estRuntime = driver.GetExecutionTime();
                }
                else if (this.setupId.Equals(Consts.STRXML_SetupId_OpenCircuitVarySpeed))
                {
                    DriverMachine_OCVS driver = new DriverMachine_OCVS(this.xmlNodeEquipmentConfig, this);
                    validationReport.estRuntime = driver.GetExecutionTime();
                }
                else if (this.setupId.Equals(Consts.STRXML_SetupId_ShortCircuitVaryField))
                {
                    DriverMachine_SCVF driver = new DriverMachine_SCVF(this.xmlNodeEquipmentConfig, this);
                    validationReport.estRuntime = driver.GetExecutionTime();
                }
                else if (this.setupId.Equals(Consts.STRXML_SetupId_PreSynchronisation))
                {
                    DriverMachine_PreSync driver = new DriverMachine_PreSync(this.xmlNodeEquipmentConfig, this);
                    validationReport.estRuntime = driver.GetExecutionTime();
                }
                else if (this.setupId.Equals(Consts.STRXML_SetupId_Synchronisation))
                {
                    DriverMachine_Sync driver = new DriverMachine_Sync(this.xmlNodeEquipmentConfig, this);
                    validationReport.estRuntime = driver.GetExecutionTime();
                }
                else
                {
                    validationReport.accepted = false;
                    throw new Exception(STRERR_UnknownSetupId + this.setupId);
                }
            }
            catch (Exception ex)
            {
                validationReport.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            string logMessage = STRLOG_Accepted + validationReport.accepted.ToString();

            if (validationReport.accepted == true)
            {
                logMessage += Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + validationReport.estRuntime.ToString() + STRLOG_seconds;
            }

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return(validationReport);
        }