コード例 #1
0
        public async Task prefix([Remainder] string new_prefix)
        {
            SocketGuildUser GuildUser = Context.Guild.GetUser(Context.User.Id);

            if (GuildUser.GuildPermissions.Administrator || Global.DevUIDs.Contains(Context.Message.Author.Id))
            {
                MongoClient    mongoClient = new MongoClient(Global.Mongoconnstr);
                IMongoDatabase database    = mongoClient.GetDatabase("finlay");
                IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("guilds");
                ulong        _id           = Context.Guild.Id;
                BsonDocument guildDocument = await MongoHandler.FindById(collection, _id);

                if (guildDocument == null)
                {
                    MongoHandler.InsertGuild(_id);
                }

                BsonDocument guild = await collection.Find(Builders <BsonDocument> .Filter.Eq("_id", _id)).FirstOrDefaultAsync();

                if (guild == null)
                {
                    BsonDocument document = new BsonDocument {
                        { "_id", (decimal)_id }, { "prefix", new_prefix }
                    };
                    collection.InsertOne(document);
                    Global.UpdatePrefix(_id, new_prefix, await Global.DeterminePrefix(Context));
                }

                else
                {
                    collection.UpdateOne(Builders <BsonDocument> .Filter.Eq("_id", _id), Builders <BsonDocument> .Update.Set("prefix", new_prefix));
                    Global.UpdatePrefix(_id, new_prefix, await Global.DeterminePrefix(Context));
                }

                EmbedBuilder embed = new EmbedBuilder();
                embed.WithTitle("Prefix updated!");
                embed.WithDescription($"Set the prefix for this guild to: {new_prefix}");
                embed.WithColor(Color.Green);
                embed.WithAuthor(Context.Message.Author);
                embed.WithCurrentTimestamp();
                await Context.Message.ReplyAsync("", false, embed.Build());
            }

            else
            {
                await Context.Channel.TriggerTypingAsync();

                await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
                {
                    Color       = Color.LightOrange,
                    Title       = "You don't have Permission!",
                    Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command.",
                    Author      = new EmbedAuthorBuilder()
                    {
                        Name    = Context.Message.Author.ToString(),
                        IconUrl = Context.Message.Author.GetAvatarUrl() ?? Context.User.GetDefaultAvatarUrl(),
                        Url     = Context.Message.GetJumpUrl()
                    }
                }.Build());
            }
        }
コード例 #2
0
        public async Task EnableLevelling([Remainder] string toggle)
        {
            SocketGuildUser GuildUser = Context.Guild.GetUser(Context.User.Id);

            if (GuildUser.GuildPermissions.Administrator || Global.DevUIDs.Contains(Context.Message.Author.Id))
            {
                bool enabled = false;

                if (toggle == "true" || toggle == "on")
                {
                    enabled = true;
                }

                MongoClient    mongoClient = new MongoClient(Global.Mongoconnstr);
                IMongoDatabase database    = mongoClient.GetDatabase("finlay");
                IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("guilds");
                ulong        _id           = Context.Guild.Id;
                BsonDocument guildDocument = await MongoHandler.FindById(collection, _id);

                if (guildDocument == null)
                {
                    MongoHandler.InsertGuild(_id);
                }

                BsonDocument guild = await collection.Find(Builders <BsonDocument> .Filter.Eq("_id", _id)).FirstOrDefaultAsync();

                if (guild == null)
                {
                    BsonDocument document = new BsonDocument {
                        { "_id", (decimal)_id }, { "levelling", enabled }
                    };
                    collection.InsertOne(document);
                }

                else
                {
                    collection.UpdateOne(Builders <BsonDocument> .Filter.Eq("_id", _id), Builders <BsonDocument> .Update.Set("levelling", enabled));
                }

                EmbedBuilder embed = new EmbedBuilder();
                embed.WithTitle("Success");
                embed.WithDescription($"Successfully set levelling to {enabled}!");
                embed.WithColor(Color.Green);
                embed.WithAuthor(Context.Message.Author);
                embed.WithCurrentTimestamp();
                await Context.Message.ReplyAsync("", false, embed.Build());
            }

            else
            {
                await Context.Channel.TriggerTypingAsync();

                await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
                {
                    Color       = Color.LightOrange,
                    Title       = "You don't have Permission!",
                    Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command.",
                    Footer      = new EmbedFooterBuilder()
                    {
                        IconUrl = Context.User.GetAvatarUrl() ?? Context.User.GetDefaultAvatarUrl(),
                        Text    = $"{Context.User}"
                    },
                }.WithCurrentTimestamp().Build());
            }
        }
コード例 #3
0
 public static UpdateResult Update <T>(this IMongoCollection <T> collection, T entity, params Expression <Func <T, object> >[] fields)
 {
     return(collection.UpdateOne(Builders <T> .Filter.Eq(IdName, entity.ToBsonDocument()[IdName]), UpdateHelper.GetUpdater(entity, fields)));
 }
コード例 #4
0
ファイル: MongoTest.cs プロジェクト: RominYue/code_snippets
        static void Update(IMongoCollection<BsonDocument> col)
        {
            var filter = Builders<BsonDocument>.Filter.Lt("score", 100);
            var update = Builders<BsonDocument>.Update.Inc("score", 100);
            var result = col.UpdateOne(filter, update);
            //var result = col.UpdateMany(filter, update);
            if (result.IsModifiedCountAvailable)
            {
                Console.WriteLine(result.ModifiedCount);
            }

            //替换 replacing
            var result_replace = col.ReplaceOne(filter, new BsonDocument("name","yomin"));
        }
コード例 #5
0
        public void Update(string username, int balance)
        {
            var updateDef = Builders <Customer> .Update.Set("balance", balance);

            _customers.UpdateOne(customer => customer.username == username, updateDef);
        }
コード例 #6
0
        public bool UpdateOne <TField>(FilterDefinition <TEntity> filter, Expression <Func <TEntity, TField> > field, TField value, string partitionKey = null)
        {
            var updateRes = _db.UpdateOne(filter, Builders <TEntity> .Update.Set(field, value));

            return(updateRes.ModifiedCount == 1);
        }
コード例 #7
0
 public void Update(string id, string epicid)
 {
     _workspace.UpdateOne(
         project => project.ProjectId == id,
         Builders <WorkSpace> .Update.Push <string>(project => project.epics, epicid));
 }
コード例 #8
0
        public ActionResult AtalizarInfectado([FromBody] InfectadoDto dto)
        {
            _infectadosCollection.UpdateOne(Builders <Infectado> .Filter.Where(_ => _.DataNascimento == dto.DataNascimento), Builders <Infectado> .Update.Set("sexo", dto.Sexo));

            return(Ok("Atualização feita com sucesso!"));
        }
コード例 #9
0
        public override void OnLogAdded(Test test, Log log)
        {
            var document = new BsonDocument
            {
                { "test", test.ObjectId },
                { "project", _projectId },
                { "report", _reportId },
                { "testName", test.Name },
                { "sequence", log.Sequence },
                { "status", log.Status.ToString().ToLower() },
                { "timestamp", log.Timestamp },
                { "details", log.Details }
            };

            _logCollection.InsertOne(document);

            if (test.HasException())
            {
                if (_exceptionNameObjectIdCollection == null)
                {
                    _exceptionNameObjectIdCollection = new Dictionary <string, ObjectId>();
                }

                var ex = test.ExceptionInfo;

                document = new BsonDocument
                {
                    { "report", _reportId },
                    { "project", _projectId },
                    { "name", ex.Name }
                };

                var findResult = _exceptionCollection.Find(document).FirstOrDefault();

                if (!_exceptionNameObjectIdCollection.ContainsKey(ex.Name))
                {
                    if (findResult != null)
                    {
                        _exceptionNameObjectIdCollection.Add(ex.Name, findResult["_id"].AsObjectId);
                    }
                    else
                    {
                        document = new BsonDocument
                        {
                            { "project", _projectId },
                            { "report", _reportId },
                            { "name", ex.Name },
                            { "stacktrace", ex.StackTrace },
                            { "testCount", 0 }
                        };

                        _exceptionCollection.InsertOne(document);

                        var exId = document["_id"].AsObjectId;

                        document = new BsonDocument
                        {
                            { "_id", exId }
                        };
                        findResult = _exceptionCollection.Find(document).FirstOrDefault();

                        _exceptionNameObjectIdCollection.Add(ex.Name, exId);
                    }
                }

                var testCount = ((int)(findResult["testCount"])) + 1;
                var filter    = Builders <BsonDocument> .Filter.Eq("_id", findResult["_id"].AsObjectId);

                var update = Builders <BsonDocument> .Update.Set("testCount", testCount);

                _exceptionCollection.UpdateOne(filter, update);
            }

            EndTestRecursive(test);
        }
コード例 #10
0
 public virtual void Update(FilterDefinition <TEntity> filter, UpdateDefinition <TEntity> update, UpdateOptions options)
 {
     Collection.UpdateOne(filter, update, options);
 }
コード例 #11
0
        public ActionResult AtualizarPesoCobra([FromBody] CobraDto dto)
        {
            _cobraCollection.UpdateOne(Builders <Cobra> .Filter.Where(_ => _.nome == dto.nome), Builders <Cobra> .Update.Set("peso", dto.peso));

            return(StatusCode(201, "Peso de " + dto.nome + " atualizado com sucesso"));
        }
コード例 #12
0
        public async Task UpdateOneTheaterAsync()
        {
            /*
             * Let's begin by looking at the methods available to us
             * if we want to update one or more records in MongoDB. We have
             * synchronous and asynchronous methods for UpdateOne, UpdateMany,
             * and FindOneAndUpdate.
             * The name of each method should provide a good hint as to its
             * purpose. UpdateOne updates a single document, while UpdateMany
             * updates all of the documents that match the filter. Both
             * methods return an UpdateResult object, while the FindOneAndUpdate
             * method updates a single document and returns the updated document.
             *
             * Let's suppose that one of the movie theaters in our database has
             * moved, so we need to change the address we have on record. This
             * is a obvious case for using UpdateOne or FindOneAndUpdate, so let's
             * look at both of those. First, we create the filter to find the
             * specific theater we need to update:
             */

            var filter = Builders <Theater> .Filter.Eq(t => t.TheaterId, 8);

            /*
             * Now let's call Find just to make sure we're finding the correct
             * document:
             */

            var theater = await _theatersCollection.Find <Theater>(filter).FirstOrDefaultAsync();

            Assert.AreEqual(theater.TheaterId, 8);
            Assert.AreEqual("14141 Aldrich Ave S", theater.Location.Address.Street1);

            /* We don't need to call Find before doing an update; this is just
             * to ensure that we've built our filter correctly. Instead,
             * we can call UpdateOne or FindOneAndUpdate to change the address
             * of the theater. The UpdateDefinition uses the $set command to
             * change just the "location.address.street1" field in the document.
             */

            var updateResult = _theatersCollection.UpdateOne(filter,
                                                             new BsonDocument("$set",
                                                                              new BsonDocument("location.address.street1", "123 Main St."))
                                                             );

            Assert.AreEqual(1, updateResult.MatchedCount);
            Assert.AreEqual(1, updateResult.ModifiedCount);

            /* Note: this can also be written using the Builders class, which
             * helps ensure we are using the correct the field name:
             */

            _theatersCollection.UpdateOne(filter,
                                          Builders <Theater> .Update.Set(t => t.Location.Address.Street1,
                                                                         "123 Main St.")
                                          );


            /* Finally, if you want to do something with the updated document, you
             * can use the FindOneAndUpdate method:
             */

            var updatedDoc = await _theatersCollection.FindOneAndUpdateAsync <Theater>(
                filter,
                Builders <Theater> .Update.Set(
                    t => t.Location.Address.Street1,
                    "123 Main St.")
                );

            Assert.AreEqual("123 Main St.", updatedDoc.Location.Address.Street1);
        }
コード例 #13
0
ファイル: DataCollectors.cs プロジェクト: lulzzz/cbs
 public UpdateResult Update(FilterDefinition <DataCollector> filter, UpdateDefinition <DataCollector> update)
 {
     return(_collection.UpdateOne(filter, update));
 }
コード例 #14
0
        public async Task NotifyTwitch(string user)
        {
            SocketGuildUser GuildUser = Context.Guild.GetUser(Context.User.Id);

            if (GuildUser.GuildPermissions.ManageMessages || Global.DevUIDs.Contains(Context.Message.Author.Id))
            {
                List <TwitchHandler.TwitchData> ValidateUser = await TwitchHandler.GetTwitchInfo(user);

                if (ValidateUser.Count == 0)
                {
                    await Context.Message.ReplyAsync("", false, Global.EmbedMessage("Error", $"The user {user} could not be found on Twitch.", false, Color.Red).Build());

                    return;
                }

                MongoClient    mongoClient = new MongoClient(Global.Mongoconnstr);
                IMongoDatabase database    = mongoClient.GetDatabase("finlay");
                IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("guilds");
                ulong        _id           = Context.Guild.Id;
                BsonDocument guildDocument = await MongoHandler.FindById(collection, _id);

                if (guildDocument == null)
                {
                    MongoHandler.InsertGuild(_id);
                }

                BsonDocument guild = await collection.Find(Builders <BsonDocument> .Filter.Eq("_id", _id)).FirstOrDefaultAsync();

                try
                {
                    string        itemVal     = guild?.GetValue("TwitchUsers").ToJson();
                    List <string> stringArray = JsonConvert.DeserializeObject <string[]>(itemVal).ToList();
                    Regex         re          = new Regex(@"\b(" + string.Join("|", stringArray.Select(word => string.Join(@"\s*", word.ToCharArray()))) + @")\b", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

                    if (re.IsMatch(user))
                    {
                        EmbedBuilder errembed = new EmbedBuilder();
                        errembed.WithTitle("Error");
                        errembed.WithDescription("This user is already included in the notification list!");
                        errembed.WithColor(Color.Red);
                        errembed.WithAuthor(Context.Message.Author);
                        await Context.Message.ReplyAsync("", false, errembed.Build());

                        return;
                    }
                }

                catch { }

                if (guild == null)
                {
                    BsonDocument document = new BsonDocument {
                        { "_id", (decimal)_id }, { "TwitchUsers", user }
                    };
                    collection.InsertOne(document);
                }

                else
                {
                    collection.UpdateOne(Builders <BsonDocument> .Filter.Eq("_id", _id), Builders <BsonDocument> .Update.Push("TwitchUsers", user));
                }

                EmbedBuilder embed = new EmbedBuilder();
                embed.WithTitle("Twitch notification user list updated!");
                embed.WithDescription($"Successfully added notifications for when {user} goes live on Twitch!");
                embed.WithColor(Color.Green);
                embed.WithAuthor(Context.Message.Author);
                embed.WithCurrentTimestamp();
                await Context.Message.Channel.SendMessageAsync("", false, embed.Build());
            }

            else
            {
                await Context.Channel.TriggerTypingAsync();

                await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
                {
                    Color       = Color.LightOrange,
                    Title       = "You don't have Permission!",
                    Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command.",
                    Footer      = new EmbedFooterBuilder()
                    {
                        IconUrl = Context.User.GetAvatarUrl() ?? Context.User.GetDefaultAvatarUrl(),
                        Text    = $"{Context.User}"
                    },
                }.WithCurrentTimestamp().Build());
            }
        }
 public IActionResult AtualizarInfectado([FromBody] InfectadoViewModel infectadoViewModel)
 {
     _colletionsInfectados.UpdateOne(Builders <Infectados> .Filter.Where(i => i.DataNascimento == infectadoViewModel.DataNascimento), Builders <Infectados> .Update.Set("sexo", infectadoViewModel));
     return(Ok("Atualizado com sucesso"));
 }
コード例 #16
0
        public async Task SetWelcomeChannel([Remainder] SocketChannel channel)
        {
            SocketGuildUser GuildUser = Context.Guild.GetUser(Context.User.Id);

            if (GuildUser.GuildPermissions.ManageChannels || Global.DevUIDs.Contains(Context.Message.Author.Id))
            {
                if (channel.GetType() == typeof(SocketVoiceChannel))
                {
                    EmbedBuilder eb = new EmbedBuilder();
                    eb.WithTitle("Error setting welcome channel");
                    eb.WithDescription($"The welcome channel type must be a text channel!");
                    eb.WithColor(Color.Red);
                    eb.WithAuthor(Context.Message.Author);
                    eb.WithCurrentTimestamp();
                    await Context.Message.ReplyAsync("", false, eb.Build());

                    return;
                }

                MongoClient    mongoClient = new MongoClient(Global.Mongoconnstr);
                IMongoDatabase database    = mongoClient.GetDatabase("finlay");
                IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("guilds");
                ulong        _id           = Context.Guild.Id;
                BsonDocument guildDocument = await MongoHandler.FindById(collection, _id);

                if (guildDocument == null)
                {
                    MongoHandler.InsertGuild(_id);
                }

                BsonDocument guild = await collection.Find(Builders <BsonDocument> .Filter.Eq("_id", _id)).FirstOrDefaultAsync();

                ulong _chanId = channel.Id;

                if (guild == null)
                {
                    BsonDocument document = new BsonDocument {
                        { "_id", (decimal)_id }, { "welcomechannel", (decimal)_chanId }
                    };
                    collection.InsertOne(document);
                }

                else
                {
                    collection.UpdateOne(Builders <BsonDocument> .Filter.Eq("_id", _id), Builders <BsonDocument> .Update.Set("welcomechannel", _chanId));
                }

                EmbedBuilder embed = new EmbedBuilder();
                embed.WithTitle("Success");
                embed.WithDescription($"Successfully set the welcome channel to <#{_chanId}>!");
                embed.WithColor(Color.Green);
                embed.WithAuthor(Context.Message.Author);
                embed.WithCurrentTimestamp();
                await Context.Message.ReplyAsync("", false, embed.Build());
            }

            else
            {
                await Context.Channel.TriggerTypingAsync();

                await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
                {
                    Color       = Color.LightOrange,
                    Title       = "You don't have Permission!",
                    Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command.",
                    Author      = new EmbedAuthorBuilder()
                    {
                        Name    = Context.Message.Author.ToString(),
                        IconUrl = Context.Message.Author.GetAvatarUrl() ?? Context.User.GetDefaultAvatarUrl(),
                        Url     = Context.Message.GetJumpUrl()
                    }
                }.Build());
            }
        }
コード例 #17
0
        public ActionResult AtualizarInfectado(Guid id, [FromBody] InfectadoDto dto)
        {
            _infectadosCollection.UpdateOne(Builders <Infectado> .Filter.Where(_ => _.Id == id), Builders <Infectado> .Update.Set("sexo", dto.Sexo).Set("dataNascimento", dto.DataNascimento).Set("localizacao.0", dto.Longitude).Set("localizacao.1", dto.Latitude));

            return(Ok("Infectado atualizado com sucesso"));
        }
コード例 #18
0
        public ActionResult AtualizarInfectado([FromBody] InfectadoDto dto)
        {
            _infectadosCollection.UpdateOne(Builders <Infectado> .Filter.Where(_ => _.Cpf == dto.Cpf), Builders <Infectado> .Update.Set("sexo", dto.Sexo));

            return(Ok("Atualizado com sucesso!"));
        }
コード例 #19
0
        //TODO: fix and uncomment
        ///// <summary>
        ///// Returns a IMongoCollection decorated with RetryingInterceptor in case of exception, if will retry the operation specified times with pause of specified ms.
        ///// </summary>
        ///// <typeparam name="TDocument"></typeparam>
        ///// <param name="db"></param>
        ///// <param name="collectionName"></param>
        ///// <param name="retryCount"></param>
        ///// <param name="pauseBetweenRetries"></param>
        ///// <returns></returns>
        //public static IMongoCollection<TDocument> GetRetryCollection<TDocument>(this IMongoDatabase db, string collectionName = null, int retryCount = 5, int pauseBetweenRetries = 2000)
        //{
        //    var t = typeof(TDocument).Name;
        //    if (collectionName == null) collectionName = t;
        //    var key = string.Concat(db.DatabaseNamespace.DatabaseName, collectionName, t);
        //    return (IMongoCollection<TDocument>)cache.GetOrAdd(key, k =>
        //    {
        //        var coll = db.GetCollection<TDocument>(collectionName);
        //        return (IMongoCollection<TDocument>)ProxyGenerator.CreateClassProxyWithTarget(coll.GetType(), coll, new object[] { db, collectionName, coll.Settings },
        //            new RetryingInterceptor { RetryCount = retryCount, PauseBetweenCalls = pauseBetweenRetries });
        //    });
        //}
        //public static IMongoCollection<TDocument> GetRetryCollection<TColectionName, TDocument>(this IMongoDatabase db)
        //{
        //    var collectionName = typeof(TColectionName).Name;
        //    return GetRetryCollection<TDocument>(db, collectionName);
        //}

        public static UpdateResult UpdateById <T>(this IMongoCollection <T> collection, BsonValue id, Func <UpdateDefinitionBuilder <T>, UpdateDefinition <T> > update, UpdateOptions options = null)
        {
            return(collection.UpdateOne(FilterId <T>(id), update(new UpdateDefinitionBuilder <T>()), options ?? new UpdateOptions()));
        }
コード例 #20
0
 public void Remove(string id)
 {
     _mongoCollection.UpdateOne(Builders <People> .Filter.Eq("_id", ObjectId.Parse(id)),
                                Builders <People> .Update.Set("Excluded", true));
 }
コード例 #21
0
 public bool UpdateCategories(IEnumerable <Category> categories)
 {
     return(categories.All(category => _collection.UpdateOne(c => c.Id == category.Id,
                                                             Builders <Category> .Update.Set(c => c.Name, category.Name)
                                                             .Set(c => c.Order, category.Order)).MatchedCount == 1));
 }