public IActionResult TestCase5(int lower, int upper)
        {
            MongoHandler mongohandler = new MongoHandler();
            var          product      = mongohandler.GetProductById(lower, upper);

            return(Ok(product));
        }
        public IActionResult TestCase6(int lower, int upper)
        {
            MongoHandler mongohandler = new MongoHandler();
            var          product      = mongohandler.GetProductJoinProductTypeAndCompanyById(lower, upper);

            return(Ok(product));
        }
        public Product TestCase9Mongo(int id)
        {
            MongoHandler mongohandler = new MongoHandler();
            var          product      = mongohandler.GetProductJoinProductTypeAndCompanyById(id);

            return(product);
        }
        public IActionResult TestCase3(int id)
        {
            MongoHandler mongohandler = new MongoHandler();
            var          product      = mongohandler.GetProductJoinProductTypeAndCompanyById(id);

            return(Ok(product));
        }
        public void MongoHandlerInitiallizer()
        {
            DatabaseInfo info = TestingConsts.DB_INFO;

            mongoHandler = new MongoHandler(info);
            mongoHandler.DeleteDatabase(mongoHandler.DbInfo.DatabaseName); // in case db wasn't cleard previous run
        }
        public List <Product> TestCase6Mongo(int lower, int upper)
        {
            MongoHandler mongohandler = new MongoHandler();
            var          product      = mongohandler.GetProductJoinProductTypeAndCompanyById(lower, upper);

            return(product);
        }
        public Product TestCase8Mongo(int id)
        {
            MongoHandler mongohandler = new MongoHandler();
            var          product      = mongohandler.GetProductById(id);

            return(product);
        }
        public List <Product> TestCase5Mongo(int lower, int upper)
        {
            MongoHandler mongohandler = new MongoHandler();
            var          product      = mongohandler.GetProductById(lower, upper);

            return(product);
        }
        public IActionResult TestCase8(int id)
        {
            MongoHandler mongohandler = new MongoHandler();
            var          product      = mongohandler.GetProductById(id);

            return(Ok(product));
        }
예제 #10
0
        public async Task Getguilddata(params string[] inputOptions)
        {
            if (Global.IsDev(Context.User))
            {
                if (inputOptions.Length == 0)
                {
                    MongoClient    mongoClient = new MongoClient(Global.Mongoconnstr);
                    IMongoDatabase database    = mongoClient.GetDatabase("finlay");
                    IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("guilds");
                    ulong _id = Context.Guild.Id;

                    try
                    {
                        BsonDocument data = await MongoHandler.FindById(collection, _id);

                        if (data != null)
                        {
                            await ReplyAsync(data.ToString());
                        }

                        else
                        {
                            await ReplyAsync("Guild config data is null.");
                        }
                    }

                    catch (KeyNotFoundException)
                    {
                        await ReplyAsync("No data was found for guild data.");
                    }
                }

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

                    string results = "";

                    for (int i = 0; i < inputOptions.Length; i++)
                    {
                        try
                        {
                            results += $"{data.GetElement(inputOptions[i])}\n\n";
                        }

                        catch (KeyNotFoundException)
                        {
                            results += $"No data found for {inputOptions[i]}.\n\n";
                        }
                    }

                    await ReplyAsync(results);
                }
            }
        }
예제 #11
0
        public static Disciplinas GetAllClassesInfo()
        {
            string classUrl = "https://siga.ufrj.br/sira/gradeHoraria/{0}";

            Disciplinas response = new Disciplinas
            {
                Cursos = new Dictionary <string, Dictionary <string, List <Disciplina> > >()
            };

            foreach (string cursos in Courses.Keys)
            {
                string formatedUrl = string.Format(classUrl, Courses[cursos]);

                Result storedData = MongoHandler.IsOnMongo(cursos);
                if (storedData != null)
                {
                    response.Cursos.Add(cursos, storedData.Disciplinas);
                    continue;
                }

                HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(formatedUrl);

                webReq.KeepAlive              = true;
                webReq.UserAgent              = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36";
                webReq.Accept                 = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
                webReq.ContentType            = "text/html";
                webReq.Host                   = "siga.ufrj.br";
                webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                webReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
                webReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7");

                string htmlResponse = String.Empty;

                HttpWebResponse htmlContent = (HttpWebResponse)webReq.GetResponse();

                using (StreamReader reader = new StreamReader(htmlContent.GetResponseStream(), Encoding.GetEncoding("iso-8859-1")))
                {
                    htmlResponse = reader.ReadToEnd();
                }

                htmlResponse = HttpUtility.HtmlDecode(htmlResponse);

                if (String.IsNullOrWhiteSpace(htmlResponse))
                {
                    response.Erro = "Não foi possível obter as disciplinas. Tente novamente!";
                    return(response);
                }

                ParseCourseInfo(htmlResponse, ref response, cursos);
            }

            if (response.Cursos.Count == 0)
            {
                response.Erro = "Curso não implementado.";
            }

            return(response);
        }
        public void Should_CreateCardBasedOnWord_When_DatabaseIsValid()
        {
            MongoHandler mongoHandler = new MongoHandler(TestingConsts.DB_INFO);
            CardDocument document     = CardDocument.CreateBasedOnWordAsync(mongoHandler, "Test").Result;

            Assert.IsNotNull(document);
            mongoHandler.DeleteDatabase(mongoHandler.DbInfo.DatabaseName);
        }
예제 #13
0
파일: B0Handler.cs 프로젝트: tom6886/DQGJK
        public void Handle()
        {
            MongoHandler.Save(new B0C0Data(_Message));

            UpdateCabinet(_Message);

            UpdateOperate(_Message, "B0");
        }
예제 #14
0
        private void LoadConfig()
        {
            string login      = ConfigurationManager.AppSettings["login"];
            string password   = ConfigurationManager.AppSettings["password"];
            string host       = ConfigurationManager.AppSettings["host"];
            string database   = ConfigurationManager.AppSettings["database"];
            string collection = ConfigurationManager.AppSettings["collection"];

            MongoHandler.StartOnMongo(login, password, host, database, collection);
            MongoHandler.ConnectToMongo();
        }
        public void Should_ThrowArgumentNullException_When_DatabaseIsInvalid()
        {
            MongoHandler mongoHandler = null;

            try
            {
                CardDocument document = CardDocument.CreateBasedOnWordAsync(mongoHandler, "Test").Result;
            } catch (AggregateException e) {
                throw e.InnerException;
            }
        }
예제 #16
0
파일: Statistic.cs 프로젝트: tom6886/DQGJK
        private List <BsonDocument> GetAlarmStat(string sDate, string sNDate)
        {
            var stages = new List <IPipelineStageDefinition>();

            //根据日期筛选出数据
            stages.Add(new JsonPipelineStageDefinition <BsonDocument, BsonDocument>("{$match:{IsChecked:true,SendTime:{$gte:new Date(\"" + sDate + "\"),$lte:new Date(\"" + sNDate + "\")}}}"));
            //拆分嵌套文件
            stages.Add(new JsonPipelineStageDefinition <BsonDocument, BsonDocument>("{$unwind:\"$Data\"}"));
            //统计数据
            stages.Add(new JsonPipelineStageDefinition <BsonDocument, BsonDocument>("{$group:{ _id:{Client:\"$ClientCode\",Device:\"$Data.Code\"},HumAlarm:{$sum:\"$Data.State.HumidityAlarm\"},TemAlarm:{$sum:\"$Data.State.TemperatureAlarm\"}}}"));

            var pipeline = new PipelineStagePipelineDefinition <BsonDocument, BsonDocument>(stages);

            return(MongoHandler.GetBsonCollection <B0C0Data>().AggregateAsync(pipeline).Result.ToList());
        }
예제 #17
0
파일: Statistic.cs 프로젝트: tom6886/DQGJK
        private List <BsonDocument> GetMaxMinAvgStat(string sDate, string sNDate)
        {
            var stages = new List <IPipelineStageDefinition>();

            //根据日期筛选出数据
            stages.Add(new JsonPipelineStageDefinition <BsonDocument, BsonDocument>("{$match:{IsChecked:true,SendTime:{$gte:new Date(\"" + sDate + "\"),$lte:new Date(\"" + sNDate + "\")}}}"));
            //拆分嵌套文件
            stages.Add(new JsonPipelineStageDefinition <BsonDocument, BsonDocument>("{$unwind:\"$Data\"}"));
            //过滤无效数据
            stages.Add(new JsonPipelineStageDefinition <BsonDocument, BsonDocument>("{$match:{\"Data.Valid\":true}}"));
            //统计数据
            stages.Add(new JsonPipelineStageDefinition <BsonDocument, BsonDocument>("{$group:{ _id:{Client:\"$ClientCode\",Device:\"$Data.Code\"},maxHum:{$max:\"$Data.Humidity\"},minHum:{$min:\"$Data.Humidity\"},avgHum:{ $avg:\"$Data.Humidity\"},maxTem:{$max:\"$Data.Temperature\"},minTem:{$min:\"$Data.Temperature\"},avgTem:{$avg:\"$Data.Temperature\"}}}"));

            var pipeline = new PipelineStagePipelineDefinition <BsonDocument, BsonDocument>(stages);

            return(MongoHandler.GetBsonCollection <B0C0Data>().AggregateAsync(pipeline).Result.ToList());
        }
        public async void OnGetExcellFromZip(object sender, RoutedEventArgs e)
        {
            ZipReader.ZipReader.Read("../../../tables.zip");
            var db = new TuxedoDb();

            using (db)
            {
                SeedXcelToDb.SeedBrands("Brand", db);
                SeedXcelToDb.SeedColors("Color", db);
                SeedXcelToDb.SeedCountries("Countries", db);
                SeedXcelToDb.SeedMaterials("Materials", db);
                SeedXcelToDb.SeedTypes("Types", db);
                SeedXcelToDb.SeedItems("Items", db);
            }

            Console.WriteLine(DataTransfered, "Excell");

            var mongo = new MongoHandler("TuxedoDB");
            await mongo.TransferToMSSQL();

            Console.WriteLine("Data from MongoDb Imported!");
        }
예제 #19
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());
            }
        }
예제 #20
0
        private static void ParseCourseInfo(string htmlResponse, ref Disciplinas resposta, string curso)
        {
            HtmlDocument htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(htmlResponse);

            Dictionary <string, List <Disciplina> > response = new Dictionary <string, List <Disciplina> >();

            HtmlNodeCollection numberPeriodosNode = htmlDoc.DocumentNode.SelectNodes("//*[@class='tableTitle']");

            List <string> periods = new List <string>();

            if (numberPeriodosNode != null)
            {
                foreach (HtmlNode node in numberPeriodosNode)
                {
                    string   texto         = Remover.ReplaceMultipleSpacesByPipe(Remover.RemoveSeparators(node.InnerText));
                    string[] splittedTexto = texto.Split('|');
                    if (splittedTexto.Length == 3)
                    {
                        if (splittedTexto[1].Length == 10)
                        {
                            periods.Add(splittedTexto[1]);
                        }
                        if (splittedTexto[1].Length == 11)
                        {
                            periods.Add(splittedTexto[1]);
                        }
                    }
                }
            }

            HtmlNodeCollection periodosNode = htmlDoc.DocumentNode.SelectNodes("//*[@class='table'][1]//table//table//tr");

            if (periodosNode != null)
            {
                List <Disciplina> disciplinas = new List <Disciplina>();
                Disciplina        disciplina  = new Disciplina();
                List <Dia>        dias        = new List <Dia>();
                Dia dia     = new Dia();
                int periodo = 0;
                foreach (HtmlNode node in periodosNode)
                {
                    string texto = Remover.ReplaceMultipleSpacesByPipe(Remover.RemoveSeparators(node.InnerText));

                    if (texto.Contains("Professor"))
                    {
                        if (!String.IsNullOrWhiteSpace(disciplina.Código))
                        {
                            disciplina.Dias = dias;
                            disciplinas.Add(disciplina);

                            response.Add(periods[periodo], disciplinas);

                            periodo++;
                            dias        = new List <Dia>();
                            disciplina  = new Disciplina();
                            disciplinas = new List <Disciplina>();
                        }
                        continue;
                    }
                    string[] splittedText = texto.Split('|');

                    if (String.IsNullOrWhiteSpace(splittedText[1]) && dias.Count != 0)
                    {
                        dia = new Dia
                        {
                            DiaDaSemana = splittedText[4],
                            Horário     = splittedText[5]
                        };

                        if (!String.IsNullOrWhiteSpace(splittedText[6]))
                        {
                            dia.SegundoProfessor = splittedText[6];
                        }
                        dias.Add(dia);
                        dia = new Dia();
                    }

                    if (!String.IsNullOrWhiteSpace(splittedText[1]) && dias.Count != 0)
                    {
                        disciplina.Dias = dias;
                        dias            = new List <Dia>();

                        disciplinas.Add(disciplina);
                        disciplina = new Disciplina();
                    }

                    if (splittedText.Length == 8 && !String.IsNullOrWhiteSpace(splittedText[1]))
                    {
                        disciplina.Código    = splittedText[1];
                        disciplina.Número    = splittedText[2];
                        disciplina.Nome      = splittedText[3];
                        disciplina.Professor = splittedText[6];

                        dia.DiaDaSemana = splittedText[4];
                        dia.Horário     = splittedText[5];

                        dias.Add(dia);
                        dia = new Dia();
                        continue;
                    }
                    if (splittedText.Length == 9 && !String.IsNullOrWhiteSpace(splittedText[1]))
                    {
                        disciplina.Código    = splittedText[1];
                        disciplina.Número    = splittedText[2];
                        disciplina.Nome      = splittedText[3] + " " + splittedText[4];
                        disciplina.Professor = splittedText[7];

                        dia.DiaDaSemana = splittedText[5];
                        dia.Horário     = splittedText[6];

                        dias.Add(dia);
                        dia = new Dia();
                        continue;
                    }
                }

                if (dias.Count != 0)
                {
                    disciplina.Dias = dias;
                    disciplinas.Add(disciplina);
                    response.Add(periods[periodo], disciplinas);
                }
            }

            HtmlNodeCollection ComplementaresNode = htmlDoc.DocumentNode.SelectNodes("//*[@class='table'][2]//table//table//tr");

            if (ComplementaresNode != null)
            {
                List <Disciplina> disciplinas = new List <Disciplina>();
                Disciplina        disciplina  = new Disciplina();
                List <Dia>        dias        = new List <Dia>();
                Dia dia = new Dia();

                foreach (HtmlNode node in ComplementaresNode)
                {
                    string texto = Remover.ReplaceMultipleSpacesByPipe(Remover.RemoveSeparators(node.InnerText));

                    if (texto.Contains("Professor"))
                    {
                        continue;
                    }
                    string[] splittedText = texto.Split('|');

                    if (String.IsNullOrWhiteSpace(splittedText[1]) && dias.Count != 0)
                    {
                        dia = new Dia
                        {
                            DiaDaSemana = splittedText[4],
                            Horário     = splittedText[5]
                        };

                        if (!String.IsNullOrWhiteSpace(splittedText[6]))
                        {
                            dia.SegundoProfessor = splittedText[6];
                        }
                        dias.Add(dia);
                        dia = new Dia();
                    }

                    if (!String.IsNullOrWhiteSpace(splittedText[1]) && dias.Count != 0)
                    {
                        disciplina.Dias = dias;
                        dias            = new List <Dia>();

                        disciplinas.Add(disciplina);
                        disciplina = new Disciplina();
                    }

                    if (splittedText.Length == 8 && !String.IsNullOrWhiteSpace(splittedText[1]))
                    {
                        disciplina.Código    = splittedText[1];
                        disciplina.Número    = splittedText[2];
                        disciplina.Nome      = splittedText[3];
                        disciplina.Professor = splittedText[6];

                        dia.DiaDaSemana = splittedText[4];
                        dia.Horário     = splittedText[5];

                        dias.Add(dia);
                        dia = new Dia();
                        continue;
                    }
                    if (splittedText.Length == 9 && !String.IsNullOrWhiteSpace(splittedText[1]))
                    {
                        disciplina.Código    = splittedText[1];
                        disciplina.Número    = splittedText[2];
                        disciplina.Nome      = splittedText[3] + " " + splittedText[4];
                        disciplina.Professor = splittedText[7];

                        dia.DiaDaSemana = splittedText[5];
                        dia.Horário     = splittedText[6];

                        dias.Add(dia);
                        dia = new Dia();
                        continue;
                    }
                }

                if (dias.Count != 0)
                {
                    disciplina.Dias = dias;
                    disciplinas.Add(disciplina);
                }

                response.Add("Complementares", disciplinas);
            }

            resposta.Cursos.Add(curso, response);
            Result data = new Result
            {
                Curso       = curso,
                Disciplinas = response
            };

            MongoHandler.SaveOnMongo(data);
        }
예제 #21
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());
            }
        }
예제 #22
0
        public async Task SetAFK([Remainder] string status)
        {
            if (string.IsNullOrEmpty(status))
            {
                await Context.Message.ReplyAsync("", false, Global.EmbedMessage("Error", "Please enter a valid AFK status.", 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();

            if (guild == null)
            {
                //BsonDocument statusDocument = new BsonDocument { { "_id", (decimal)_id }, { "AFKUsers", new BsonArray { new BsonDocument { { Context.Message.Author.Id.ToString(), status } } } } };
                BsonDocument statusDocument = new BsonDocument {
                    { "_id", (decimal)_id }, { "AFKUsers", /*new BsonArray {*/ new BsonDocument {
                                                   { Context.Message.Author.Id.ToString(), status }
                                               } }                                                                                                                                                  /*} */
                };
                collection.InsertOne(statusDocument);
            }

            else
            {
                BsonDocument test = new BsonDocument {
                    { "$push", new BsonDocument {
                          { "AFKUsers", new BsonDocument {
                                                                   { Context.Message.Author.Id.ToString(), status }
                                                               } }
                      } }
                };
                BsonDocument testing = new BsonDocument {
                    { "_id", (decimal)_id }
                };
                collection.UpdateOne(testing, test);
            }

            await Context.Message.ReplyAsync($"Successfully set AFK status to: {status}");

            try
            {
                SocketGuildUser user = (SocketGuildUser)Context.Message.Author;

                if (user.Nickname != null)
                {
                    await user.ModifyAsync(x =>
                    {
                        x.Nickname = $"[AFK] {user.Nickname}";
                    });
                }

                else
                {
                    await user.ModifyAsync(x =>
                    {
                        x.Nickname = $"[AFK] {user.Username}";
                    });
                }
            }

            catch { }
        }
예제 #23
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());
            }
        }
예제 #24
0
 public void Handle()
 {
     MongoHandler.Save(new B3Data(_Message));
 }
예제 #25
0
        public Query(Db database)
        {
            Field <ProductObjType>(
                Product.product,
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "id"
            }
                    ),
                resolve: context =>
            {
                var id = context.GetArgument <int>("id");
                if (database == Db.Mongo)
                {
                    MongoHandler mongo = new MongoHandler();
                    return(mongo.GetProductById(id));
                }
                else
                {
                    MySqlHandler mySql = new MySqlHandler();
                    return(mySql.GetProductById(id));
                }
            }
                );
            Field <ListGraphType <ProductObjType> >(
                "products",
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "lower"
            },
                    new QueryArgument <IdGraphType> {
                Name = "upper"
            }
                    ),

                resolve: context =>
            {
                var lower = context.GetArgument <int>("lower");
                var upper = context.GetArgument <int>("upper");
                if (database == Db.Mongo)
                {
                    MongoHandler mongo = new MongoHandler();
                    return(mongo.GetProductById(lower, upper));
                }
                else
                {
                    MySqlHandler mySql = new BachelorProjectBackend.Repository.MySqlHandler();
                    return(mySql.GetProductById(lower, upper));
                }
            });


            Field <ProductObjType>(
                "productAndType",
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "id"
            }
                    ),
                resolve: context =>
            {
                var id = context.GetArgument <int>("id");
                if (database == Db.Mongo)
                {
                    MongoHandler mongo = new MongoHandler();
                    return(mongo.GetProductJoinProductTypeById(id));
                }
                else
                {
                    MySqlHandler mySql = new MySqlHandler();
                    return(mySql.GetProductJoinProductTypeById(id));
                }
            }
                );

            Field <ListGraphType <ProductObjType> >(
                "productsAndTypes",
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "lower"
            },
                    new QueryArgument <IdGraphType> {
                Name = "upper"
            }
                    ),

                resolve: context =>
            {
                var lower = context.GetArgument <int>("lower");
                var upper = context.GetArgument <int>("upper");
                if (database == Db.Mongo)
                {
                    MongoHandler mongo = new MongoHandler();
                    return(mongo.GetProductJoinProductTypeById(lower, upper));
                }
                else
                {
                    MySqlHandler mySql = new BachelorProjectBackend.Repository.MySqlHandler();
                    return(mySql.GetProductJoinProductTypeById(lower, upper));
                }
            });

            Field <ProductObjType>(
                "productAndTypeAndCompany",
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "id"
            }
                    ),

                resolve: context =>
            {
                var id = context.GetArgument <int>("id");
                if (database == Db.Mongo)
                {
                    MongoHandler mongo = new MongoHandler();
                    return(mongo.GetProductJoinProductTypeAndCompanyById(id));
                }
                else
                {
                    MySqlHandler mySql = new BachelorProjectBackend.Repository.MySqlHandler();
                    return(mySql.GetProductJoinProductTypeAndCompanyById(id));
                }
            });

            Field <ListGraphType <ProductObjType> >(
                "productsAndTypesAndCompanys",
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "lower"
            },
                    new QueryArgument <IdGraphType> {
                Name = "upper"
            }
                    ),

                resolve: context =>
            {
                var lower = context.GetArgument <int>("lower");
                var upper = context.GetArgument <int>("upper");
                if (database == Db.Mongo)
                {
                    MongoHandler mongo = new MongoHandler();
                    return(mongo.GetProductJoinProductTypeAndCompanyById(lower, upper));
                }
                else
                {
                    MySqlHandler mySql = new BachelorProjectBackend.Repository.MySqlHandler();
                    return(mySql.GetProductJoinProductTypeAndCompanyById(lower, upper));
                }
            });



            Field <CompanyObjType>(
                Company.company,
                resolve: context =>
            {
                if (database == Db.Mongo)
                {
                    return(null);
                }
                else
                {
                    return(null);
                }
            });
            Field <DepartmentObjType>(
                Department.department,
                resolve: context =>
            {
                if (database == Db.Mongo)
                {
                    return(null);
                }
                else
                {
                    return(null);
                }
            });
            Field <PersonObjType>(
                Person.person,
                resolve: context =>
            {
                if (database == Db.Mongo)
                {
                    return(null);
                }
                else
                {
                    return(null);
                }
            });
            Field <ProductTypeObjType>(
                ProductType.productType,
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "id"
            }
                    ),
                resolve: context =>
            {
                var id = context.GetArgument <int>("id");
                if (database == Db.Mongo)
                {
                    MongoHandler mongo = new MongoHandler();
                    return(mongo.GetProductJoinProductTypeById(id));
                }
                else
                {
                    MySqlHandler mySql = new MySqlHandler();
                    return(mySql.GetProductJoinProductTypeById(id));
                }
            });
        }
예제 #26
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());
            }
        }