Beispiel #1
0
        public void When_prepending_item_on_cache_will_reply_with_stored()
        {
            var      buffer  = new byte[] { 1, 2, 3, 4 };
            ICommand command = new SetCommand();

            command.SetContext(GetStreamWithData(buffer));
            command.Init("foo", "1", "6000", "4");

            command.FinishedExecuting += () => { wait.Set(); };
            command.Execute();
            wait.WaitOne();

            wait.Reset();

            buffer = new byte[] { 5, 6, 7, 8 };
            MemoryStream stream = GetStreamWithData(buffer);

            command = new PrependCommand();
            command.SetContext(stream);
            command.Init("foo", "1", "6000", "4");

            command.FinishedExecuting += () => { wait.Set(); };
            command.Execute();
            wait.WaitOne();

            Assert.AreEqual("STORED\r\n", ReadAll(6, stream));
        }
Beispiel #2
0
    public static Task Set(this IKeyValueStore keyValueStore,
                           string key, string value, Moment?expiresAt, CancellationToken cancellationToken = default)
    {
        var command = new SetCommand(key, value, expiresAt);

        return(keyValueStore.Set(command, cancellationToken));
    }
        public static void Cut(User user)
        {
            try
            {
                UserSession userSession = WorldEditManager.GetUserSession(user);
                WorldRange  region      = userSession.Selection;

                WorldEditCommand command = new CopyCommand(user);
                if (command.Invoke(region))
                {
                    user.Player.MsgLoc($"Copy done in {command.ElapsedMilliseconds}ms.");
                    command = new SetCommand(user, "Empty");
                    if (command.Invoke(region))
                    {
                        user.Player.MsgLoc($"{command.BlocksChanged} blocks cleared in {command.ElapsedMilliseconds}ms.");
                    }
                }
            }
            catch (WorldEditCommandException e)
            {
                user.Player.ErrorLocStr(e.Message);
            }
            catch (Exception e)
            {
                Log.WriteError(Localizer.Do($"{e}"));
            }
        }
Beispiel #4
0
        public void When_prepending_item_on_cache_will_prepend_to_data_already_on_cache()
        {
            var      buffer  = new byte[] { 1, 2, 3, 4 };
            ICommand command = new SetCommand();

            command.SetContext(GetStreamWithData(buffer));
            command.Init("foo", "1", "6000", "4");

            command.FinishedExecuting += () => { wait.Set(); };
            command.Execute();
            wait.WaitOne();

            wait.Reset();

            buffer = new byte[] { 5, 6, 7, 8 };
            MemoryStream stream = GetStreamWithData(buffer);

            command = new PrependCommand();
            command.SetContext(stream);
            command.Init("foo", "1", "6000", "4");

            command.FinishedExecuting += () => { wait.Set(); };
            command.Execute();
            wait.WaitOne();

            var item = (CachedItem)Cache.Get("foo");

            CollectionAssert.AreEqual(new byte[] { 5, 6, 7, 8, 1, 2, 3, 4, }, item.Buffer);
        }
Beispiel #5
0
        public void CreateSetCommand()
        {
            SetCommand command = new SetCommand("foo", new ConstantExpression(1));

            Assert.AreEqual("foo", command.Name);
            Assert.IsInstanceOfType(command.Expression, typeof(ConstantExpression));
        }
Beispiel #6
0
        public static Task <int> Main(string[] args)
        {
            var command = new RootCommand()
            {
                Description = "Developer tool to update the Visual Studio project versions."
            };

            command.AddCommand(ListCommand.Create());
            command.AddCommand(MajorCommand.Create());
            command.AddCommand(MinorCommand.Create());
            command.AddCommand(PatchCommand.Create());
            command.AddCommand(BuildCommand.Create());
            command.AddCommand(PreCommand.Create());
            command.AddCommand(SetCommand.Create());


            var builder = new CommandLineBuilder(command)
                          .UseHelp()
                          .UseDefaults()
                          .UseVersionOption()
                          .CancelOnProcessTermination()
                          .UseExceptionHandler();

            var parser = builder.Build();

            return(parser.InvokeAsync(args));
        }
Beispiel #7
0
 public void Visit(SetCommand cmd)
 {
     this.writer.Write(cmd.Name);
     this.writer.Write(" = ");
     cmd.Expression.Accept(this);
     this.writer.WriteLine(";");
 }
Beispiel #8
0
        public void ExecuteSetCommandWithComplexDotExpression()
        {
            BindingEnvironment environment = new BindingEnvironment();
            DotExpression      dot         = new DotExpression(new VariableExpression("foo"), "Address");
            DotExpression      dotexpr     = new DotExpression(dot, "Street");
            SetCommand         command     = new SetCommand(dotexpr, new ConstantExpression("bar"));

            command.Execute(environment);

            object obj = environment.GetValue("foo");

            Assert.IsNotNull(obj);
            Assert.IsInstanceOfType(obj, typeof(DynamicObject));

            DynamicObject dynobj = (DynamicObject)obj;

            object obj2 = dynobj.GetValue("Address");

            Assert.IsNotNull(obj2);
            Assert.IsInstanceOfType(obj2, typeof(DynamicObject));

            DynamicObject dynobj2 = (DynamicObject)obj2;

            Assert.AreEqual("bar", dynobj2.GetValue("Street"));
        }
Beispiel #9
0
        public void DecompileSetCommandWithArithmeticOperation()
        {
            IExpression expression = new ArithmeticBinaryExpression(ArithmeticOperation.Add, new ConstantExpression(1), new ConstantExpression(2));
            ICommand    command    = new SetCommand("a", expression);

            Assert.AreEqual("a = (1 + 2);\r\n", this.Decompile(command));
        }
Beispiel #10
0
        public async Task ExecuteAsync_UploadsCorrectlyModifiedBuild()
        {
            // Arrange
            var build         = TestUtilities.CreateValidBuild();
            var expectedBuild = TestUtilities.CreateValidBuild();

            expectedBuild["variables"]["Variable"] = TestUtilities.CreateValidVariableJObject();
            var variables = new Dictionary <string, Variable>
            {
                { "Variable", TestUtilities.CreateValidVariable() }
            };
            var azureClient = CreateValidAzureClient();

            azureClient.GetAsync(Arg.Any <string>()).Returns(JsonConvert.SerializeObject(build));
            var output  = CreateValidOutput();
            var options = CreateValidSetOptions(AvmObjectType.BuildVariables);

            File.WriteAllText(options.SourceFilePath, JsonConvert.SerializeObject(variables));
            var setCommand = new SetCommand(options, new ReleaseTransformer(),
                                            new VariableContainerTransformer(), CreateValidUrlStore(), azureClient, output);

            // Act
            await setCommand.ExecuteAsync();

            File.Delete(options.SourceFilePath);

            // Assert
            await azureClient.Received().PutAsync(Arg.Any <string>(), Arg.Is <string>(res => JToken.DeepEquals(JsonConvert.DeserializeObject <JToken>(res), expectedBuild)));
        }
Beispiel #11
0
        private ICommand MakeAddCommand(string target, string source, int number)
        {
            IExpression add = new BinaryArithmeticExpression(new VariableExpression(source), new ConstantExpression(number), ArithmeticOperator.Add);
            ICommand    set = new SetCommand(target, add);

            return(set);
        }
Beispiel #12
0
        public void DecompileSetCommandWithArithmeticOperationAndVariables()
        {
            IExpression expression = new ArithmeticBinaryExpression(ArithmeticOperation.Add, new VariableExpression("b"), new VariableExpression("c"));
            ICommand    command    = new SetCommand("a", expression);

            Assert.AreEqual("a = (b + c);\r\n", this.Decompile(command));
        }
Beispiel #13
0
        public void When_prepending_item_on_cache_will_not_modify_flags()
        {
            var      buffer  = new byte[] { 1, 2, 3, 4 };
            ICommand command = new SetCommand();

            command.SetContext(GetStreamWithData(buffer));
            command.Init("foo", "1", "6000", "4");

            command.FinishedExecuting += () => { wait.Set(); };
            command.Execute();
            wait.WaitOne();

            wait.Reset();

            buffer = new byte[] { 5, 6, 7, 8 };
            MemoryStream stream = GetStreamWithData(buffer);

            command = new PrependCommand();
            command.SetContext(stream);
            command.Init("foo", "15", "6000", "4");

            command.FinishedExecuting += () => { wait.Set(); };
            command.Execute();
            wait.WaitOne();

            var item = (CachedItem)Cache.Get("foo");

            Assert.AreEqual(1, item.Flags);
        }
 public async Task ReadResponse()
 {
     var command = new SetCommand();
     await StorageCommandValidator.AssertReadResponse(command, StorageCommandResult.Stored, true);
     await StorageCommandValidator.AssertReadResponseFailure<SetCommand, bool>(command, StorageCommandResult.NotStored);
     await StorageCommandValidator.AssertReadResponseFailure<SetCommand, bool>(command, StorageCommandResult.NotFound);
     await StorageCommandValidator.AssertReadResponseFailure<SetCommand, bool>(command, StorageCommandResult.Exists);
 }
Beispiel #15
0
        public async Task SetProgram(int program)
        {
            await Task.Yield();

            var command = new SetCommand(Tuner, CommandNames.Program, $"{program:d}", LockKey);

            await Send(command);
        }
Beispiel #16
0
        public async Task SetFrequency(decimal frequency)
        {
            await Task.Yield();

            var command = new SetCommand(Tuner, CommandNames.Channel, $"auto:{frequency:#.000000}".Replace(".", ""), LockKey);

            await Send(command);
        }
Beispiel #17
0
        public async Task SetChannelMap(string channelMap)
        {
            await Task.Yield();

            var command = new SetCommand(Tuner, CommandNames.ChannelMap, channelMap, LockKey);

            await Send(command);
        }
        public DirectoryItems(string source, string target)
        {
            Target = target;
            Source = source;

            FileFilter fileFilter = new FileFilter();
            SetCommand setCommand = new SetCommand(fileFilter.Md5Check);
        }
        public static Result <Command> FromString(string command, string[] parameters)
        {
            try
            {
                if (!Enum.TryParse <CommandType>(command, ignoreCase: true, out var parsedCommandType))
                {
                    throw new ArgumentException(message: $"Could not parse `{nameof(CommandType)}` from string `{command}`", paramName: nameof(command));
                }

                Command?parsedCommand = null;
                switch (parsedCommandType)
                {
                case CommandType.Get:
                    parsedCommand = new GetCommand();
                    break;

                case CommandType.Set:
                    parsedCommand = new SetCommand()
                    {
                        Value = Encoding.UTF8.GetBytes(parameters[1]),
                    };
                    break;

                case CommandType.CompareExchange:
                    parsedCommand = new CompareExchangeCommand()
                    {
                        Comparand = Encoding.UTF8.GetBytes(parameters[1]),
                        Value     = Encoding.UTF8.GetBytes(parameters[2]),
                    };
                    break;

                case CommandType.CompareRemove:
                    parsedCommand = new CompareRemoveCommand()
                    {
                        Comparand = Encoding.UTF8.GetBytes(parameters[1]),
                    };
                    break;

                case CommandType.Remove:
                    parsedCommand = new RemoveCommand();
                    break;

                case CommandType.PrefixEnumerate:
                    parsedCommand = new PrefixEnumerateCommand();
                    break;
                }

                Contract.Assert(parsedCommand != null);

                parsedCommand.Key = Encoding.UTF8.GetBytes(parameters[0]);

                return(new Result <Command>(parsedCommand));
            }
            catch (Exception e)
            {
                return(new Result <Command>(e, message: $"Failed to parse request `{command}` with parameters `{string.Join(", ", parameters)}`"));
            }
        }
        public void CreateSimpleDefinedFunction()
        {
            IList <Parameter> parameters = new Parameter[] { new Parameter("a", null, false), new Parameter("b", null, false) };
            ICommand          body       = new SetCommand("c", new NameExpression("a"));
            DefinedFunction   func       = new DefinedFunction("foo", parameters, body, null);

            Assert.AreEqual(parameters, func.Parameters);
            Assert.AreEqual(body, func.Body);
        }
        public static SelectSelector <TSelect1> Select <TSelect1>(this SetCommand selector)
        {
            var selectSelector = new SelectSelector <TSelect1>(selector.Client)
            {
                ParentSelector = selector
            };

            return(selectSelector);
        }
Beispiel #22
0
        public void ExecuteSetCommand()
        {
            SetCommand command = new SetCommand("foo", new ConstantExpression("bar"));
            Machine    machine = new Machine();

            command.Execute(machine.Environment);

            Assert.AreEqual("bar", machine.Environment.GetValue("foo"));
        }
Beispiel #23
0
        public void ExecuteSetCommandWithVariable()
        {
            BindingEnvironment environment = new BindingEnvironment();
            SetCommand         command     = new SetCommand(new VariableExpression("foo"), new ConstantExpression("bar"));

            command.Execute(environment);

            Assert.AreEqual("bar", environment.GetValue("foo"));
        }
Beispiel #24
0
        public void DecompileCompositeCommand()
        {
            IExpression expression = new ArithmeticBinaryExpression(ArithmeticOperation.Add, new ConstantExpression(1), new ConstantExpression(2));
            ICommand    command1   = new SetCommand("a", expression);
            ICommand    command2   = new SetCommand("b", expression);
            ICommand    command    = new CompositeCommand(new ICommand[] { command1, command2 });

            Assert.AreEqual("{\r\na = (1 + 2);\r\nb = (1 + 2);\r\n}\r\n", this.Decompile(command));
        }
Beispiel #25
0
        public void ExecuteSetCommand()
        {
            BindingEnvironment environment = new BindingEnvironment();
            ICommand           command     = new SetCommand("one", new ConstantExpression(1));

            command.Execute(environment);

            Assert.AreEqual(1, environment.GetValue("one"));
        }
        public void CreateAndExecuteTryCommand()
        {
            BindingEnvironment environment = new BindingEnvironment();
            ICommand           body        = new SetCommand("a", new ConstantExpression(1));
            TryCommand         command     = new TryCommand(body);

            command.Execute(environment);

            Assert.AreEqual(1, environment.GetValue("a"));
        }
        public void CreateSimpleDefCommand()
        {
            IList <ParameterExpression> parameters = new ParameterExpression[] { new ParameterExpression("a", null, false), new ParameterExpression("b", null, false) };
            ICommand   body    = new SetCommand("c", new ConstantExpression(1));
            DefCommand command = new DefCommand("foo", parameters, body);

            Assert.AreEqual("foo", command.Name);
            Assert.AreEqual(parameters, command.ParameterExpressions);
            Assert.AreEqual(body, command.Body);
        }
Beispiel #28
0
        public void SetCommand()
        {
            Context context = new Context();

            Assert.IsNull(context.GetValue("foo"));
            SetCommand command = new SetCommand("foo", new ConstantExpression("bar"));

            command.Execute(context);
            Assert.AreEqual("bar", context.GetValue("foo"));
        }
        public void ConfigSet_SetAll_Execute_ReturnsSuccess()
        {
            var console = new TestConsole(_output, "config value edited");
            var command = new SetCommand(_engineConfig.Object, console, (new Mock <ILogger <SetCommand> >()).Object);

            var message = command.Execute();

            Assert.Equal("config value edited", _configs["config1"]);
            Assert.Equal("Config values have been saved successfully.", message);
        }
        private string PerformSet(SetCommand command)
        {
            if (_storage.TryAdd(command.Key, new StringValue(command.Value)))
            {
                return(command.Value);
            }

            // TODO: add error handling
            return("Key already exists");
        }
Beispiel #31
0
        public static SetCommand GetTrackerSetCommand(string key, object value)
        {
            var result = new SetCommand()
            {
                Key   = key,
                Value = value,
            };

            return(result);
        }
Beispiel #32
0
        public async Task SetCommandHandlerDefaultConfigurationHasDefinedVariables()
        {
            var definedVariables = new[] { "border", "topkmap" };
            var setCommand = new SetCommand();
            var setCommandHandler = new SetCommandHandler(this.notificationService);

            (await setCommandHandler.Execute(setCommand)).Should().BeTrue();

            var output = this.notificationService.InfoString;
            foreach (var variable in definedVariables)
            {
                output.Should().Contain(variable);
            }

            // Set command appends a new line by default to end of output, hence + 1
            output.Split('\r').Length.Should().Be(definedVariables.Length + 1);
        }
Beispiel #33
0
        public async Task SetCommandHandlerExecutePrintsNullForSettingIfNoValueIsSpecified()
        {
            var setCommand = new SetCommand { Args = "var1doesnotexist" };

            (await this.testableSetCommandHandler.Execute(setCommand)).Should().BeTrue();

            this.notificationService.InfoString.Should().Be("var1doesnotexist = <undefined>\r\n");
        }
        /// <summary>
        /// UpdateTransaction
        /// </summary>
        /// <param name="cmds"></param>
        /// <param name="setCommand"></param>
        public static void UpdateTransaction(ICollection<MyDbCommand> cmds, SetCommand setCommand)
        {
            //MyDbCommand cmdCurrent = null;

            foreach (MyDbCommand cmd in cmds)
            {
                try
                {
                    if (cmd == null || cmd.Command == null)
                    {
                        throw new ArgumentException("cmds has null Command", "cmds");
                    }
                    //cmdCurrent = cmd;

                    // Do at out delegate
                    setCommand(cmd);

                    object actualResult = null;
                    if (cmd.Command.CommandText.IndexOf("INSERT", StringComparison.Ordinal) != -1
                        || cmd.Command.CommandText.IndexOf("UPDATE", StringComparison.Ordinal) != -1
                        || cmd.Command.CommandText.IndexOf("DELETE", StringComparison.Ordinal) != -1)
                    {
                        actualResult = cmd.Command.ExecuteNonQuery();
                    }
                    else if (cmd.Command.CommandText.IndexOf("SELECT", StringComparison.Ordinal) != -1)
                    {
                        actualResult = cmd.Command.ExecuteScalar();
                    }
                    else
                    {
                        throw new NotSupportedException("Invalid Sql Command Format. Now only INSERT,UPDATE,DELETE,SELECT Supported!");
                    }

                    switch (cmd.ExpectedResultType)
                    {
                        case ExpectedResultTypes.Any:
                            break;
                        case ExpectedResultTypes.GreaterThanOrEqualZero:
                            if ((int)actualResult < 0)
                            {
                                throw new DBConcurrencyException(cmd.ErrorMsg);
                            }
                            break;
                        case ExpectedResultTypes.GreaterThanZero:
                            if ((int)actualResult <= 0)
                            {
                                throw new DBConcurrencyException(cmd.ErrorMsg);
                            }
                            break;
                        case ExpectedResultTypes.Special:
                            if ((actualResult == null && cmd.ExpectedResult != null)
                                || (actualResult != null && cmd.ExpectedResult == null))
                            {
                                throw new DBConcurrencyException(cmd.ErrorMsg);
                            }

                            if (actualResult.ToString() != cmd.ExpectedResult.ToString())
                            {
                                throw new DBConcurrencyException(cmd.ErrorMsg);
                            }
                            break;
                        default:
                            throw new NotSupportedException("Invalid MyDbCommand ExpectedType!");
                    }
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(cmd.Command.CommandText + " ִ�д���", ex);
                }
            }
        }
 public override void ExplicitVisit(SetCommand fragment)
 {
     _fragments.Add(fragment);
 }
Beispiel #36
0
        public async Task SetCommandHandlerExecutePrintsSettingIfNoValueIsSpecified()
        {
            var setCommand = new SetCommand { Args = "var1" };

            (await this.testableSetCommandHandler.Execute(setCommand)).Should().BeTrue();

            this.notificationService.InfoString.Should().Be("var1 = value1\r\n");
        }
Beispiel #37
0
        public async Task SetCommandHandlerExecuteCreatesSettingIfNotExists()
        {
            var setCommand = new SetCommand { Args = "var2doesnotexist value2" };

            (await this.testableSetCommandHandler.Execute(setCommand)).Should().BeTrue();

            this.configurationMap["var2doesnotexist"].Should().Be("value2");
        }
Beispiel #38
0
        public async Task SetCommandHandlerHasDefaultValueForBorderVariable()
        {
            var setCommand = new SetCommand { Args = "border" };
            var setCommandHandler = new SetCommandHandler(this.notificationService);

            (await setCommandHandler.Execute(setCommand)).Should().BeTrue();

            this.notificationService.InfoString.Should().Be("border = 1\r\n");
        }
Beispiel #39
0
 public void SetCommandHasNameAsSet()
 {
     var setCommand = new SetCommand();
     setCommand.Name.Should().Be("set");
 }
Beispiel #40
0
        public async Task SetCommandHandlerExecuteSetsValueToExistingSetting()
        {
            var setCommand = new SetCommand { Args = "var2 value2new" };

            (await this.testableSetCommandHandler.Execute(setCommand)).Should().BeTrue();

            this.configurationMap["var2"].Should().Be("value2new");
        }
Beispiel #41
0
 public override void ExplicitVisit(SetCommand node) { this.action(node); }
Beispiel #42
0
        public async Task SetCommandHandlerExecuteWithNullOrEmptyArgsPrintsValuesOfAllVariables()
        {
            var setCommand = new SetCommand();

            (await this.testableSetCommandHandler.Execute(setCommand)).Should().BeTrue();

            this.notificationService.InfoString.Should().Be("var1 = value1\r\nvar2 = value2\r\n");
        }