Beispiel #1
0
        public async Task GuildInfo()
        {
            DateTime     startTime    = DateTime.Now;
            var          orderedRoles = Context.Guild.Roles.Where(x => x.IsMentionable).ToList().OrderByDescending(x => x.Permissions.ToString());
            EmbedBuilder embedBuilder = new EmbedBuilder();

            EmbedService.BuildFeedbackEmbed(embedBuilder);
            embedBuilder.Title       = $"{Context.Guild.Name.ToString()} Info";
            embedBuilder.Description = $"{Context.Guild.DefaultChannel.Topic.SpliceText(50)}\n\n{"Roles:".Bold()} ";

            foreach (IRole role in orderedRoles)
            {
                embedBuilder.AppendEmbedDescription($"{role.Mention} ({Context.Guild.Users.Where(x => x.Roles.Contains(role)).Count().ToString().Bold()}), ");
            }
            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                embedBuilder.AddField(x => { x.Name = ":desktop: Default Channel"; x.Value = Context.Guild.DefaultChannel.Name; x.IsInline = true; });
                embedBuilder.AddField(x => { x.Name = ":man: Users"; x.Value = Context.Guild.MemberCount; x.IsInline = true; });
                embedBuilder.AddField(x => { x.Name = ":abc: Text Channels"; x.Value = Context.Guild.TextChannels.Count(); x.IsInline = true; });
                embedBuilder.AddField(x => { x.Name = ":speaking_head: Voice Channels"; x.Value = Context.Guild.VoiceChannels.Count(); x.IsInline = true; });
                embedBuilder.AddField(x => { x.Name = ":love_letter: Stored Messages"; x.Value = DBContext.Messages.FromSql("SELECT Messages.Id, Messages.ChannelId, TextChannels.GuildId FROM Messages INNER JOIN TextChannels ON TextChannels.Id = Messages.ChannelId WHERE TextChannels.GuildId = {0}", Context.Guild.Id.ToString()).AsNoTracking().Count().ToString(); x.IsInline = true; });
                //embedBuilder.AddField(x => { x.Name = ":love_letter: Stored Messages"; x.Value = DBContext.Messages.Where(y => Context.Guild.Channels.FirstOrDefault(z => z.Id.ToString() == y.ChannelId) != null).Count().ToString(); x.IsInline = true; });
                embedBuilder.AddField(x => { x.Name = ":camera_with_flash:  Multifactor Authentication Level"; x.Value = Enum.GetName(typeof(MfaLevel), Context.Guild.MfaLevel); x.IsInline = true; });
                embedBuilder.AddField(x => { x.Name = ":tools: Commands Executed"; x.Value = DBContext.CommandLogs.Where(y => y.GuildId == Context.Guild.Id.ToString()).Count().ToString().Number().Bold(); x.IsInline = true; });
            }
            embedBuilder.WithThumbnailUrl(Context.Guild.IconUrl);
            embedBuilder.WithFooter(x =>
            {
                x.Text = $"⏰ Generated in:  {Math.Round((DateTime.Now.Subtract(startTime).TotalMilliseconds)).ToString()}ms";
            });
            await ReplyAsync("", embed : embedBuilder.Build());
        }
        public ParcelEditViewModel(DBContextFactory contextFactory)
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                ContextFactory = contextFactory;
                ContextDb      = ContextFactory.Create();
                LoadData       = LoadDataAsync();
            }

            //Инициализация комманд
            SaveChangesCommand = new RelayCommand(SaveChanges);
            UndoChangesCommand = new RelayCommand(UndoChanges);

            //Подписка на уведомление об изменении справочников
            Messenger.Default.Register <ReferenceRefreshedMessage>(this, async(msg) =>
            {
                if (LoadData != null)                                                   //Если не завершилась первичная загрузка данных, то ждем ее
                {
                    await Task.WhenAll(LoadData);
                }
                if (RefreshData != null)                                //Если не завершилась предыдущая операция обновления данных, то ждем ее
                {
                    await Task.WhenAll(RefreshData);
                }
                RefreshData = RefreshDataAsync();                               //Запускаем операцию обновления данных
            });
        }
Beispiel #3
0
        public async Task MakeTag([Summary("The name of the Tag.")] string name, [Summary("The content of the tag.")][Remainder] string content)
        {
            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                var tagExists = DBContext.ChannelTags.Where(x => x.ChannelId == Context.Channel.Id.ToString()).FirstOrDefault(x => x.Name.ToLower() == name.ToLower());
                if (tagExists == null)
                {
                    ChannelTag channelTag = new ChannelTag(name, content, Context.Channel.Id.ToString(), Context.User.Id.ToString(), DateTime.Now);
                    await DBContext.AddAsync(channelTag);

                    await DBContext.SaveChangesAsync();
                    await ReplyAsync("", embed : EmbedService.MakeSuccessFeedbackEmbed($"You have successfully attached the tag {name} to this channel."));
                }
                else
                {
                    await ReplyAsync("", embed : EmbedService.MakeFailFeedbackEmbed("A tag already exists in this channel with that name."));
                }
            }
        }
        /// <summary>
        /// Загружает данные из базы данных
        /// </summary>
        async protected void LoadDataAsync()
        {
            using (var ContextDb = ContextDbFactory.Create())
            {
                var dbDep = await ContextDb.CadastraleDepartements_v.Select((g) => g.Shape).ToListAsync();

                var dbZone = await ContextDb.CadastraleZones_v.Select((g) => g.Shape).ToListAsync();

                var dbSect = await ContextDb.CadastraleSecteurs_v.Select((g) => g.Shape).ToListAsync();

                var depLoc  = dbDep.AsParallel().Select((s) => UtmZone31nToWgs84Transform(s)).ToList();
                var zoneLoc = dbZone.AsParallel().Select((s) => UtmZone31nToWgs84Transform(s)).ToList();
                var sectLoc = dbSect.AsParallel().Select((s) => UtmZone31nToWgs84Transform(s)).ToList();

                CadDepartamentsLocations = new ObservableCollection <LocationCollection>(depLoc);
                CadZoneLocations         = new ObservableCollection <LocationCollection>(zoneLoc);
                CadSectorLocations       = new ObservableCollection <LocationCollection>(sectLoc);
            }
            //Направляем уведомление об изменении свойств
            RaisePropertyChanged(nameof(CadDepartamentsLocations));
            RaisePropertyChanged(nameof(CadZoneLocations));
            RaisePropertyChanged(nameof(CadSectorLocations));
        }
Beispiel #5
0
        public async Task CNNSubscribe()
        {
            using (SubDBContext DBContext = DBFactory.Create <SubDBContext>())
            {
                string channelId = Context.Channel.Id.ToString();
                string userId    = Context.User.Id.ToString();

                var subExists = (DBContext.CNNSubscribers.FromSql("SELECT * FROM CNNSubscribers WHERE Id = {0} AND Subscriber = {1} LIMIT 1", Context.Channel.Id.ToString(), Context.User.Id.ToString()).AsNoTracking().FirstOrDefault() != null);
                if (subExists)
                {
                    await ReplyAsync("", embed : EmbedService.MakeFailFeedbackEmbed("This channel is already subscribed to CNN."), lifeTime : Config.FeedbackMessageLifeTime);

                    return;
                }
                var newUser = new CNNSubscriber(channelId, userId, DateTime.Now);
                await DBContext.CNNSubscribers.AddAsync(newUser);

                await DBContext.SaveChangesAsync();

                CNNService.TextChannnels.Add(Context.Channel as SocketTextChannel);
                await ReplyAsync("", embed : EmbedService.MakeSuccessFeedbackEmbed($"You have subscribed the channel {Context.Channel.Name.Bold()} to CNN breaking news!"));
            }
        }
Beispiel #6
0
 public ReferenceViewModel(DBContextFactory contextFactory)
 {
     if (IsInDesignMode)
     {
         // Code runs in Blend --> create design time data.
     }
     else
     {
         ContextDb = contextFactory.Create();
         LoadDataAsync();
     }
     //Инициализация комманд
     SaveChangesCommand = new RelayCommand(SaveChanges);
     UndoChangesCommand = new RelayCommand(UndoChanges);
 }
        /// <summary>
        /// Индикатор ошибок по имени поля
        /// </summary>
        /// <param name="columnName">Наименование проверяемого свойства</param>
        /// <returns>null - при осутствии ошибок, в противном случае описание ошибки</returns>
        public string this[string columnName]
        {
            get
            {
                if (columnName == nameof(EditShape))
                {
                    //Защита от дурака
                    if (EditShape == "" || EditShape == null)
                    {
                        return("Геометрия не может быть пустой");
                    }

                    SqlGeometry shape;

                    //Проверка на возможность конвертации в геометрию
                    try
                    {
                        //Конвертация строки в SqlGeometry
                        SqlChars wkt = new SqlChars(EditShape.ToCharArray());
                        shape = SqlGeometry.STGeomFromText(wkt, 32631).MakeValid();
                    }
                    catch (Exception ex)
                    {
                        return(String.Format("Ошибка геометрии: {0}", ex.Message));
                    }

                    //Расположен ли полигон в пределах границ Республики Бенин
                    DbGeometry newDbGeometry = shape.ToDbGeometry();
                    using (var context = ContextFactory.Create())
                    {
                        context.CadastraleSecteurs_v.Load();
                        var  cadSect       = context.CadastraleSecteurs_v.Local;
                        bool IsBeninWithin = cadSect.Where(s => s.Shape.Intersects(newDbGeometry)).Any();
                        if (!IsBeninWithin)
                        {
                            return("Границы расположены за пределами государственной границы Республики Бенин");
                        }
                    }

                    //Ошибок не найдено
                    return(null);
                }
                else
                {
                    return(null);
                }
            }
        }
        override protected Task RunAsync()
        {
            Client.UserJoined += async(guildUser) =>
            {
                string guildId = guildUser.Guild.Id.ToString();
                using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                {
                    var message = await DBContext.DiscordSalutationMessages.FromSql("SELECT * FROM DiscordSalutationMessages WHERE Id = {0} AND OnJoin = 1 LIMIT 1", guildUser.Guild.Id.ToString()).AsNoTracking().SingleAsync();
                    await ProcessMessage(guildId, guildUser, message);
                }
            };

            Client.UserLeft += async(guildUser) =>
            {
                string guildId = guildUser.Guild.Id.ToString();
                using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                {
                    var message = await DBContext.DiscordSalutationMessages.FromSql("SELECT * FROM DiscordSalutationMessages WHERE Id = {0} AND OnJoin = 0 LIMIT 1", guildUser.Guild.Id.ToString()).AsNoTracking().SingleAsync();
                    await ProcessMessage(guildId, guildUser, message);
                }
            };

            return(Task.CompletedTask);
        }
Beispiel #9
0
        public async Task Stats()
        {
            var pInfo = new ProcessStartInfo()
            {
                FileName               = "bash",
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                Arguments              = $"{Directory.GetCurrentDirectory()}/BashScripts/ServerStats.sh"
            };
            Process bashProcess = new Process()
            {
                StartInfo = pInfo
            };

            bashProcess.Start();
            string strOut = await bashProcess.StandardOutput.ReadToEndAsync();

            bashProcess.WaitForExit();
            var osName = "Windows ";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                osName = "Linux ";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                osName = "OSX ";
            }

            osName = $"{osName}{Enum.GetName(typeof(Architecture), RuntimeInformation.OSArchitecture)}";
            var    libVersion   = typeof(DiscordSocketClient).GetTypeInfo().Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;
            string embedMessage = $"OS: {osName}\nLibrary Version: Discord.Net - {libVersion}\n{strOut}";
            Regex  titleRegex   = new Regex(@"[A-Za-z].+\:");

            foreach (Match match in titleRegex.Matches(embedMessage))
            {
                embedMessage = embedMessage.Replace(match.Value, $"{match.Value.Bold()}");
            }
            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
                using (MySqlConnection conn = new MySqlConnection(DBContext.ConnectionString))
                {
                    MySqlCommand mySQLCommand = new MySqlCommand(File.ReadAllText("SQLScripts/dbsize.txt"), conn);
                    mySQLCommand.CommandType = System.Data.CommandType.Text;
                    double totalSize = 0;

                    await conn.OpenAsync();

                    using (var rowReader = await mySQLCommand.ExecuteReaderAsync())
                    {
                        while (await rowReader.ReadAsync())
                        {
                            totalSize += double.Parse(rowReader[4].ToString());
                        }
                    }
                    conn.Close();
                    embedMessage += $"**Database Size**: {totalSize}MB";
                }
            await ReplyAsync("", embed : EmbedService.MakeFeedbackEmbed(embedMessage));

            bashProcess.Dispose();
        }
        /// <summary>
        /// Обновляет данные справочников изменившихся в БД
        /// </summary>
        /// <returns></returns>
        async protected Task RefreshDataAsync()
        {
            //Актуальные справочники
            ObservableCollection <UtilisationType>           actualUtilisations;
            ObservableCollection <CertificationDocumentType> actualCertificationDocumentTypes;

            //Загружаем актуальные справочники
            using (CadastrBeninDB db = ContextFactory.Create())
            {
                await db.UtilisationTypes.LoadAsync();

                await db.CertificationDocumentTypes.LoadAsync();

                actualUtilisations = new ObservableCollection <UtilisationType>(db.UtilisationTypes.Local);
                actualCertificationDocumentTypes = new ObservableCollection <CertificationDocumentType>(db.CertificationDocumentTypes.Local);
            }

            //Находим изменившиеся справочники
            var oldUtilisations = ContextDb.UtilisationTypes.Local.Except(actualUtilisations, new UtilizationTypeEqualityComparer()).ToList();
            var oldCertificationDocumentTypes = ContextDb.CertificationDocumentTypes.Local.Except(actualCertificationDocumentTypes, new CertificationDocumentTypeEqualityComparer()).ToList();

            //Находим зу, затронутые изменениями
            var oldParcels = Parcels.Where(p => p.Utilisations.Select(u => u.UtilisationTypeNom)
                                           .Intersect(
                                               oldUtilisations.Select(u => u.Nom))
                                           .Any()
                                           ||
                                           p.CertificationDocuments.Select(c => c.CertificationDocumentTypeNom)
                                           .Intersect(
                                               oldCertificationDocumentTypes.Select(c => c.Nom))
                                           .Any()
                                           ).ToList();



            ContextDb.UtilisationTypes.Load();
            UtilisationTypes = new ObservableCollection <UtilisationType>(ContextDb.UtilisationTypes.Local);
            //Убираем из справочника устаревшие значения
            foreach (var old in oldUtilisations.ToList())
            {
                UtilisationTypes.Remove(UtilisationTypes.Where(d => d.Nom == old.Nom).Single());
            }

            ContextDb.CertificationDocumentTypes.Load();
            CertificationDocumentTypes = new ObservableCollection <CertificationDocumentType>(ContextDb.CertificationDocumentTypes.Local);
            //Убираем из справочника устаревшие значения
            foreach (var old in oldCertificationDocumentTypes.ToList())
            {
                CertificationDocumentTypes.Remove(CertificationDocumentTypes.Where(d => d.Nom == old.Nom).Single());
            }


            //Обновляем участки, затронутые изменениями
            foreach (var parcel in oldParcels)
            {
                foreach (var util in parcel.Utilisations)
                {
                    if (oldUtilisations.Contains(util.UtilisationType))
                    {
                        ContextDb.Entry(util).Reload();
                    }
                }

                foreach (var doc in parcel.CertificationDocuments)
                {
                    if (oldCertificationDocumentTypes.Contains(doc.CertificationDocumentType))
                    {
                        ContextDb.Entry(doc).Reload();
                    }
                }
            }

            //Направляем уведомление об изменении данных
            RaisePropertyChanged(nameof(CertificationDocumentTypes));
            RaisePropertyChanged(nameof(UtilisationTypes));
            RaisePropertyChanged(nameof(Parcels));
        }
Beispiel #11
0
 public GetTicketsForUserTests()
 {
     _context = DBContextFactory.Create();
     _identityServiceFactory = new IdentityServiceFactory();
 }
 public CreateTicketTests()
 {
     _context            = DBContextFactory.Create();
     _userServiceFactory = new IdentityServiceFactory();
 }
        public async Task InitializeCollection()
        {
            GameTracker();
            MessageTracker();
            ReactionTracker();
            GuildTracker();
            await Task.Run(async() =>
            {
                await ProcessGuilds();
            });

            using (BotDBContext DBContext = DBFactory.Create <BotDBContext>())
            {
                ConsoleEx.WriteColoredLine(LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, $"$[[Cyan]]${DBContext.Guilds.Count()}$[[Gray]]$ Guilds in the database.");
                ConsoleEx.WriteColoredLine(LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, $"$[[Cyan]]${DBContext.TextChannels.Count()}$[[Gray]]$ Text Channels in the database.");
                ConsoleEx.WriteColoredLine(LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, $"$[[Cyan]]${DBContext.Users.Count()}$[[Gray]]$ Users in the database.");
            }
        }
Beispiel #14
0
 public GetAllTicketsTests()
 {
     _context = DBContextFactory.Create();
 }
Beispiel #15
0
 public TicketDetailsTests()
 {
     _context = DBContextFactory.Create();
 }
 public CloseTicketTests()
 {
     _context = DBContextFactory.Create();
 }
Beispiel #17
0
        protected override void Run()
        {
            bool firstRun              = true; //So articles don't spam when I restart the bot.
            bool readyFired            = false;
            DiscordSocketClient client = Provider.GetService <DiscordSocketClient>();

            client.Ready += () =>
            {
                if (readyFired)
                {
                    return(Task.CompletedTask);
                }

                readyFired = true;
                using (SubDBContext DBContext = Factory.Create <SubDBContext>())
                {
                    var subscribers = DBContext.CNNSubscribers.FromSql("SELECT * FROM CNNSubscribers");
                    foreach (CNNSubscriber sub in subscribers)
                    {
                        SocketTextChannel textChannel = client.GetChannel(ulong.Parse(sub.Id)) as SocketTextChannel;
                        if (!TextChannnels.Contains(textChannel))
                        {
                            TextChannnels.Add(textChannel);
                        }
                        ConsoleEx.WriteColoredLine(Discord.LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, $"Attached $[[DarkMagenta]]$CNNService$[[Gray]]$ to text channel $[[White]]${textChannel.Name}.");
                    }
                }

                StaticMethods.FireAndForget(() =>
                {
                    ConsoleEx.WriteColoredLine(Discord.LogSeverity.Info, ConsoleTextFormat.TimeAndText, $"Attached CNNService to $[[Green]]${TextChannnels.Count}$[[Gray]]$ channels.");
                    int checkInterval = Provider.GetService <MathService>().TimeUnitToMilli(TimeUnit.Minutes, Config.CNNCheckInterval);
                    CheckTimer        = new Timer(async(e) =>
                    {
                        try
                        {
                            string result       = await HttpService.Get("http://www.cnn.com/");
                            Regex articlesRegex = new Regex("siblings:(.*?)(?=                     ,)");
                            Match match         = articlesRegex.Match(result);
                            string trimmedMatch = match.Value.TrimEnd(',').Replace("siblings:         ", "");
                            Dictionary <string, dynamic> json = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(trimmedMatch));
                            string articleTitle = json["articleList"][0]["headline"].ToString();
                            string articleUrl   = json["articleList"][0]["uri"].ToString();
                            if (PostedArticles.FirstOrDefault(x => x == articleUrl) == null)
                            {
                                PostedArticles.Add(articleUrl);
                                if (!firstRun)
                                {
                                    foreach (SocketTextChannel textChannel in TextChannnels)
                                    {
                                        await textChannel.SendMessageAsync($"http://www.cnn.com{articleUrl}");
                                    }
                                }
                            }

                            firstRun = false;
                            await Task.CompletedTask;
                        }
                        catch (Exception ex)
                        {
                            ConsoleEx.WriteColoredLine($"$[[DarkCyan]]$CNNService$[[Gray]]$ has made an exception\n$[[Red]]${ex.Message}");
                            Console.WriteLine(ex.Message);
                        }
                        CheckTimer.Change(checkInterval, 0);
                    }, null, checkInterval, 0);
                });
                return(Task.CompletedTask);
            };
        }
Beispiel #18
0
 public AddMessageTests()
 {
     _context            = DBContextFactory.Create();
     _userServiceFactory = new IdentityServiceFactory();
 }