public void IsValidCommand_WhenCommandIsInvalidShouldReturnFalse()
        {
            var commandValidator = new CommandValidator<CommandType>();
            var command = "go";

            Assert.IsFalse(commandValidator.IsValidCommand(command));
        }
        public void IsValidCommand_WhenCommandIsValidShouldReturnTrue()
        {
            var commandValidator = new CommandValidator<CommandType>();
            var command = "start";

            Assert.IsTrue(commandValidator.IsValidCommand(command));
        }
        /// <summary>
        ///  Executes the context command .
        /// </summary>
        /// <param name="context">It is used for different kinds of commands to communicate with the game engine.</param>
        public void Execute(IContext context)
        {
            var factory = new GameFactory();
            var validator = new CommandValidator<GameDifficulty>();

            context.Printer.PrintMessage(GlobalMessages.StartCommandMsg);
            var input = context.Reader.ReadInput();

            if (validator.IsValidCommand(input))
            {
                context.GameLogic.Game = factory.CreateGame(validator.GetType(input));
            }
            else
            {
                context.Printer.PrintMessage(GlobalMessages.StartCommandInvalidDifficultyMsg);
            }

            context.Printer.PrintGameBoard(context.GameLogic.Game.Field);
        }
Exemplo n.º 4
0
        internal ValidationReport RunAllValidations(TTarget target, bool throwOnValidationFailure = false)
        {
            AuthorizeOrThrow(target);

            if (AppliesToVersion != null)
            {
                var eventSourced = target as IEventSourced;

                if (eventSourced != null && AppliesToVersion != eventSourced.Version)
                {
                    throw new ConcurrencyException(
                              $"The command's AppliesToVersion value ({AppliesToVersion}) does not match the aggregate's version ({eventSourced.Version})");
                }
            }

            // first validate the command's validity in and of itself
            ValidationReport validationReport;

            try
            {
                validationReport = ExecutePreparedCommandValidator();
            }
            catch (RuntimeBinderException ex)
            {
                throw new InvalidOperationException(
                          $"Property CommandValidator returned a validator of the wrong type. It should return a {typeof (IValidationRule<>).MakeGenericType(GetType())}, but returned a {CommandValidator.GetType()}", ex);
            }

            if (validationReport.HasFailures)
            {
                if (throwOnValidationFailure)
                {
                    throw new CommandValidationException($"{CommandName} is invalid.", validationReport);
                }

                return(validationReport);
            }

            return(ExecuteValidator(target));
        }
Exemplo n.º 5
0
 public CommandHandler(CommandValidator commandValidator, IUnitOfWork unitOfWork, IPrivateCertRepository privateCertRepository)
 {
     this.commandValidator      = commandValidator;
     this.unitOfWork            = unitOfWork;
     this.privateCertRepository = privateCertRepository;
 }
Exemplo n.º 6
0
 private bool IsMetadataAddValid(MetadataCreateCommand command)
 {
     return(CommandValidator.Validate(command).Success &&
            command.ReleaseId == PersistenceId &&
            TrackIds.Contains(command.TrackId));
 }
 public void GetType_ShouldNotThrowWhenInputIsInCorrectFormat()
 {
     var commandValidator = new CommandValidator<CommandType>();
     var input = "start";
     commandValidator.GetType(input);  
 }
 public AttackShipCommandValidationTests()
 {
     _validator = new CommandValidator(_context);
 }
Exemplo n.º 9
0
        public void ValidateShouldThrowInputExceptionBecauseOfTooManyArguments()
        {
            var ex = Assert.Throws <InputException>(() => CommandValidator.Validate(_classData, _cmdInputDataTooManyArguments), "Because of too many arguments.");

            ex.Message.ShouldBeEquivalentTo(Constants.ErrorMessages.TooManyParams);
        }
Exemplo n.º 10
0
 public void ValidateShouldThrowInputExceptionBecauseOfArgumentValueMissing()
 {
     Assert.Throws <InputException>(() => CommandValidator.Validate(_classData, _cmdInputDataArgumentValueMissing), "Because of argument value is missing.");
 }
Exemplo n.º 11
0
        public void ValidateShouldThrowInputExceptionBecauseOfInvalidMethodName()
        {
            var ex = Assert.Throws <InputException>(() => CommandValidator.Validate(_classData, _cmdInputDataInvalidMethodName), "Because of invalid method name.");

            ex.Message.ShouldBeEquivalentTo(string.Format(Constants.ErrorMessages.UnrecognizedCommand, _cmdInputDataInvalidMethodName.MethodName));
        }
Exemplo n.º 12
0
 public void ValidateShouldThrowInputExceptionBecauseOfInvalidArgument()
 {
     Assert.Throws <InputException>(() => CommandValidator.Validate(_classData, _cmdInputDataInvalidArgument), "Because of invalid argument.");
 }
Exemplo n.º 13
0
        public async Task <OneOf <ModelWithErrors <ViewModel>, Success> > Handle(Command request, CancellationToken cancellationToken)
        {
            NormalizeCommand();
            var allRegions = await _regionCache.GetAllRegions();

            var validator        = new CommandValidator(_clock, allRegions);
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.IsValid)
            {
                _flow.Update(s => s.SetCourseRun(request.CourseName,
                                                 request.ProviderCourseRef,
                                                 request.StartDate,
                                                 request.FlexibleStartDate,
                                                 request.NationalDelivery,
                                                 request.SubRegionIds,
                                                 request.CourseWebPage,
                                                 request.Cost,
                                                 request.CostDescription,
                                                 request.Duration,
                                                 request.DurationUnit,
                                                 request.StudyMode,
                                                 request.AttendancePattern,
                                                 request.VenueId));
                return(new Success());
            }
            else
            {
                var vm = await CreateViewModel(request.DeliveryMode, request);

                request.Adapt(vm);
                return(new ModelWithErrors <ViewModel>(vm, validationResult));
            }


            void NormalizeCommand()
            {
                // Some fields only apply under certain conditions; ensure we don't save fields that are not applicable

                if (request.DeliveryMode != CourseDeliveryMode.ClassroomBased)
                {
                    request.VenueId           = null;
                    request.StudyMode         = null;
                    request.AttendancePattern = null;
                }

                if (request.DeliveryMode != CourseDeliveryMode.WorkBased)
                {
                    request.NationalDelivery = null;
                    request.SubRegionIds     = null;
                }

                if (request.FlexibleStartDate == true)
                {
                    request.StartDate = null;
                }

                if (request.NationalDelivery == true)
                {
                    request.SubRegionIds = null;
                }
            }
        }
 public void FailsValidationForInvalidCharCommand()
 {
     Assert.Throws <ArgumentException>(() => CommandValidator.Validate(new[] { 'q' }));
 }
Exemplo n.º 15
0
 public CreateShipCommandValidationTests()
 {
     _validator = new CommandValidator(_context);
 }
Exemplo n.º 16
0
        /// <summary>
        /// Send Commands to simulator, to make its state consistent with RTDB
        /// </summary>
        public void InitializeSimulator()
        {
            // ovo probati sa taskovima, za svaki od rtu-ova. ipak ne, jer nekim promenljivim komandujes, nekim ne
            // var rtus = dbContext.GettAllRTUs();

            //Parallel.ForEach(rtus, (currentRtu, state) =>
            //{
            //    Console.WriteLine("InitSim Parallel.foreach RTU name = {0}, Therad id = {1} started", currentRtu.Key, Thread.CurrentThread.ManagedThreadId);
            //    IIndustryProtocolHandler IProtHandler = null;
            //    RTU rtu = dbContext.GetRTUByName(currentRtu.Key);
            //    if (currentRtu.Value != null)
            //    {
            //        IORequestBlock iorb = new IORequestBlock()
            //        {
            //            RequestType = RequestType.SEND,
            //            ProcessControllerName = currentRtu.Key
            //        };

            //        switch (rtu.Protocol)
            //        {
            //            case IndustryProtocols.ModbusTCP:
            //                IProtHandler = new ModbusHandler()
            //                {
            //                    Header = new ModbusApplicationHeader
            //                    {
            //                        TransactionId = 0,
            //                        ProtocolId = (ushort)IndustryProtocols.ModbusTCP,
            //                        DeviceAddress = rtu.Address,
            //                        Length = 5
            //                    },
            //                    Request = new WriteRequest()
            //                };
            //                break;
            //        }

            //        //to do. praviti nove iorbove
            //        // za svaku varijablu trebas imati should command ili ne i u zavisnosti od toga puniti data, racunati length  zahtvea i ostalo
            //        //-------------analogs---------------
            //        var analogs = dbContext.GetProcessVariable().Where(pv => pv.Type == VariableTypes.ANALOG && pv.IsInit == false &&
            //                                                            pv.ProcContrName.Equals(currentRtu.Key)).OrderBy(pv => pv.RelativeAddress);
            //        int requestCount = analogs.ToList().Count();
            //        if (requestCount != 0)
            //        {
            //            ProcessVariable firstPV = analogs.FirstOrDefault();
            //            iorb.ReqAddress = (ushort)rtu.GetAcqAddress(firstPV);

            //            if (IProtHandler != null)
            //            {
            //                switch (rtu.Protocol)
            //                {
            //                    case IndustryProtocols.ModbusTCP:


            //                        for(int i = 0; i < requestCount; i++)
            //                        {

            //                        }
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).FunCode = FunctionCodes.ReadInputRegisters;
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).Quantity = (ushort)requestCount;
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).StartAddr = iorb.ReqAddress;
            //                        break;
            //                }

            //                iorb.Flags = requestCount;
            //                iorb.SendBuff = IProtHandler.PackData();
            //                iorb.SendMsgLength = iorb.SendBuff.Length;
            //                IORequests.EnqueueRequest(iorb);
            //            }
            //        }

            //        //-------------digitals---------------(to do: add init flag...)
            //        var digitals = dbContext.GetProcessVariable().Where(pv => pv.Type == VariableTypes.DIGITAL &&
            //                                                            pv.ProcContrName.Equals(currentRtu.Key)).OrderBy(pv => pv.RelativeAddress);
            //        requestCount = digitals.ToList().Count();
            //        if (requestCount != 0)
            //        {
            //            ProcessVariable firstPV = digitals.FirstOrDefault();
            //            iorb.ReqAddress = (ushort)rtu.GetAcqAddress(firstPV);

            //            if (IProtHandler != null)
            //            {
            //                switch (rtu.Protocol)
            //                {
            //                    case IndustryProtocols.ModbusTCP:

            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).FunCode = FunctionCodes.ReadDiscreteInput;
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).Quantity = (ushort)requestCount;
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).StartAddr = iorb.ReqAddress;
            //                        break;
            //                }

            //                iorb.Flags = requestCount;
            //                iorb.SendBuff = IProtHandler.PackData();
            //                iorb.SendMsgLength = iorb.SendBuff.Length;
            //                IORequests.EnqueueRequest(iorb);
            //            }
            //        }
            //    }
            //});

            List <ProcessVariable> pvs = dbContext.GetProcessVariable().ToList();

            if (pvs.Count != 0)
            {
                foreach (ProcessVariable pv in pvs)
                {
                    IORequestBlock iorb = new IORequestBlock()
                    {
                        RequestType           = RequestType.SEND,
                        ProcessControllerName = pv.ProcContrName
                    };

                    RTU rtu;
                    if ((rtu = dbContext.GetRTUByName(pv.ProcContrName)) != null)
                    {
                        iorb.ReqAddress = (ushort)rtu.GetCommandAddress(pv);
                        bool shouldCommand = false;

                        switch (rtu.Protocol)
                        {
                        case IndustryProtocols.ModbusTCP:

                            ModbusHandler mdbHandler = new ModbusHandler();
                            mdbHandler.Header = new ModbusApplicationHeader()
                            {
                                TransactionId = 0,
                                Length        = 5,
                                ProtocolId    = (ushort)IndustryProtocols.ModbusTCP,
                                DeviceAddress = rtu.Address
                            };

                            mdbHandler.Request = new WriteRequest()
                            {
                                StartAddr = (ushort)rtu.GetCommandAddress(pv)
                            };

                            switch (pv.Type)
                            {
                            // initialy, on simulator all digitals are set to 0 -> closed state
                            case VariableTypes.DIGITAL:
                                Digital digital = (Digital)pv;

                                CommandTypes comm;
                                if (shouldCommand = CommandValidator.InitialCommandingForDigital(digital, out comm))
                                {
                                    mdbHandler.Request.FunCode = FunctionCodes.WriteSingleCoil;
                                    ((WriteRequest)mdbHandler.Request).Value = (ushort)comm;
                                }
                                break;

                            case VariableTypes.ANALOG:
                                Analog analog = (Analog)pv;

                                if (shouldCommand = AnalogProcessor.InitialWorkPointAnalog(analog))
                                {
                                    mdbHandler.Request.FunCode = FunctionCodes.WriteSingleRegister;
                                    ((WriteRequest)mdbHandler.Request).Value = (ushort)analog.RawCommValue;
                                }
                                analog.IsInit = true;
                                break;

                            case VariableTypes.COUNTER:
                                Counter counter = (Counter)pv;

                                break;
                            }

                            if (shouldCommand)
                            {
                                iorb.SendBuff      = mdbHandler.PackData();
                                iorb.SendMsgLength = iorb.SendBuff.Length;
                                //if (pv.Name == "MEAS_AN_1")
                                //    Console.WriteLine(BitConverter.ToString(iorb.SendBuff, 0, 12));
                            }

                            break;
                        }

                        if (shouldCommand)
                        {
                            IORequests.EnqueueRequest(iorb);
                        }
                    }
                    else
                    {
                        // izbrisati omdah te procesne varijable sa rtu-om tog imena?
                        Console.WriteLine("Invalid config: ProcContrName = {0} does not exists.", pv.ProcContrName);
                        continue;
                    }
                }
            }
        }
Exemplo n.º 17
0
 public void ValidateShouldBeValid()
 {
     CommandValidator.Validate(_classData, _cmdInputDataValid);
 }
 public void CommandValidator_WhenTypeOfCommandIsInICorrectFormatShouldNotThrow()
 {
     var commandValidator = new CommandValidator<CommandType>();
 }
Exemplo n.º 19
0
 public void ValidateShouldThrowInputExceptionBecauseOfRequiredArgumentMissing()
 {
     Assert.Throws <InputException>(() => CommandValidator.Validate(_classData, _cmdInputDataRequiredArgumentMissing), "Because of required argument missing.");
 }
Exemplo n.º 20
0
 public CreatePlayerCommandValidatorTests()
 {
     _validator = new CommandValidator();
 }
 public CreateBoardCommandValidationTests()
 {
     _validator = new CommandValidator();
 }
 public void when_Validate_Command_is_called()
 {
     _validator = new CommandValidator<SomeTestCommand>(ObjectFactory.Container);
     _isValid = _validator.IsValid(_command);
 }
Exemplo n.º 23
0
 public EditTest()
 {
     _validator = new CommandValidator();
 }
 public void SetUp()
 {
     _commandValidator = new CommandValidator();
 }
Exemplo n.º 25
0
        public void AddMetadata(MetadataCreateCommand createMetadata)
        {
            WithValidation(() => CommandValidator.Validate(createMetadata));

            ActorModel.TellReleaseActor(createMetadata.ReleaseId, createMetadata);
        }
Exemplo n.º 26
0
 public CreateTest()
 {
     _validator = new CommandValidator();
 }
Exemplo n.º 27
0
 public void UpdateMetadata(MetadataUpdateCommand updateMetadata)
 {
     WithValidation(() => CommandValidator.Validate(updateMetadata));
     ActorModel.TellReleaseActor(updateMetadata.ReleaseId, updateMetadata);
 }
Exemplo n.º 28
0
        public void TestIfCommandValidatorReturnsFalseWhitInvalidCommand()
        {
            bool result = CommandValidator <CommandType> .IsValidCommand("Invalid");

            Assert.IsFalse(result, "Incorrect true return of IsValidComandDir");
        }
Exemplo n.º 29
0
 public void UpdateRelease(ReleaseUpdateCommand updateRelease)
 {
     WithValidation(() => CommandValidator.Validate(updateRelease));
     ActorModel.TellReleaseActor(updateRelease.ReleaseId, updateRelease);
 }
Exemplo n.º 30
0
    public static CommandValueLookup GetParameterValues(CommandTree?tree, ITypeResolver resolver)
    {
        var lookup = new CommandValueLookup();
        var binder = new CommandValueBinder(lookup);

        CommandValidator.ValidateRequiredParameters(tree);

        while (tree != null)
        {
            // Process unmapped parameters.
            foreach (var parameter in tree.Unmapped)
            {
                // Got a value provider?
                if (parameter.ValueProvider != null)
                {
                    var context = new CommandParameterContext(parameter, resolver, null);
                    if (parameter.ValueProvider.TryGetValue(context, out var result))
                    {
                        result = ConvertValue(resolver, lookup, binder, parameter, result);

                        lookup.SetValue(parameter, result);
                        CommandValidator.ValidateParameter(parameter, lookup, resolver);
                        continue;
                    }
                }

                if (parameter.IsFlagValue())
                {
                    // Set the flag value to an empty, not set instance.
                    var instance = Activator.CreateInstance(parameter.ParameterType);
                    lookup.SetValue(parameter, instance);
                }
                else
                {
                    // Is this an option with a default value?
                    if (parameter.DefaultValue != null)
                    {
                        var value = parameter.DefaultValue?.Value;
                        value = ConvertValue(resolver, lookup, binder, parameter, value);

                        binder.Bind(parameter, resolver, value);
                        CommandValidator.ValidateParameter(parameter, lookup, resolver);
                    }
                    else if (Nullable.GetUnderlyingType(parameter.ParameterType) != null ||
                             !parameter.ParameterType.IsValueType)
                    {
                        lookup.SetValue(parameter, null);
                    }
                }
            }

            // Process mapped parameters.
            foreach (var mapped in tree.Mapped)
            {
                if (mapped.Parameter.WantRawValue)
                {
                    // Just try to assign the raw value.
                    binder.Bind(mapped.Parameter, resolver, mapped.Value);
                }
                else
                {
                    if (mapped.Parameter.IsFlagValue() && mapped.Value == null)
                    {
                        if (mapped.Parameter is CommandOption option && option.DefaultValue != null)
                        {
                            // Set the default value.
                            binder.Bind(mapped.Parameter, resolver, option.DefaultValue?.Value);
                        }
                        else
                        {
                            // Set the flag but not the value.
                            binder.Bind(mapped.Parameter, resolver, null);
                        }
                    }
Exemplo n.º 31
0
 public void UpdateTrack(TrackUpdateCommand trackUpdate)
 {
     WithValidation(() => CommandValidator.Validate(trackUpdate));
     ActorModel.TellTrackActor(trackUpdate.TrackId, trackUpdate);
 }
Exemplo n.º 32
0
 public EditTest()
 {
     _validator = new CommandValidator();
     context    = GetDbContext();;
 }
 public void CommandValidator_WhenTypeOfCommandIsInIncorrectFormatShouldThrow()
 {
     var commandValidator = new CommandValidator<char>();
 }
Exemplo n.º 34
0
        public OMSSCADACommon.Responses.Response WriteSingleDigital(string id, CommandTypes command)
        {
            Console.WriteLine("WriteSingleDigital!");

            Digital digital = null;

            OMSSCADACommon.Responses.Response response = new OMSSCADACommon.Responses.Response();

            // sporno
            //while (!Database.IsConfigurationRunning)

            // getting PV from db
            ProcessVariable pv;

            if (dbContext.GetProcessVariableByName(id, out pv))
            {
                digital = (Digital)pv;
            }

            // does this ID exist in the database
            if (digital == null)
            {
                response.ResultMessage = ResultMessage.INVALID_ID;
                return(response);
            }

            // is this a valid command for this digital device
            if (!CommandValidator.ValidateDigitalCommand(digital, command))
            {
                response.ResultMessage = ResultMessage.INVALID_DIG_COMM;
                return(response);
            }


            RTU rtu;

            if ((rtu = dbContext.GetRTUByName(digital.ProcContrName)) != null)
            {
                IORequestBlock iorb = new IORequestBlock()
                {
                    RequestType           = RequestType.SEND,
                    ProcessControllerName = digital.ProcContrName
                };

                iorb.ReqAddress = (ushort)rtu.GetCommandAddress(digital);

                switch (rtu.Protocol)
                {
                case IndustryProtocols.ModbusTCP:

                    ModbusHandler mdbHandler = new ModbusHandler
                    {
                        Header = new ModbusApplicationHeader()
                        {
                            TransactionId = 0,
                            Length        = 5,
                            ProtocolId    = (ushort)IndustryProtocols.ModbusTCP,
                            DeviceAddress = rtu.Address
                        },

                        Request = new WriteRequest()
                        {
                            FunCode   = FunctionCodes.WriteSingleCoil,
                            StartAddr = (ushort)rtu.GetCommandAddress(digital),
                            Value     = (ushort)command
                        }
                    };

                    iorb.SendBuff      = mdbHandler.PackData();
                    iorb.SendMsgLength = iorb.SendBuff.Length;
                    break;
                }

                IORequests.EnqueueRequest(iorb);
                Console.WriteLine("enqued {0}", BitConverter.ToString(iorb.SendBuff, 0, 12));

                digital.Command = command;

                response.ResultMessage = ResultMessage.OK;
            }
            else
            {
                // rtu does not exist
            }

            return(response);
        }
 public void when_Validate_Command_is_called()
 {
     _validator = new CommandValidator <SomeTestCommand>(ObjectFactory.Container);
     _isValid   = _validator.IsValid(_command);
 }