Beispiel #1
0
 public Command(string command, CommandExecutor executor, string description, Permission permission)
 {
     this.command = command.ToLower();
     this.executor = executor;
     this.description = description;
     this.permission = permission;
 }
Beispiel #2
0
 public Command(string command, CommandExecutor executor)
 {
     this.command = command.ToLower();
     this.executor = executor;
     this.description = null;
     this.permission = null;
 }
        public void RedoUndo()
        {
            var command = new FakeCommand();
            var executor = new CommandExecutor();
            executor.Redo();

            executor.Execute<FakeCommand>((configuration) =>
            {
                configuration.OnSuccess((s) => { });
                configuration.OnProgress((p) => { });
                configuration.OnFailure((f) => { });
                configuration.ConstructUsing(() => command);
            });

            Assert.True(executor.CanUndo);
            Assert.False(executor.CanRedo);

            executor.Undo();

            Assert.False(executor.CanUndo);
            Assert.True(executor.CanRedo);

            executor.Redo();

            Assert.True(executor.CanUndo);
            Assert.False(executor.CanRedo);
        }
        public void Setup()
        {
            _commandBus = MockRepository.GenerateMock<ICommandBus>();
            _messageManager = MockRepository.GenerateMock<IMessageManager>();

            _commandExecutor = new CommandExecutor( _commandBus, _messageManager );
        }
Beispiel #5
0
 public MySqlProvider()
     : base(PROVIDER_NAME)
 {
     m_mapper = new Mapper(this);
     m_builder = new CommandBuilder(this);
     m_commandExecutor = new CommandExecutor();
 }
        public GetAllUsersUICommand(MainWindowViewModel mainWindowViewModel, CommandExecutor commandExecutor, QueryExecutor queryExecutor, RequestExecutor requestExecutor)
            : base(commandExecutor, queryExecutor, requestExecutor)
        {
            Argument.IsNotNull(mainWindowViewModel, "mainWindowViewModel");

            _mainWindowViewModel = mainWindowViewModel;
        }
        internal static void Main(string[] args)
        {
            IPerformanceDatabase performanceDatabase = new PerformanceDatabase();
            ICommandExecutor commandExecutor = new CommandExecutor(performanceDatabase);
            IEngine engine = new TheatreEngine(commandExecutor);

            engine.Run();
        }
 public Command(CommandExecutor executor, string name)
 {
     if (executor == null) throw new ArgumentNullException("executor");
     if (name == null) throw new ArgumentNullException("name");
     this.executor = executor;
     Name = name;
     logDeExecucao = new LogEvent { Message = name };
 }
        public void Execute_NoHandlerDefined_ThrowsException()
        {
            var commandDispatcher = new CommandExecutor(t => { throw new Exception(); }, _validationProcessor);
              var expectedMessage = string.Format("Can not resolve handler for ICommandHandler<{0}>", typeof(ICommand).Name);
              A.CallTo(() => _validationProcessor.Validate(_command)).Returns(new ValidationStatus());

              Assert.That(() => commandDispatcher.Execute(_command), Throws.InstanceOf<ResolverException>().And.Message.EqualTo(expectedMessage));
        }
        public void Execute_InvoiceModelIsValid_ValidationStateIsValid()
        {
            var commandDispatcher = new CommandExecutor(t => _handler, _validationProcessor);
              A.CallTo(() => _validationProcessor.Validate(_command)).Returns(new ValidationStatus());

              var result = commandDispatcher.Execute(_command);

              Assert.IsTrue(result.IsValid);
        }
        public void Execute_InvoiceModelIsInvalid_HandlerHandleMustNotHaveHappened()
        {
            var commandDispatcher = new CommandExecutor(t => _handler, _validationProcessor);
              A.CallTo(() => _validationProcessor.Validate(_command)).Returns(new ValidationStatus(new List<ValidationError> { new ValidationError("error") }));

              commandDispatcher.Execute(_command);

              A.CallTo(() => _handler.Handle(A<ICommand>._)).MustNotHaveHappened();
        }
Beispiel #12
0
        public static void Main()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            var userInterface = new ConsoleInterface();
            var commandExecutor = new CommandExecutor(userInterface);
            var data = new BattleshipsData();
            var engine = new BattleshipsEngine(commandExecutor, userInterface, data);
            engine.Run();
        }
Beispiel #13
0
        protected BaseUICommand(CommandExecutor commandExecutor, QueryExecutor queryExecutor, RequestExecutor requestExecutor)
        {
            Argument.IsNotNull(commandExecutor, "commandExecutor");
            Argument.IsNotNull(queryExecutor, "queryExecutor");
            Argument.IsNotNull(requestExecutor, "requestExecutor");

            CommandExecutor = commandExecutor;
            QueryExecutor = queryExecutor;
            RequestExecutor = requestExecutor;
        }
 public Bootstrap(IseIntegrator iseIntegrator, IseFileReloader iseFileReloader, CommandExecutor commandExecutor,
     WorkspaceDirectoryModel workspaceDirectoryModel, DocumentHierarchyFactory documentHierarchyFactory, FileSystemChangeWatcher fileSystemChangeWatcher)
 {
     this.iseIntegrator = iseIntegrator;
     this.iseFileReloader = iseFileReloader;
     this.commandExecutor = commandExecutor;
     this.workspaceDirectoryModel = workspaceDirectoryModel;
     this.documentHierarchyFactory = documentHierarchyFactory;
     this.fileSystemChangeWatcher = fileSystemChangeWatcher;
 }
        public static void Main()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            IUserInterface userInterface = new ConsoleUserInterface();
            var commandExecutor = new CommandExecutor();

            IEngine engine = new IssueTrackerEngine(commandExecutor, userInterface);
            engine.Run();
        }
        public static void Main()
        {
            var consoleOperator = new ConsoleOperator();
            var httpRequester = new Requester();
            var commandParser = new CommandParser();

            var commandExecutor = new CommandExecutor(httpRequester, consoleOperator);
            var gameEngine = new GameEngine(commandParser, commandExecutor, consoleOperator);

            gameEngine.Run();
        }
		public AppVersionController(IQueryRepository queries,
			CommandExecutor<CreateVersion> createExecutor,
			CommandExecutor<RenameVersion> renameExecutor,
			CommandExecutor<DeleteVersion> deleteExecutor,
			CommandExecutor<AssignVersion> assignExecutor,
			CommandExecutor<UnAssignVersion> unAssignExecutor)
		{
			_queries = queries;
			_createExecutor = createExecutor;
			_renameExecutor = renameExecutor;
			_deleteExecutor = deleteExecutor;
			_assignExecutor = assignExecutor;
			_unAssignExecutor = unAssignExecutor;
		}
        public void ExecuteCommand_TestOutputMessageWithAdd()
        {
            ICatalog currentCatalog = new Catalog();
            ICommand newCommand = new Command("Add application: Firefox v.11.0; Mozilla; 16148072; http://www.mozilla.org");
            StringBuilder output = new StringBuilder();

            CommandExecutor commandExecutor = new CommandExecutor();
            commandExecutor.ExecuteCommand(currentCatalog, newCommand, output);

            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.AppendLine("Application added");

            Assert.AreEqual(expectedOutput.ToString(), output.ToString());
        }
        public void Run()
        {
            var output = new StringBuilder();
            var catalog = new Catalog();
            ICommandExecutor commadExecutor = new CommandExecutor();
            var generatedCommands = GenerateCommandsFromInput();

            foreach (ICommand command in generatedCommands)
            {
                commadExecutor.ExecuteCommand(catalog, command, output);
            }

            Console.WriteLine(output.ToString().Trim());
        }
Beispiel #20
0
        public static void Main()
        {
            StringBuilder output = new StringBuilder();
            Catalog catalog = new Catalog();
            ICommandExecutor cmdExecutor = new CommandExecutor();

            var commands = ReadInputCommands();
            foreach (ICommand command in commands)
            {
                cmdExecutor.ExecuteCommand(catalog, command, output);
            }

            Console.Write(output);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GlimpseAdomdCommand"/> class.
 /// </summary>
 /// <param name="command">The wrapped adomdcommand.</param>
 /// <param name="connection">The wrapped adomdconnection.</param>
 /// <param name="connectionId">The Id of its related glimpseadomdconnection.</param>
 public GlimpseAdomdCommand(IAdomdCommand command, IAdomdConnection connection, Guid connectionId)
 {
     if (command == null)
     {
         throw new ArgumentNullException("command");
     }
     if (connection == null)
     {
         throw new ArgumentNullException("connection");
     }
     _innerCommand = command;
     _innerConnection = connection;
     _connectionId = connectionId;
     _commandExecutor = new CommandExecutor(this);
 }
Beispiel #22
0
		public BuildController(IQueryRepository queries,
			CommandExecutor<CreateBuild> createExecutor,
			CommandExecutor<CreateBulkOfBuilds> bulkCreateExecutor,
			CommandExecutor<RenameBuild> renameExecutor,
			CommandExecutor<DeleteBuild> deleteExecutor,
			CommandExecutor<AssignBuild> assignExecutor,
			CommandExecutor<UnAssignBuild> unAssignExecutor)
		{
			_queries = queries;
			_createExecutor = createExecutor;
			_bulkCreateExecutor = bulkCreateExecutor;
			_renameExecutor = renameExecutor;
			_deleteExecutor = deleteExecutor;
			_assignExecutor = assignExecutor;
			_unAssignExecutor = unAssignExecutor;
		}
        public void Execute_CallsResolverWithExpectedType()
        {
            bool wasCalledWithExpectedType = false;
              var commandDispatcher = new CommandExecutor(t =>
              {
            if (t == typeof(ICommandHandler<ICommand>))
            {
              wasCalledWithExpectedType = true;
            }
            return _handler;
              }, _validationProcessor);
              A.CallTo(() => _validationProcessor.Validate(_command)).Returns(new ValidationStatus());

              commandDispatcher.Execute(_command);

              Assert.That(wasCalledWithExpectedType, Is.True);
        }
        public void ExecuteCommand_TestOutputMessageWithFindMissingItem()
        {
            ICatalog currentCatalog = new Catalog();
            ICommand newCommand = new Command("Add movie: The Secret; Drew Heriot, Sean Byrne & others (2006); 832763834; http://t.co/dNV4d");
            StringBuilder output = new StringBuilder();

            CommandExecutor commandExecutor = new CommandExecutor();
            commandExecutor.ExecuteCommand(currentCatalog, newCommand, output);

            ICommand findCommand = new Command("Find: MissingName; 1");
            commandExecutor.ExecuteCommand(currentCatalog, findCommand, output);

            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.AppendLine("Movie added");
            expectedOutput.AppendLine("No items found");

            Assert.AreEqual(expectedOutput.ToString(), output.ToString());
        }
Beispiel #25
0
        private void InitializeWriteContext()
        {
            _container = new Container(i =>
                {
                    i.Scan(s =>
                                {
                                    s.AssemblyContainingType<WriteRegistry>();
                                    s.LookForRegistries();
                                });

                    i.For<IStoreEvents>()
                        .Singleton()
                        .Use(InitializeEventStore);
                });

            _executor = _container.GetInstance<CommandExecutor>();
            Storage.Store = _container.GetInstance<IStoreEvents>();
        }
        public void ExecuteCommand_TestOutputMessageWithFind()
        {
            ICatalog currentCatalog = new Catalog();
            ICommand newCommand = new Command("Add song: One; Metallica; 8771120; http://goo.gl/dIkth7gs");
            StringBuilder output = new StringBuilder();

            CommandExecutor commandExecutor = new CommandExecutor();
            commandExecutor.ExecuteCommand(currentCatalog, newCommand, output);

            ICommand findCommand = new Command("Find: One; 1");
            commandExecutor.ExecuteCommand(currentCatalog, findCommand, output);

            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.AppendLine("Song added");
            expectedOutput.AppendLine("Song: One; Metallica; 8771120; http://goo.gl/dIkth7gs");

            Assert.AreEqual(expectedOutput.ToString(), output.ToString());
        }
Beispiel #27
0
        private static void InitializeWriteContext()
        {
            ObjectFactory.Initialize(i =>
                {
                    i.Scan(s =>
                        {
                            s.AssemblyContainingType<WriteRegistry>();
                            s.LookForRegistries();
                        });

                    i.For<IStoreEvents>()
                        .Singleton()
                        .Use(InitializeEventStore);
                }
                );

            _executor = ObjectFactory.GetInstance<CommandExecutor>();
        }
        public void ExecuteCommand_TestOutputMessageWithUpdate()
        {
            ICatalog currentCatalog = new Catalog();
            ICommand newCommand = new Command("Add book: Intro C#; S.Nakov; 12763892; http://www.introprogramming.info");
            StringBuilder output = new StringBuilder();

            CommandExecutor commandExecutor = new CommandExecutor();
            commandExecutor.ExecuteCommand(currentCatalog, newCommand, output);

            ICommand updateCommand = new Command("Update: http://www.introprogramming.info; http://introprograming.info/en/");
            commandExecutor.ExecuteCommand(currentCatalog, updateCommand, output);

            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.AppendLine("Book added");
            expectedOutput.AppendLine("1 items updated");

            Assert.AreEqual(expectedOutput.ToString(), output.ToString());
        }
    static void Main(string[] args)
    {
        string phonesFilePath = "phones.txt";
        string commandsFilePath = "commands.txt";
        PhoneBook phonebook = new PhoneBook();
        List<Command> commands = new List<Command>();
        StringBuilder output = new StringBuilder();
       
        GeneratePhoneBook(phonesFilePath, phonebook);

        ParseCommands(commandsFilePath, commands);

        CommandExecutor executor = new CommandExecutor(phonebook, commands);
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        executor.ExecuteCommands(output);
        Console.WriteLine(stopwatch.Elapsed);
       // Console.WriteLine(output);
    }
        public KinectControlWindow(PRESENTATION_MODE mode, CommandExecutor Executor)
        {
            InitializeComponent();
            setWindowPosition();

            skeletonRepository = new SkeletonStateRepository();

            commands = new ServiceCommandsLocalActivation(Executor);

            //Runtime initialization is handled when the window is opened. When the window
            //is closed, the runtime MUST be unitialized.
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            //Handle the content obtained from the video camera, once received.
            this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);

            this.mode = mode;

            CreateGestureRecognition(mode);

            Minimize();
            UnMinimize();
        }
Beispiel #31
0
        private IScanClient GetSubjectUnderTest()
        {
            var executor = new CommandExecutor(new SocketClient(), "localhost", 3310);

            return(new ScanClient(executor));
        }
Beispiel #32
0
 public HistoricVariableInstanceQueryImpl(CommandExecutor commandExecutor) : base(commandExecutor)
 {
 }
Beispiel #33
0
 public UserQueryImpl(CommandExecutor commandExecutor) : base(commandExecutor)
 {
 }
Beispiel #34
0
        public async Task <HttpResponseMessage> ReverseMilePost(double?x, double?y,
                                                                [FromUri] ReverseMilepostOptions options)
        {
            var log         = Log.ForContext <GeocodeController>();
            var specificLog = log.ForContext("request-id", $"{x},{y}");

            specificLog.Warning("geocode(reverse-milepost): {x},{y}, with {@options}", x, y, options);

            #region validation

            var errors = "";
            if (!x.HasValue)
            {
                errors = "X is empty.";
            }

            if (!y.HasValue)
            {
                errors += "Y is emtpy";
            }

            if (errors.Length > 0)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              new ResultContainer <ReverseGeocodeResult>
                {
                    Status = (int)HttpStatusCode.BadRequest,
                    Message = errors
                }));
            }

            #endregion

            var baseUrl = "https://maps.udot.utah.gov/randh/rest/services/ALRS/MapServer/exts/LRSServer/networkLayers/0/";

            var point           = new GeometryToMeasure.Point(x.Value, y.Value);
            var requestContract = new GeometryToMeasure.RequestContract
            {
                Locations = new[] {
                    new GeometryToMeasure.RequestLocation {
                        Geometry = point
                    }
                },
                OutSr     = options.WkId,
                InSr      = options.WkId,
                Tolerance = options.Buffer
            };

            var requestUri = $"{baseUrl}geometryToMeasure{requestContract.QueryString}";

            HttpResponseMessage httpResponse;

            try
            {
                httpResponse = await App.HttpClient.GetAsync(requestUri);
            }
            catch (AggregateException ex)
            {
                specificLog.Fatal(ex, "geocode(reverse - milepost): aggregate exception");

                return(Request.CreateResponse(HttpStatusCode.InternalServerError,
                                              new ResultContainer
                {
                    Status = (int)HttpStatusCode.InternalServerError,
                    Message = "I'm sorry, it seems as though the request had issues."
                })
                       .AddTypeHeader(typeof(ResultContainer <ReverseMilepostResult>)));
            }

            try
            {
                httpResponse.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                specificLog.Fatal(ex, "geocode(reverse-milepost): general exception");

                return(Request.CreateResponse(HttpStatusCode.InternalServerError,
                                              new ResultContainer
                {
                    Status = (int)HttpStatusCode.InternalServerError,
                    Message = "I'm sorry, we were unable to communicate with the UDOT service."
                })
                       .AddTypeHeader(typeof(ResultContainer <ReverseMilepostResult>)));
            }

            GeometryToMeasure.ResponseContract response;

            try
            {
                response = await httpResponse.Content.ReadAsAsync <GeometryToMeasure.ResponseContract>(new[]
                {
                    new TextPlainResponseFormatter()
                });
            }
            catch (Exception ex)
            {
                specificLog.Fatal(ex, "geocode(reverse-milepost): error reading result");

                return(Request.CreateResponse(HttpStatusCode.InternalServerError,
                                              new ResultContainer
                {
                    Status = (int)HttpStatusCode.InternalServerError,
                    Message = "I'm sorry, we were unable to read the result."
                })
                       .AddTypeHeader(typeof(ResultContainer <ReverseMilepostResult>)));
            }

            if (!response.IsSuccessful)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              new ResultContainer
                {
                    Status = (int)HttpStatusCode.BadRequest,
                    Message = "Your request was invalid. Check that your coordinates and spatial reference match."
                })
                       .AddTypeHeader(typeof(ResultContainer <ReverseMilepostResult>)));
            }

            if (response.Locations?.Length != 1)
            {
                // this should not happen
                specificLog.Warning("geocode(reverse-milepost): multiple locations found");
            }

            var location = response.Locations[0];

            if (location.Status != GeometryToMeasure.Status.esriLocatingOK)
            {
                if (location.Status != GeometryToMeasure.Status.esriLocatingMultipleLocation)
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound,
                                                  new ResultContainer
                    {
                        Message = "No milepost was found within your buffer radius.",
                        Status = (int)HttpStatusCode.NotFound
                    })
                           .AddTypeHeader(typeof(ResultContainer <ReverseMilepostResult>)));
                }

                // concurrency
                var primaryRoutes = FilterPrimaryRoutes(location.Results, options.IncludeRampSystems == 1);

                if (primaryRoutes.Count < 1)
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound,
                                                  new ResultContainer
                    {
                        Message = "No milepost was found within your buffer radius.",
                        Status = (int)HttpStatusCode.NotFound
                    })
                           .AddTypeHeader(typeof(ResultContainer <ReverseMilepostResult>)));
                }

                var dominantRoutes = await CommandExecutor.ExecuteCommandAsync(
                    new DominantRouteResolverCommand(primaryRoutes, point, options.SuggestCount));

                return(Request.CreateResponse(HttpStatusCode.OK, new ResultContainer <ReverseMilepostResult>
                {
                    Status = (int)HttpStatusCode.OK,
                    Result = dominantRoutes
                })
                       .AddTypeHeader(typeof(ResultContainer <ReverseMilepostResult>))
                       .AddCache());
            }

            var routes = FilterPrimaryRoutes(location.Results, options.IncludeRampSystems == 1);

            if (routes.Count < 1)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound, new ResultContainer <ReverseMilepostResult>
                {
                    Message = "No milepost was found within your buffer radius.",
                    Status = (int)HttpStatusCode.NotFound
                }));
            }

            location = routes[0];

            return(Request.CreateResponse(HttpStatusCode.OK, new ResultContainer <ReverseMilepostResult>
            {
                Result = new ReverseMilepostResult
                {
                    Route = location.RouteId,
                    OffsetMeters = 0,
                    Milepost = location.Measure,
                    Dominant = true,
                    Candidates = Array.Empty <ReverseMilepostResult>()
                },
                Status = (int)HttpStatusCode.OK
            }));
        }
Beispiel #35
0
 public DFG <Block> NextDFG <T>(Dictionary <string, float> variables, CommandExecutor <T> executor, Dictionary <string, BoardFluid> dropPositions)
 {
     return(Cond.NextDFG);
 }
Beispiel #36
0
        public void handle_package_result(PackageResult packageResult, ChocolateyConfiguration config, CommandNameType commandName)
        {
            var pkgInfo = _packageInfoService.get_package_information(packageResult.Package);

            if (config.AllowMultipleVersions)
            {
                pkgInfo.IsSideBySide = true;
            }

            if (packageResult.Success && config.Information.PlatformType == PlatformType.Windows)
            {
                if (!config.SkipPackageInstallProvider)
                {
                    var before = _registryService.get_installer_keys();

                    var powerShellRan = _powershellService.install(config, packageResult);
                    if (powerShellRan)
                    {
                        // we don't care about the exit code
                        if (config.Information.PlatformType == PlatformType.Windows)
                        {
                            CommandExecutor.execute_static("shutdown", "/a", config.CommandExecutionTimeoutSeconds, _fileSystem.get_current_directory(), (s, e) => { }, (s, e) => { }, false, false);
                        }
                    }

                    var difference = _registryService.get_differences(before, _registryService.get_installer_keys());
                    if (difference.RegistryKeys.Count != 0)
                    {
                        //todo v1 - determine the installer type and write it to the snapshot
                        //todo v1 - note keys passed in
                        pkgInfo.RegistrySnapshot = difference;

                        var key = difference.RegistryKeys.FirstOrDefault();
                        if (key != null && key.HasQuietUninstall)
                        {
                            pkgInfo.HasSilentUninstall = true;
                        }
                    }
                }

                _configTransformService.run(packageResult, config);
                pkgInfo.FilesSnapshot = _filesService.capture_package_files(packageResult, config);

                if (packageResult.Success)
                {
                    _shimgenService.install(config, packageResult);
                }
            }
            else
            {
                if (config.Information.PlatformType != PlatformType.Windows)
                {
                    this.Log().Info(ChocolateyLoggers.Important, () => " Skipping Powershell and shimgen portions of the install due to non-Windows.");
                }
            }

            if (packageResult.Success)
            {
                handle_extension_packages(config, packageResult);
            }

            _packageInfoService.save_package_information(pkgInfo);
            ensure_bad_package_path_is_clean(config, packageResult);

            if (!packageResult.Success)
            {
                this.Log().Error(ChocolateyLoggers.Important, "The {0} of {1} was NOT successful.".format_with(commandName.to_string(), packageResult.Name));
                handle_unsuccessful_operation(config, packageResult, movePackageToFailureLocation: true, attemptRollback: true);

                return;
            }

            remove_rollback_if_exists(packageResult);

            this.Log().Info(ChocolateyLoggers.Important, " The {0} of {1} was successful.".format_with(commandName.to_string(), packageResult.Name));
        }
Beispiel #37
0
 public UpdateProcessInstancesSuspensionStateBuilderImpl(CommandExecutor commandExecutor)
 {
     this.processInstanceIds = new List <string>();
     this.commandExecutor    = commandExecutor;
 }
        public TestLibraryWindows(string baseUrl, string gdprUrl)
        {
            IAdjustCommandExecutor adjustCommandExecutor = new CommandExecutor(this, baseUrl, gdprUrl);

            _testLibraryInterface.Init(adjustCommandExecutor, baseUrl, UnityEngine.Debug.Log);
        }
Beispiel #39
0
 public DeploymentStatisticsQueryImpl(CommandExecutor executor) : base(executor)
 {
 }
Beispiel #40
0
        /// <summary>
        /// 将信息解密函数挂钩
        /// </summary>
        /// <param name="cmd"></param>
        public void HandleEncryptedMessage(CommandExecutor cmd)
        {
            //加密信息预先解密
            cmd.TextMessageReceiving += (s, e) =>
            {
                if (!e.IsHandled && e.Message.IsEncrypt)
                {
                    DecryptMessage(cmd, e);
                }
            };
            cmd.MessageProxy.MessageSending += (s, e) =>
            {
                if (!e.IsHandled && e.Message.Command == Consts.Commands.SendMsg && e.Message.IsEncrypt)
                {
                    EncryptMessage(cmd, e);
                }
            };
            cmd.MessageProcessing += (s, e) =>
            {
                if (e.IsHandled || e.Host == null)
                {
                    return;
                }

                if (e.Message.Command == Consts.Commands.AnsPubKey)
                {
                    //发送确认消息
                    MessageProxy.SendWithNoCheck(e.Host, Consts.Commands.RecvMsg, 0ul, e.Message.PackageNo.ToString(), "");

                    //分析
                    int index = e.Message.NormalMsg.IndexOf(":");
                    if (index == -1)
                    {
                        return;
                    }

                    ulong capa;
                    if (!ulong.TryParse(e.Message.NormalMsg.Substring(0, index++), System.Globalization.NumberStyles.AllowHexSpecifier, null, out capa))
                    {
                        return;
                    }
                    if ((capa & EncryptCapa) == 0)
                    {
                        return;
                    }

                    e.Host.SupportEncrypt       = true;
                    e.Host.IsEncryptUseSmallKey = (capa & EncryptNormalCapa) == 0;

                    int nextMatch;
                    if ((nextMatch = e.Message.NormalMsg.IndexOf('-', index)) == -1)
                    {
                        return;
                    }
                    byte[] exp = e.Message.NormalMsg.Substring(index, nextMatch - index).ConvertToBytes();
                    if (exp == null)
                    {
                        return;
                    }

                    byte[] pubKey = e.Message.NormalMsg.Substring(nextMatch + 1).ConvertToBytes();
                    if (pubKey == null)
                    {
                        return;
                    }

                    e.Host.SetEncryptInfo(pubKey, exp);

                    //查看有没有队列消息,有就发出去
                    if (e.Host.QueuedMessage != null && e.Host.QueuedMessage.Count > 0)
                    {
                        Message m = null;
                        while (e.Host.QueuedMessage.Count > 0)
                        {
                            m = e.Host.QueuedMessage.Dequeue();
                            MessageProxy.Send(m);
                        }
                    }
                }
                else if (e.Message.Command == Consts.Commands.GetPubKey)
                {
                    ulong capa;
                    if (!ulong.TryParse(e.Message.NormalMsg, System.Globalization.NumberStyles.AllowHexSpecifier, null, out capa))
                    {
                        return;
                    }

                    if ((capa & EncryptCapa) == 0)
                    {
                        return;
                    }

                    //返回响应
                    e.Host.SupportEncrypt       = true;
                    e.Host.IsEncryptUseSmallKey = (capa & EncryptNormalCapa) == 0;

                    byte[] key = e.Host.IsEncryptUseSmallKey ? PublicKey_512 : PublicKey_1024;
                    byte[] exp = e.Host.IsEncryptUseSmallKey ? Exponent_512 : Exponent_1024;

                    string content = string.Format("{0}:{1}-{2}", EncryptCapa.ToString("x"), BitConverter.ToString(exp).Replace("-", ""), BitConverter.ToString(key).Replace("-", "")).ToLower();
                    MessageProxy.SendWithNoCheck(e.Host, Consts.Commands.AnsPubKey, 0ul, content, "");
                }
            };
        }
Beispiel #41
0
        private Payload ProcessStream(
            Stream inputStream,
            Stream outputStream,
            Version version,
            out bool readComplete)
        {
            readComplete = false;

            try
            {
                DateTime bootTime = DateTime.UtcNow;

                Payload payload = new PayloadProcessor(version).Process(inputStream);
                if (payload is null)
                {
                    return(null);
                }

                ValidateVersion(payload.Version);

                DateTime initTime = DateTime.UtcNow;

                CommandExecutorStat commandExecutorStat = new CommandExecutor(version).Execute(
                    inputStream,
                    outputStream,
                    payload.SplitIndex,
                    payload.Command);

                DateTime finishTime = DateTime.UtcNow;

                WriteDiagnosticsInfo(outputStream, bootTime, initTime, finishTime);

                // Mark the beginning of the accumulators section of the output
                SerDe.Write(outputStream, (int)SpecialLengths.END_OF_DATA_SECTION);

                // TODO: Extend the following to write accumulator values here.
                SerDe.Write(outputStream, 0);

                // Check the end of stream.
                int endOfStream = SerDe.ReadInt32(inputStream);
                if (endOfStream == (int)SpecialLengths.END_OF_STREAM)
                {
                    s_logger.LogDebug($"[{TaskId}] Received END_OF_STREAM signal.");

                    SerDe.Write(outputStream, (int)SpecialLengths.END_OF_STREAM);
                    readComplete = true;
                }
                else
                {
                    // This may happen when the input data is not read completely,
                    // e.g., when take() operation is performed
                    s_logger.LogWarn($"[{TaskId}] Unexpected end of stream: {endOfStream}.");
                    s_logger.LogWarn(SerDe.ReadInt32(inputStream).ToString());

                    // Write a different value to tell JVM to not reuse this worker.
                    SerDe.Write(outputStream, (int)SpecialLengths.END_OF_DATA_SECTION);
                }

                LogStat(commandExecutorStat, readComplete);

                return(payload);
            }
            catch (Exception e)
            {
                s_logger.LogError($"[{TaskId}] ProcessStream() failed with exception: {e}");

                try
                {
                    SerDe.Write(outputStream, (int)SpecialLengths.PYTHON_EXCEPTION_THROWN);
                    SerDe.Write(outputStream, e.ToString());
                }
                catch (IOException)
                {
                    // JVM closed the socket.
                }
                catch (Exception ex)
                {
                    s_logger.LogError(
                        $"[{TaskId}] Writing exception to stream failed with exception: {ex}");
                }

                throw;
            }
        }
Beispiel #42
0
 public LdapTenantQuery(CommandExecutor commandExecutor) : base(commandExecutor)
 {
 }
        //// http://stackoverflow.com/a/8861895/18475
        //// http://stackoverflow.com/a/2864714/18475
        //[DllImport("kernel32.dll", SetLastError = true)]
        //private static extern bool SetDllDirectory(string lpPathName);

        //public struct DieInternal
        //{
        //    [SuppressUnmanagedCodeSecurity]
        //    [DllImport("diedll", CallingConvention = CallingConvention.StdCall, EntryPoint = "_DIE_scanExW@20", SetLastError = true)]
        //    internal static extern int scanExW_0([MarshalAs(UnmanagedType.LPWStr)] string pwszFileName, sbyte[] pszOutBuffer, int nOutBufferSize, uint nFlags, [MarshalAs(UnmanagedType.LPWStr)] string pwszDataBase);
        //}


        //public string scan_file(string filePath)
        //{
        //    if (Platform.get_platform() != PlatformType.Windows)
        //    {
        //        this.Log().Debug("Unable to detect file types when not on Windows");
        //        return string.Empty;
        //    }
        //    try
        //    {
        //        var successPath = SetDllDirectory(dieDllLocation);
        //        if (!successPath)
        //        {
        //            "chocolatey".Log().Warn("Error during native SetDllDirectory call - {0}".format_with(Marshal.GetLastWin32Error()));
        //        }
        //        var outputBuffer = new sbyte[1024];
        //        int outputBufferSize = outputBuffer.Length;
        //        const uint flags = DIE_SINGLELINEOUTPUT;

        //        var success = DieInternal.scanExW_0(filePath, outputBuffer, outputBufferSize, flags, databaseLocation);
        //        if (success != 0)
        //        {
        //            "chocolatey".Log().Warn("Error during native _DIE_scanExW call - {0}".format_with(Marshal.GetLastWin32Error()));
        //        }

        //        byte[] outputBytes = Array.ConvertAll(outputBuffer, (a) => (byte)a);

        //        var output = Encoding.UTF8.GetString(outputBytes).to_string().Trim('\0');

        //        return output;
        //    }
        //    catch (Exception ex)
        //    {
        //        this.Log().Warn("Unable to detect type for '{0}':{1} {2}".format_with(_fileSystem.get_file_name(filePath), Environment.NewLine, ex.Message));
        //        return string.Empty;
        //    }
        //}

        public string scan_file(string filePath)
        {
            if (Platform.get_platform() != PlatformType.Windows)
            {
                this.Log().Debug("Unable to detect file types when not on Windows");
                return(string.Empty);
            }

            // http://stackoverflow.com/q/5503951/18475
            // http://stackoverflow.com/a/10852827/18475
            // http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/
            //todo: convert this to call the exe assembly instead. The dll is 32bit and won't work with AnyCPU

            filePath = _fileSystem.get_full_path(filePath);
            var dieDllLocation   = _fileSystem.combine_paths(ApplicationParameters.InstallLocation, "tools", "detector");
            var diecPath         = _fileSystem.combine_paths(ApplicationParameters.InstallLocation, "tools", "detector", "diec.exe");
            var databaseLocation = _fileSystem.get_full_path(_fileSystem.combine_paths(ApplicationParameters.InstallLocation, "tools", "detector", "db"));

            this.Log().Debug("Attempting to detect type for '{0}' with db '{1}'".format_with(_fileSystem.get_file_name(filePath), databaseLocation));

            if (!_fileSystem.directory_exists(diecPath) || !_fileSystem.directory_exists(databaseLocation))
            {
                var dieZipLocation = _fileSystem.combine_paths(ApplicationParameters.InstallLocation, "tools", "detector.zip");
                unzip_die_files(dieZipLocation, dieDllLocation);
                // finish unpacking
                Thread.Sleep(1000);
            }

            if (!_fileSystem.file_exists(filePath))
            {
                this.Log().Warn("File not found at '{0}'. Unable to detect type for inexistent file.".format_with(filePath));
                return(string.Empty);
            }

            try
            {
                //todo: detector databaselocation fails now - it's based on the current directory relative path
                //C:\\ProgramData\\chocolatey\\tools\\detector\\db
                var output = string.Empty;
                // var success = CommandExecutor.execute_static(diecPath, "\"{0}\" -singlelineoutput:yes -showoptions:no -showversion:no -database:\"{1}\"".format_with(filePath, databaseLocation),
                var success = CommandExecutor.execute_static(diecPath, "\"{0}\"".format_with(filePath),
                                                             60,
                                                             _fileSystem.get_current_directory(),
                                                             (s, e) =>
                {
                    if (!string.IsNullOrWhiteSpace(e.Data))
                    {
                        output = e.Data;
                    }
                },
                                                             (s, e) =>
                {
                    if (!string.IsNullOrWhiteSpace(e.Data))
                    {
                        this.Log().Warn("{0}".format_with(e.Data));
                    }
                },
                                                             false,
                                                             false);

                return(output);
            }
            catch (Exception ex)
            {
                this.Log().Warn("Unable to detect type for '{0}':{1} {2}".format_with(_fileSystem.get_file_name(filePath), Environment.NewLine, ex.Message));
                return(string.Empty);
            }
        }
Beispiel #44
0
 public CleanableHistoricProcessInstanceReportImpl(CommandExecutor commandExecutor) : base(commandExecutor)
 {
 }
Beispiel #45
0
        protected internal virtual void clearDatabase()
        {
            CommandExecutor commandExecutor = processEngineConfiguration.CommandExecutorTxRequired;

            commandExecutor.execute(new CommandAnonymousInnerClass(this));
        }
Beispiel #46
0
        /// <summary>
        /// 加密信息
        /// </summary>
        /// <param name="cmd">Commander</param>
        /// <param name="e">事件参数</param>
        void EncryptMessage(CommandExecutor cmd, Entity.MessageEventArgs e)
        {
            Entity.Host host = null;
            if (cmd.LivedHost == null || (host = cmd.LivedHost.GetHost(e.Message.HostAddr.Address.ToString())) == null || !host.SupportEncrypt)
            {
                return;
            }

            if (host.PubKey == null)
            {
                //压入队列
                if (host.QueuedMessage == null)
                {
                    host.QueuedMessage = new Queue <FSLib.IPMessager.Entity.Message>();
                }
                host.QueuedMessage.Enqueue(e.Message);
                e.IsHandled = true;

                //请求公钥
                GetPubKey(host);
            }
            else
            {
                if (e.Message.NormalMsgBytes == null)
                {
                    System.Text.Encoding enc = e.Message.IsEncodingUnicode ? System.Text.Encoding.Unicode : System.Text.Encoding.Default;
                    if (!string.IsNullOrEmpty(e.Message.NormalMsg))
                    {
                        e.Message.NormalMsgBytes = enc.GetBytes(e.Message.NormalMsg);
                    }
                    else
                    {
                        e.Message.NormalMsgBytes = new byte[] { 0 }
                    };

                    if (!string.IsNullOrEmpty(e.Message.ExtendMessage))
                    {
                        e.Message.ExtendMessageBytes = enc.GetBytes(e.Message.ExtendMessage);
                    }
                    else
                    {
                        e.Message.ExtendMessageBytes = new byte[] { 0 }
                    };
                }
                if (e.Message.NormalMsgBytes == null)
                {
                    return;
                }

                //加密
                if (host.IsEncryptUseSmallKey)
                {
                    //RSA512&&RC2
                    //暂时不支持。。。
                    //TODO:加密支持RC2
                    e.Message.IsEncrypt = false;
                }
                else
                {
                    //RSA1024&BlowFish
                    byte[] key = new byte[8];
                    rcsp.GetBytes(key);

                    blowFish.Initialize(key, 0, key.Length);
                    byte[] content = new byte[(int)Math.Ceiling(e.Message.NormalMsgBytes.Length / 16.0) * 16];                          //BlowFish加密必须是16字节的整数倍
                    e.Message.NormalMsgBytes.CopyTo(content, 0);

                    blowFish.Encrypt(content, 0, content, 0, content.Length);
                    blowFish.Invalidate();

                    //加密Key
                    RSAParameters p = new RSAParameters()
                    {
                        Modulus  = host.PubKey,
                        Exponent = host.Exponent
                    };
                    RSA_1024_Encryptor.ImportParameters(p);
                    key = RSA_1024_Encryptor.Encrypt(key, false);
                    //Array.Reverse(key);

                    //组装消息
                    System.Text.StringBuilder sb = new StringBuilder();
                    sb.Append(EncryptNormalCapa.ToString("x"));
                    sb.Append(":");
                    sb.Append(key.ConvertToString());
                    sb.Append(":");
                    sb.Append(content.ConvertToString());

                    e.Message.NormalMsg      = sb.ToString();
                    e.Message.NormalMsgBytes = null;
                }
            }
        }

        /// <summary>
        /// 解析加密信息
        /// </summary>
        /// <param name="cmd">Commander</param>
        /// <param name="e">事件参数</param>
        void DecryptMessage(CommandExecutor cmd, Entity.MessageEventArgs e)
        {
            int index     = 0;
            int nextMatch = 0;

            if ((nextMatch = e.Message.NormalMsg.IndexOf(':', index)) == -1)
            {
                return;
            }
            ulong capa;

            if (!ulong.TryParse(e.Message.NormalMsg.Substring(index, nextMatch - index), System.Globalization.NumberStyles.AllowHexSpecifier, null, out capa))
            {
                return;
            }
            //查找密钥
            index = nextMatch + 1;
            if ((nextMatch = e.Message.NormalMsg.IndexOf(':', index)) == -1)
            {
                return;
            }
            byte[] buf = e.Message.NormalMsg.ConvertToBytes(index, nextMatch);
            //消息加密内容
            byte[] content = e.Message.NormalMsg.ConvertToBytes(nextMatch + 1, e.Message.NormalMsg.Length);

            //解密密钥
            bool isSuccess = false;

            Define.Consts.Cmd_Encrpy_Option encOpt = (Define.Consts.Cmd_Encrpy_Option)capa;
            if ((encOpt & Consts.Cmd_Encrpy_Option.RSA_1024) == Consts.Cmd_Encrpy_Option.RSA_1024)
            {
                //RSA1024
                try
                {
                    buf       = this.RSA_1024_Decryptor.Decrypt(buf, false);
                    isSuccess = true;
                }
                catch (Exception) { }
            }
            else
            {
                try
                {
                    buf       = this.RSA_512_Decryptor.Decrypt(buf, false);
                    isSuccess = true;
                }
                catch (Exception) { }
            }

            if (!isSuccess)
            {
                if ((encOpt & Consts.Cmd_Encrpy_Option.RSA_1024) == Consts.Cmd_Encrpy_Option.RSA_1024)
                {
                    cmd.SendCommand(e.Message.HostAddr, Consts.Commands.SendMsg, 0ul, "[AUTO=PUBKEY_EXP]\n\n公钥已经过期,无法解密信息,请刷新主机列表。", "", false, false, true, true, true, false, false, false);
                    e.IsHandled = true;                         //过滤掉消息
                    return;
                }
                else
                {
                    cmd.SendCommand(e.Message.HostAddr, Consts.Commands.SendMsg, 0ul, "[AUTO=KEY_NOT_SUPPORT]\n\n您的客户端所使用的加密等级过低,无法支持。", "", false, false, true, true, true, false, false, false);
                    e.IsHandled = true;                         //过滤掉消息
                    return;
                }
            }
            else
            {
                //解密文本
                if ((encOpt & Consts.Cmd_Encrpy_Option.RC2_40) == Consts.Cmd_Encrpy_Option.RC2_40)
                {
                    //TODO:RC2加密解决
                }
                else
                {
                    //BlowFish
                    blowFish.Initialize(buf, 0, buf.Length);
                    blowFish.Decrypt(content, 0, content, 0, content.Length);
                    blowFish.Invalidate();
                }

                int endIndex = Array.FindIndex(content, (s) => s == 0);
                if (endIndex == -1)
                {
                    endIndex = content.Length;
                }

                if (Define.Consts.Check(e.Message.Options, Define.Consts.Cmd_Send_Option.Content_Unicode))
                {
                    e.Message.NormalMsg = System.Text.Encoding.Unicode.GetString(content, 0, endIndex);
                }
                else
                {
                    e.Message.NormalMsg = System.Text.Encoding.Default.GetString(content, 0, endIndex);
                }
            }
        }

        /// <summary>
        /// 获得指定主机的公钥
        /// </summary>
        /// <param name="host">主机</param>
        void GetPubKey(Host host)
        {
            if (!host.SupportEncrypt)
            {
                return;
            }

            Commander.SendCommand(host, Consts.Commands.GetPubKey, 0ul, EncryptCapa.ToString("x"), "", false, false, false, false, false, false, false, false);
        }
Beispiel #47
0
 protected internal virtual void unlockJob(string nextJobId, CommandExecutor commandExecutor)
 {
     commandExecutor.execute(new UnlockJobCmd(nextJobId));
 }
 public MovieController(CommandExecutor commandExecutor, QueryExecutor queryExecutor)
 {
     _commandExecutor = commandExecutor;
     _queryExecutor   = queryExecutor;
 }
Beispiel #49
0
        public void EntryPoint(IStorageManager storageManager, IEmbeddedFileManager emb)
        {
            storageManager.Init("dos");
            using (UI)
            {
                UI.Show();  //显示ui
                InitUI();   //初始化ui


                ////执行前的一些检查与提示
                //SetProgress("Checking", 10);
                //if (!DoAppCheck()) return;//进行APP安装检查
                //if (!DoWarn()) return;//进行一系列提示与警告

                //做出一系列警告与提示,只要一个不被同意,立刻再见
                if (!(DoAppCheck() && DoWarn()))
                {
                    UI.Shutdown(); //直接关闭UI
                    return;        //退出函数
                }

                /* 正式开始流程 */

                //构造一个命令执行器
                using (CommandExecutor executor = new CommandExecutor())
                {
                    //创建一个OutputBuilder
                    OutputBuilder outputBuilder = new OutputBuilder();

                    //接收并记录所有executor的输出
                    outputBuilder.Register(executor);

                    //将命令执行器输出定向到界面
                    executor.To(e => UI.WriteOutput(e.Text));

                    //构造一个dpmpro的控制器
                    var dpmpro = new DpmPro(executor, emb, storageManager, Device);

                    //将dpmpro提取到临时目录
                    SetProgress("Extract", 0);
                    dpmpro.Extract();

                    //推送dpmpro到设备
                    SetProgress("Push", 20);
                    dpmpro.PushToDevice();

                    //移除账户
                    SetProgress("RMAcc", 40);
                    dpmpro.RemoveAccounts();

                    //移除用户
                    SetProgress("RMUser", 60);
                    dpmpro.RemoveUsers();

                    //使用可能的方式设置管理员,并记录结果
                    SetProgress("SettingDpm", 80);
                    var codeOfSetDeviceOwner = SetDeviceOwner(executor, dpmpro).ExitCode;

                    if (codeOfSetDeviceOwner == 0 &&      //如果设置成功并且
                        (PackageName == "com.catchingnow.icebox" || //目标包名是冰箱
                         PackageName == "web1n.stopapp")) //小黑屋
                    {
                        //给予APPOPS权限
                        executor.AdbShell(Device, $"pm grant {PackageName} android.permission.GET_APP_OPS_STATS");
                    }

                    //使用输出解析器,对记录的输出进行解析
                    DpmFailedMessageParser.Parse(codeOfSetDeviceOwner, outputBuilder.ToString(), out string tip, out string message);



                    //在输出框写下简要信息与建议
                    UI.WriteLine(message);
                    UI.ShowMessage(message);

                    //去除输出信息事件注册
                    outputBuilder.Unregister(executor);

                    //ui流程结束
                    UI.Finish(tip);
                }
            }
        }
Beispiel #50
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                                CancellationToken cancellationToken)
        {
            return(base.SendAsync(request, cancellationToken).ContinueWith(response =>
            {
                IEnumerable <string> formats, types;

                if (response.IsCanceled)
                {
                    return null;
                }

                var requestContent = HttpContentProvider.GetRequestContent(request);

                if (!requestContent.Headers.TryGetValues("X-Format", out formats))
                {
                    return response.Result;
                }

                if (response.Result == null || response.Result.Content == null || !formats.Contains("geojson"))
                {
                    return response.Result;
                }

                var responseContent = HttpContentProvider.GetResponseContent(response.Result);

                if (!responseContent.Headers.TryGetValues("X-Type", out types))
                {
                    return response.Result;
                }

                var typeName = types.FirstOrDefault();

                if (typeName == null)
                {
                    return response.Result;
                }

                var assembly = typeof(Domain.ApiResponses.GeocodeAddressResult).Assembly;
                var type = assembly.GetType(typeName);

                try
                {
                    var result = responseContent.ReadAsAsync(type)
                                 .ContinueWith(y =>
                    {
                        HttpStatusCode status;
                        var geoJson = CommandExecutor.ExecuteCommand(new CreateFeatureFromCommand(y.Result));

                        if (geoJson == null)
                        {
                            return response.Result;
                        }

                        Enum.TryParse(geoJson.Status.ToString(), out status);

                        return request.CreateResponse(status, geoJson);
                    });

                    return result.Result;
                }
                catch (AggregateException)
                {
                }

                return response.Result;
            }));
        }
Beispiel #51
0
 public void InitializeData()
 {
     this.engine        = new Engine(this.userInterface);
     this.executor      = new CommandExecutor(this.engine);
     this.userInterface = new ConsoleUserInterface();
 }
Beispiel #52
0
 public override float Run <T>(Dictionary <string, float> variables, CommandExecutor <T> executor, Dictionary <string, BoardFluid> dropPositions)
 {
     throw new InternalRuntimeException("This method is not supported for this block.");
 }
Beispiel #53
0
 /// <summary>
 /// Note: this is a hook to be overridden by
 /// org.camunda.bpm.container.impl.threading.ra.inflow.JcaInflowExecuteJobsRunnable.executeJob(String, CommandExecutor)
 /// </summary>
 protected internal virtual void executeJob(string nextJobId, CommandExecutor commandExecutor)
 {
     ExecuteJobHelper.executeJob(nextJobId, commandExecutor);
 }
Beispiel #54
0
 public override void Context()
 {
     commandExecutor = new CommandExecutor(fileSystem);
 }
 public PersonController(QueryExecutor queryExecutor, CommandExecutor commandExecutor)
 {
     _queryExecutor   = queryExecutor;
     _commandExecutor = commandExecutor;
 }
        public override void SetUp()
        {
            base.SetUp();
            App.Cache();

            var appConfig = new Config
            {
                AdminPage            = "admin.html",
                BaseUrl              = "http://testurl.com/",
                AdministrativeEmails = new[] { "*****@*****.**", "*****@*****.**" },
                Description          = "unit test description",
                Roles          = new[] { "admin", "role2", "role3", "role4" },
                UsersCanExpire = false,
                CustomEmails   = null
            };

            var hashedPassword =
                CommandExecutor.ExecuteCommand(new HashPasswordCommand("password", "SALT", ")(*&(*^%*&^$*^#$"));

            ApprovedAdmin = new User("admin", "user", "*****@*****.**", "AGENCY", hashedPassword.Result.HashedPassword,
                                     "SALT", null, "admin", "1admin.abc", null, null)
            {
                Approved = true
            };

            var notApprovedActiveUser = new User("Not Approved", " but Active", "*****@*****.**",
                                                 "AGENCY",
                                                 hashedPassword.Result.HashedPassword, "SALT", null,
                                                 null, null, null, null);

            var approvedActiveUser = new User("Approved and", "Active", "*****@*****.**", "AGENCY",
                                              hashedPassword.Result.HashedPassword, "SALT", null,
                                              "admin", null, null, null)
            {
                Active   = false,
                Approved = true
            };

            var notApprovedNotActiveUser = new User("Not approved", "or active", "*****@*****.**",
                                                    "AGENCY", hashedPassword.Result.HashedPassword, "SALT", null,
                                                    null, null, null, null)
            {
                Active = false
            };

            var accessRulesUser = new User("Not Approved", " but Active", "*****@*****.**",
                                           "AGENCY",
                                           hashedPassword.Result.HashedPassword, "SALT", null,
                                           null, null, null, null);

            using (var s = DocumentStore.OpenSession())
            {
                s.Store(appConfig, "1");
                s.Store(ApprovedAdmin, "1admin");
                s.Store(approvedActiveUser);
                s.Store(notApprovedActiveUser);
                s.Store(notApprovedNotActiveUser);
                s.Store(accessRulesUser);

                s.SaveChanges();
            }

            var config  = new HttpConfiguration();
            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/");

            _controller = new AdminController
            {
                Request           = request,
                DocumentStore     = DocumentStore,
                ValidationService = new MockValidationService()
            };

            _controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
        }
Beispiel #57
0
 public DeploymentQueryImpl(CommandExecutor commandExecutor) : base(commandExecutor)
 {
 }
 public void Execute(CommandExecutor executor)
 {
     executor.Execute(this);
 }
Beispiel #59
0
 static int Main(string[] args)
 {
     // As long as this doesn't blow up, we're good to go
     return(CommandExecutor.ExecuteCommand <NameCommand>(args));
 }
Beispiel #60
0
        public async Task <HttpResponseMessage> RouteMilePost(string route, string milepost, [FromUri] MilepostOptions options)
        {
            var log         = Log.ForContext <GeocodeController>();
            var specificLog = log.ForContext("request-id", $"{route},{milepost}");

            specificLog.Warning("geocode(milepost): {route},{milepost}, with {@options}", route, milepost, options);

            double milepostNumber = -1;

            #region validation

            var errors = "";

            var standardRoute = route;
            if (!options.FullRoute)
            {
                standardRoute = CommandExecutor.ExecuteCommand(new StandardizeRouteNameCommand(route, options.Side));
            }

            if (string.IsNullOrEmpty(route) || string.IsNullOrEmpty(standardRoute))
            {
                errors = "route is empty or in an unexpected format. Expected number eg: 15, 89.";
            }

            if (string.IsNullOrEmpty(milepost) || !double.TryParse(milepost, out milepostNumber))
            {
                errors += "milepost is empty or in unexpected format. Expected number eg: 300, 300.009";
            }

            if (errors.Length > 0)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              new ResultContainer <ReverseGeocodeResult>
                {
                    Status = (int)HttpStatusCode.BadRequest,
                    Message = errors
                }));
            }

            #endregion

            var response = await
                           CommandExecutor.ExecuteCommandAsync(new MilepostCommand(standardRoute, milepostNumber, options));

            if (response is null)
            {
                specificLog.Warning("geocode(milepost): not found");

                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              new ResultContainer <RouteMilepostResult>
                {
                    Status = (int)HttpStatusCode.NotFound,
                    Message = $"route {route} and milepost {milepost} was not found."
                })
                       .AddTypeHeader(typeof(ResultContainer <RouteMilepostResult>))
                       .AddCache());
            }

            specificLog.Warning("geocode(milepost): success {@response}", response);

            return(Request.CreateResponse(HttpStatusCode.OK,
                                          new ResultContainer <RouteMilepostResult>
            {
                Status = (int)HttpStatusCode.OK,
                Result = response
            })
                   .AddTypeHeader(typeof(ResultContainer <RouteMilepostResult>))
                   .AddCache());
        }