Esempio n. 1
0
        public void Processing_command_against_older_version_of_aggregate_should_throw()
        {
            Guid aggregateId = Guid.NewGuid();

            var creatingCommandMetadata = new CommandMetadata
                                              {
                                                  CommandId = Guid.NewGuid(),
                                                  TargetType = typeof (TestAggregate),
                                                  TargetId = aggregateId
                                              };

            _facade.Execute(creatingCommandMetadata, x => ((TestAggregate) x).TestMethod("Creating..."));

            var susequentCommandMetadata = new CommandMetadata
                                               {
                                                   CommandId = Guid.NewGuid(),
                                                   TargetType = typeof (TestAggregate),
                                                   TargetId = aggregateId
                                               };

            var yetAnotherCommandMetadata = new CommandMetadata
                                                {
                                                    CommandId = Guid.NewGuid(),
                                                    TargetType = typeof (TestAggregate),
                                                    TargetId = aggregateId,
                                                    LastKnownRevision = 1
                                                };

            _facade.Execute(susequentCommandMetadata, x => ((TestAggregate)x).TestMethod("First attempt"));

            Assert.Throws<ConcurrencyException>(() => _facade.Execute(yetAnotherCommandMetadata, x => ((TestAggregate)x).TestMethod(
                "Second attempt")));
        }
Esempio n. 2
0
        public void Processing_the_same_command_twice_should_trow()
        {
            Guid aggregateId = Guid.NewGuid();

            var creatingCommandMetadata = new CommandMetadata
                                              {
                                                  CommandId = Guid.NewGuid(),
                                                  TargetType = typeof (TestAggregate),
                                                  TargetId = aggregateId
                                              };

            _facade.Execute(creatingCommandMetadata, x => ((TestAggregate)x).TestMethod("Creating..."));

            var duplicateCommandMetadata = new CommandMetadata
                                               {
                                                   CommandId = Guid.NewGuid(),
                                                   TargetType = typeof (TestAggregate),
                                                   TargetId = aggregateId
                                               };

            _facade.Execute(duplicateCommandMetadata, x => ((TestAggregate)x).TestMethod("First attempt"));

            Assert.Throws<DuplicateCommitException>(() => _facade.Execute(duplicateCommandMetadata, x => ((TestAggregate) x).TestMethod(
                "Second attempt")));
        }
Esempio n. 3
0
            public Task <Result> Execute(CommandMetadata data, SocketGuildUser shippieOne, SocketGuildUser shippieTwo)
            {
                var succesful = ParentPlugin.Ship(data.AuthorID, shippieOne.Id, shippieTwo.Id);

                if (succesful)
                {
                    return(TaskResult(succesful, "Succesfully shipped " + shippieOne.GetShownName() + " and " + shippieTwo.GetShownName() + ", now known as " + ParentPlugin.GetShipName(ParentPlugin.GetShipByShippies(shippieOne.Id, shippieTwo.Id)) + "."));
                }
                return(TaskResult(succesful, $"Failed to ship {shippieOne.GetShownName ()} x {shippieTwo.GetShownName ()} - You've already shipped them."));
            }
Esempio n. 4
0
            public Task <Result> Execute(CommandMetadata data, SocketGuildUser shippieOne, SocketGuildUser shippieTwo)
            {
                var succesful = ParentPlugin.Sink(data.AuthorID, shippieOne.Id, shippieTwo.Id);

                if (succesful)
                {
                    return(TaskResult(true, "Succesfully sunk " + ParentPlugin.GetShipName(ParentPlugin.GetShipByShippies(shippieOne.Id, shippieTwo.Id)) + ", at least for you."));
                }
                return(TaskResult(false, $"Failed to sink that ship, as you have not shipped them yet."));
            }
Esempio n. 5
0
        public override string AllowExecution(CommandMetadata metadata)
        {
            string baseAllowance = base.AllowExecution(metadata);

            if (!IsAdmin(metadata.AuthorID))
            {
                baseAllowance += "\t" + "User is not a bot administrator.";
            }
            return(baseAllowance);
        }
Esempio n. 6
0
 /// <summary>
 /// Generates a new parser that uses the given registry, args, metadata, context, and ID to run
 /// </summary>
 /// <param name="registry">Registry from which the parser will obtain <see cref="IObjectConverter"/>s</param>
 /// <param name="input">The original input string</param>
 /// <param name="additionalArgs">Any additional arguments to be added to the end of the argument list</param>
 /// <param name="metadata">CommandMetadata containing information used to parse and execute</param>
 /// <param name="exeData"><see cref="CommandExecutorData"/> containing the data required for execution</param>
 /// <param name="ctx">Context object passed to the executed command, and an <see cref="IObjectConverter"/>s that are used</param>
 /// <param name="callback">Reference to a method used as a callback when processing completes</param>
 public Parser(CommandRegistry registry,
               string input,
               IEnumerable <object> additionalArgs,
               CommandMetadata metadata,
               CommandExecutorData exeData,
               IContextObject ctx,
               InputResultDelegate callback)
     : base(registry, input, additionalArgs, metadata, exeData, ctx, callback)
 {
 }
Esempio n. 7
0
        public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo)
        {
            var metadata          = new CommandMetadata(info);
            var privateCmdletName = metadata.Name.Split('!').First();
            var parts             = privateCmdletName.Split('_');

            return(parts.Length > 1
                ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) }
                   // Process multiple parameter sets, so we declare a variant per parameter set.
                : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray());
        }
 /// <inheritdoc />
 public void Authroized <T>(T command, CommandMetadata metadata)
     where T : ICommand
 {
     this.SetBaseInfo(
         command,
         info =>
     {
         info.Authorized = true;
     },
         metadata);
 }
 /// <inheritdoc />
 public void Handled <T>(T command, CommandMetadata metadata)
     where T : ICommand
 {
     this.SetBaseInfo(
         command,
         info =>
     {
         info.Handled = true;
     },
         metadata);
 }
Esempio n. 10
0
        public Task HandleAsync(BasicCommand command, CommandMetadata metadata)
        {
            this.TrackingStore.Handled(command, metadata);

            if (command.Name == "handler-exception")
            {
                throw new System.Exception();
            }

            return(Task.CompletedTask);
        }
        public void GetContext_NullMetadata_ReturnsNull()
        {
            // Arrange
            CommandMetadata metadata = null;

            // Act
            var result = metadata.GetContext <TestContext1>();

            // Assert
            Assert.Null(result);
        }
Esempio n. 12
0
            public async Task <Result> Execute(CommandMetadata data, string name)
            {
                SocketGuildUser user = data.Message.Author as SocketGuildUser;

                if (user.VoiceChannel != null)
                {
                    await ParentPlugin.SetCustomName(user.VoiceChannel, name);

                    return(new Result(null, $"Succesfully set custom voice channel name to {name}."));
                }
                return(new Result(null, "You aren't in a voice channel at the moment. At least not on this server."));
            }
            public async Task <Result> Execute(CommandMetadata metadata, string query)
            {
                JObject result = await ParentPlugin.QueryAsync(SourceUrl, query);

                Embed embed = ParentPlugin.BuildPageEmbed(result);

                if (embed == null)
                {
                    return(new Result(null, "Sorry fam, the wiki fetch failed."));
                }
                return(new Result(embed, string.Empty));
            }
Esempio n. 14
0
            public Task <Result> Execute(CommandMetadata data, SocketGuildUser user)
            {
                var    allShips = ParentPlugin.GetAllShipperShips(user);
                string result   = $"{user.GetShownName ()} has shipped the following ships:```\n";

                foreach (Shipping.Ship ship in allShips)
                {
                    result += ParentPlugin.ShipToString(ship) + "\n";
                }
                result += "```";
                return(TaskResult(result, result));
            }
Esempio n. 15
0
        public static CommandMetadata CreateCommandMetadata(this BsonDocument doc)
        {
            var eventMetadata = new CommandMetadata()
            {
                CommandId   = doc.GetString("CommandId"),
                UserId      = doc.GetString("UserId"),
                CreatedDate = doc.GetDateTime("CreatedDate"),
                TypeName    = doc.GetString("TypeName")
            };

            return(eventMetadata);
        }
Esempio n. 16
0
            public Task <Result> Execute(CommandMetadata data)
            {
                var allKarma = ParentPlugin.GetLeaderboard();
                var allVotes = allKarma.SelectMany(x => x.GetMessages()).SelectMany(x => _voteSelector(x));
                var groups   = allVotes.GroupBy(x => x);
                var dict     = groups.ToDictionary(x => x.Key, x => allVotes.Count(y => x.Key == y));
                var users    = dict.Keys.ToArray();

                return(TaskResult(GetLeaderboardEmbed(users, (x, y) => dict[y] - dict[x], x => ParentPlugin.GuildHandler.FindUser(x),
                                                      x => dict[x].ToString() + " " + _voteType, $"No one has yet to be {_adjective}", $"{_type} Leaderboard", $"The most {_adjective} people on this server are..",
                                                      dict.Count), string.Empty));
            }
Esempio n. 17
0
 public Task <Result> Execute(CommandMetadata metadata, string pluginName)
 {
     ParentPlugin.AddPlugin(pluginName);
     if (ParentPlugin.GuildHandler.Plugins.IsPluginActive(pluginName))
     {
         return(TaskResult(null, $"Succesfully enabled plugin '{Plugin.GetFullName(PluginLoader.GetPlugin(pluginName))}' in this server."));
     }
     else
     {
         return(TaskResult(null, $"Failed to add plugin '{pluginName}'. An error may have occured in its initialization."));
     }
 }
Esempio n. 18
0
        public async Task <Result> Execute(CommandMetadata data, string word)
        {
            var def = await UrbanDefinition.Get(word, ParentPlugin.EnableHyperlinkReactions);

            Embed embed = def.ToEmbed();

            var message = await data.Message.Channel.SendMessageAsync(null, false, embed);

            await ParentPlugin.AddNestedDefReactions(def, message);

            return(new Result(null, string.Empty));
        }
Esempio n. 19
0
            public Task <Result> Execute(CommandMetadata data, SocketGuildUser user)
            {
                var           allShips = ParentPlugin.GetAllShipperShips(user);
                StringBuilder result   = new StringBuilder($"{user.GetShownName ()} has shipped the following ships:```\n");

                foreach (Shipping.Ship ship in allShips)
                {
                    result.Append(ParentPlugin.ShipToString(ship) + "\n");
                }
                result.Append("```");
                return(TaskResult(result, result.ToString()));
            }
Esempio n. 20
0
            public Task <Result> Execute(CommandMetadata _)
            {
                StringBuilder credits = new StringBuilder();

                credits.AppendLine("Bot core is created by Marcus \"Lomztein\" Jensen *(https://github.com/Lomztein)*, as a hobby passion project and passingly sentient slave.\n");
                credits.AppendLine("Additional council and help by the glorious Frederik \"Fred\" Rosenberg *(https://github.com/Frede175)*, the outrageously attractive Younes \"drcd\" Zakaria *(https://github.com/drcd)*, the suave servermaster Thorvald \"Purvaldur\" Kjartansson *(https://github.com/purvaldur)*, and the bona fide baguette Mph!");
                credits.AppendLine("Patience for listening to incomprehensible, overly excited ~~and mildly aroused~~ explanations of inner workings provided by the illustrious Victor \"Nyx\" Koch!\n");
                credits.AppendLine("Suffering and despair though testing the many awful versions Adminthulhu/Moduthulhu by my magnificant friends of Monster Mash!\n");
                credits.AppendLine("Thanks to the following for extending Moduthulhu by creating plugins: " + string.Join(", ", ParentPlugin.GuildHandler.Plugins.GetActivePlugins().Select(x => Plugin.GetAuthor(x.GetType())).Distinct()) + "!\n");
                credits.AppendLine("And thanks to you, for ~~unknowingly sacrifising yourself to my ever growing hunger~~ making use of my services :)");
                return(TaskResult(credits.ToString(), credits.ToString()));
            }
Esempio n. 21
0
            public Task <Result> Execute(CommandMetadata metadata, string pluginName)
            {
                Type pluginType = Plugin.Find(PluginLoader.GetPlugins(), pluginName);

                if (pluginType != null)
                {
                    return(TaskResult(GetModuleEmbed(pluginType), null));
                }
                else
                {
                    return(TaskResult(null, $"Failed to find any plugins matching '{pluginName}'"));
                }
            }
Esempio n. 22
0
        public Task <Result> Execute(CommandMetadata data, string user)
        {
            SocketGuildUser userObj = ParentPlugin.GuildHandler.FindUser(user);

            if (userObj != null)
            {
                return(Insult(ParentPlugin.GuildHandler.GetUser(user).GetShownName()));
            }
            else
            {
                return(Insult(user));
            }
        }
Esempio n. 23
0
        public static CommandRecord FromBson(BsonDocument doc)
        {
            var commandDocument = doc.GetBsonDocument("Command");

            var record = new CommandRecord
            {
                CommandDocument = commandDocument,
                Metadata        = CommandMetadata.FromBson(commandDocument.GetBsonDocument("Metadata")),
                Handlers        = CommandHandlerRecordCollection.FromBson(doc.GetBsonArray("Handlers"))
            };

            return(record);
        }
Esempio n. 24
0
 private void VerifyParametersWithMetadata(CommandMetadata metadata, string[] parameters)
 {
     if (parameters != null)
     {
         foreach (string text in parameters)
         {
             if (!metadata.Parameters.ContainsKey(text))
             {
                 base.WriteError(new ArgumentException(Strings.ParameterDoesNotExist(text)), ErrorCategory.InvalidData, this.DataObject.Id);
             }
         }
     }
 }
Esempio n. 25
0
            public Task <Result> Execute(CommandMetadata _)
            {
                int          shardIndex = 0;
                EmbedBuilder builder    = new EmbedBuilder()
                                          .WithTitle("Core Process Status")
                                          .WithAuthor(ParentPlugin.GuildHandler.BotUser)
                                          .WithDescription(ParentPlugin.GuildHandler.Core.ToString())
                                          .WithCurrentTimestamp();

                LargeEmbed embed = new LargeEmbed(builder, ParentPlugin.GuildHandler.Client.GetShardsStatus().Select(x => new EmbedFieldBuilder().WithName($"Shard {shardIndex++}").WithValue($"```{x}```")));

                return(TaskResult(embed, ""));
            }
Esempio n. 26
0
        /// <summary>
        /// Displays details of command usage for the specified <see cref="CommandMetadata"/>.
        /// </summary>
        /// <param name="commandMetadata">The <see cref="CommandMetadata"/> to display command usage
        /// for.</param>
        /// <exception cref="ArgumentNullException"><paramref name="commandMetadata"/> is
        /// <see langword="null"/>.</exception>
        public static void WriteCommandUsage(CommandMetadata commandMetadata)
        {
            ParameterValidation.IsNotNull(commandMetadata, nameof(commandMetadata));

            Console.WriteLine(string.Format(
                                  CultureInfo.InvariantCulture,
                                  Resources.CommandUsage,
                                  commandMetadata.Name,
                                  string.Join(" ", commandMetadata.ParametersMetadata
                                              .Select(m => m.Required ?
                                                      Invariant($"<{m.Name}>") :
                                                      Invariant($"[<{m.Name}>]")))));
        }
Esempio n. 27
0
        public Task <Result> Execute(CommandMetadata data, string user)
        {
            SocketGuildUser userObj = ParentPlugin.GuildHandler.FindUser(user);

            if (userObj != null)
            {
                return(Execute(data, ParentPlugin.GuildHandler.GetUser(user)));
            }
            else
            {
                return(TaskResult(null, ParentPlugin.SelectGenerator().Insult(user)));
            }
        }
Esempio n. 28
0
        public void New_ValidParameteresAreAssignedCorrectly()
        {
            // Arrange / Act
            var info = new CommandMetadata(
                "name",
                new DateTime(2021, 2, 2),
                "id");

            // Assert
            Assert.Equal("name", info.CommandName);
            Assert.Equal(new DateTime(2021, 2, 2), info.Timestamp);
            Assert.Equal("id", info.CorrelationId);
        }
    public Task AppendEvents(string streamName, CommandMetadata metadata, params object[] events)
    {
        if (!events.Any())
        {
            return(Task.CompletedTask);
        }

        var preparedEvents = events.Select(e => e.Serialize(
                                               Uuid.NewUuid(),
                                               EventMetadata.From(metadata)
                                               )).ToList();

        return(_client.AppendToStreamAsync(_tenantPrefix + streamName, StreamState.Any, preparedEvents));
    }
Esempio n. 30
0
            public Task <Result> Execute(CommandMetadata metadata)
            {
                LargeEmbed embed = new LargeEmbed();

                // TODO: Add status for shards and GuildHandlers.
                EmbedBuilder builder = new EmbedBuilder()
                                       .WithTitle("Core Process Status")
                                       .WithAuthor(ParentPlugin.GuildHandler.BotUser)
                                       .WithDescription(ParentPlugin.GuildHandler.Core.GetStatusString())
                                       .WithCurrentTimestamp();

                embed.CreateFrom(builder);
                return(TaskResult(embed, ""));
            }
            public Task <Result> Execute(CommandMetadata metadata, double value, string from)
            {
                Converter fromConverter = ParentPlugin.FindConverter(from);

                if (fromConverter != null)
                {
                    Converter toConverter = ParentPlugin.FindRandomOfType(fromConverter.Type, fromConverter);
                    return(Execute(metadata, value, from, toConverter.Name)); // don't question it.
                }
                else
                {
                    throw new InvalidOperationException("Cannot convert from unit type " + from);
                }
            }
        public void GetContext_NullContext_ReturnsNull()
        {
            // Arrange
            var metadata = new CommandMetadata(
                "command",
                new DateTime(2019, 1, 1),
                "id");

            // Act
            var result = metadata.GetContext <TestContext2>();

            // Assert
            Assert.Null(result);
        }
Esempio n. 33
0
        public void Storing_aggregate_should_preserve_values()
        {
            Guid aggregateId = Guid.NewGuid();
            Guid commandId = Guid.NewGuid();
            var commandMetadata = new CommandMetadata
                                      {
                                          CommandId = commandId,
                                          TargetType = typeof(TestAggregate),
                                          TargetId = aggregateId
                                      };
            _facade.Execute(commandMetadata, x => ((TestAggregate) x).TestMethod("Simon"));

            var restoredRoot = new TestAggregate(aggregateId);
             _repository.Load(restoredRoot, aggregateId, null);

            Assert.AreEqual("Simon", restoredRoot.HelloText);
        }