コード例 #1
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            bool active = false;

            try { active = CheckElement("access_token") && CheckElement("expires_at") && CheckElement("nickname") && CheckElement("account_id"); }
            catch (Exception) { active = false; }

            try
            {
                Task.Factory.StartNew(() =>
                {
                    Dispatcher.BeginInvoke(new ThreadStart(delegate { MainWindow.LoadPage.Visibility = System.Windows.Visibility.Visible; }));
                    Thread.Sleep(Convert.ToInt16(Properties.Resources.Default_Navigator_Sleep));
                });

                // Проверяем актуальность даты
                if (active)
                {
                    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                    dtDateTime = dtDateTime.AddSeconds((double)MainWindow.JsonSettingsGet("token.expires_at")).ToLocalTime();
                    active     = dtDateTime > DateTime.UtcNow;
                }

                // Если токен неверный, либо устарел - выводим авторизацию
                if (!active)
                {
                    try { MainWindow.JsonSettingsRemove("token"); }
                    catch (Exception) { }

                    try
                    {
                        // Live hack
                        Window1 Win1 = new Window1();
                        Win1.Show();
                        Win1.Close();

                        // Открываем окно
                        //new WarApiOpenID().ShowDialog();

                        Dispatcher.BeginInvoke(new ThreadStart(delegate
                        {
                            MainWindow.LoadPage.Content    = Lang.Set("PageLoading", "lLoading", (string)MainWindow.JsonSettingsGet("info.language"));
                            MainWindow.LoadPage.Visibility = System.Windows.Visibility.Visible;
                        }));
                        Thread.Sleep(Convert.ToInt16(Properties.Resources.Default_Navigator_Sleep));

                        Dispatcher.BeginInvoke(new ThreadStart(delegate { MainWindow.Navigator("WgOpenIdAIRUS"); }));
                    }
                    catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "if (!active)", ex.Message, ex.StackTrace)); }
                }
                else
                {
                    Task.Factory.StartNew(() => { AccountInfo(); });
                }
            }
            catch (Exception ex0) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "if (active)", ex0.Message, ex0.StackTrace)); }
        }
コード例 #2
0
        /// <summary>
        ////Открываем гиперссылку
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">Параметры</param>
        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            try
            {
                Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
                e.Handled = true;

                MainWindow.JsonSettingsSet("stats.donate_link", 1 + (int)MainWindow.JsonSettingsGet("stats.donate_link"), "int");
            }
            catch (Exception ex) { Task.Factory.StartNew(() => new Classes.Debugging().Save("General.xaml", "Hyperlink_RequestNavigate()", "Link: " + e.Uri.AbsoluteUri, ex.Message, ex.StackTrace)); }
        }
コード例 #3
0
        public Feedback()
        {
            InitializeComponent();

            Task.Factory.StartNew(() =>
            {
                try { lang = (string)MainWindow.JsonSettingsGet("info.language"); }
                catch (Exception ex) { Debugging.Save("Feedback.xaml", "Feedback()", ex.Message, ex.StackTrace); }
            }).Wait();

            Task.Factory.StartNew(() => SetInterface()); // Загрузка языка
        }
コード例 #4
0
 private void Page_Loaded(object sender, RoutedEventArgs e)
 {
     Dispatcher.BeginInvoke(new ThreadStart(delegate
     {
         try
         {
             MainWindow.LoadPage.Visibility = Visibility.Hidden;
             MainWindow.JsonSettingsSet("stats.donate", 1 + (int)MainWindow.JsonSettingsGet("stats.donate"), "int");
         }
         catch (Exception) { }
     }));
 }
コード例 #5
0
 /// <summary>
 /// Запрещал ли пользователь закрытие процесса при оптимизации ПК?
 /// </summary>
 /// <param name="proc">Имя процесса для проверки</param>
 /// <returns>Если процесс есть в списке, выводим TRUE, иначе - FALSE</returns>
 private bool CheckUserProcess(string proc)
 {
     try
     {
         string processes = MainWindow.JsonSettingsGet("processes").ToString();
         if (processes.IndexOf(proc) != -1)
         {
             return(true);
         }
     }
     catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("SettingsProcesses.xaml", "CheckUserProcess()", "Process: " + proc, ex.Message, ex.StackTrace)); }
     return(false);
 }
コード例 #6
0
 /// <summary>
 /// Проверяем существует ли аттрибут
 /// </summary>
 /// <param name="attr">Аттрибут для проверки</param>
 /// <returns>TRUE - существует, FALSE - не существует</returns>
 private bool CheckElement(string attr)
 {
     try
     {
         string elem = (string)MainWindow.JsonSettingsGet("token." + attr);
         if (elem != null && elem != "")
         {
             return(true);
         }
     }
     catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "CheckElement()", "Attribute: " + attr, ex.Message, ex.StackTrace)); }
     return(false);
 }
コード例 #7
0
        private void bClose_Click(object sender, RoutedEventArgs e)
        {
            MainWindow.PlayBtn.Text = Lang.Set("MainProject", "bPlay", (string)MainWindow.JsonSettingsGet("info.language"));

            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                MainWindow.LoadPage.Content    = Lang.Set("PageLoading", "lLoading", (string)MainWindow.JsonSettingsGet("info.language"));
                MainWindow.LoadPage.Visibility = System.Windows.Visibility.Visible;

                MainWindow.Flag.Source = new BitmapImage(new Uri(String.Format(@"pack://application:,,,/{0};component/Resources/flag_{1}.png", (string)MainWindow.JsonSettingsGet("info.ProductName"), (string)MainWindow.JsonSettingsGet("info.language"))));
            }));
            Thread.Sleep(Convert.ToInt16(Properties.Resources.Default_Navigator_Sleep));

            Dispatcher.BeginInvoke(new ThreadStart(delegate { MainWindow.Navigator(); }));
        }
コード例 #8
0
 /// <summary>
 /// Если мы удалили 1 пункт из списка, то дальнейший перебор невозможен.
 /// Но используя рекурсию мы повторяем перебор до тех пор, пока все ненужные
 /// элементы не будут удалены из списка. Profit!
 /// </summary>
 /// <returns>Функция как таковая ничего не возвращает</returns>
 private void DeleteOldVideo()
 {
     try
     {
         foreach (var el in YoutubeClass.List)
         {
             try { if (!YoutubeClass.CheckDate((string)MainWindow.JsonSettingsGet("multipack.date"), el.Date))
                   {
                       YoutubeClass.Delete(el.ID);
                   }
             }
             catch (Exception) { DeleteOldVideo(); }
         }
     }
     catch (Exception) { }
 }
コード例 #9
0
        private void bUpdate_Click(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                try
                {
                    string link = (string)MainWindow.JsonSettingsGet("multipack.link");
                    if (link != String.Empty)
                    {
                        Process.Start(link);
                    }
                }
                catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("Update.xaml", "bUpdate_Click()", ex.Message, ex.StackTrace)); }
            }));

            Task.Factory.StartNew(() => ClosingPage());
        }
コード例 #10
0
        public General()
        {
            InitializeComponent();

            string nickname = String.Empty;

            try
            {
                nickname = (string)MainWindow.JsonSettingsGet("info.user_name");
                if (nickname.Length > 0)
                {
                    nickname = ", " + nickname;
                }
            }
            catch (Exception) { nickname = String.Empty; }

            Task.Factory.StartNew(() => SetInterface());
            Task.Factory.StartNew(() => ShowNotify(Lang.Set("PageGeneral", "lStatus", lang) + nickname + "!", "", false));
        }
コード例 #11
0
        private void SetText()
        {
            try
            {
                Classes.Language Lang = new Classes.Language();

                string lang = (string)MainWindow.JsonSettingsGet("info.language");

                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    tbCaption.Text = Lang.Set("GiveEmail", "Caption", lang);
                    tbMessage.Text = Lang.Set("GiveEmail", "Message", lang);

                    Iagree.Content    = Lang.Set("Button", "Iagree", lang);
                    Idisagree.Content = Lang.Set("Button", "Idisagree", lang);
                }));
            }
            catch (Exception ex) { Debugging.Save("GiveEmail.xaml", "SetText()", ex.Message, ex.StackTrace); }
        }
コード例 #12
0
        /// <summary>
        ///
        /// </summary>
        private void ClosingPage()
        {
            Dispatcher.BeginInvoke(new ThreadStart(delegate { MainWindow.LoadPage.Visibility = System.Windows.Visibility.Visible; }));
            Thread.Sleep(Convert.ToInt16(Properties.Resources.Default_Navigator_Sleep));

            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                try
                {
                    if (cbNotify.IsChecked == true)
                    {
                        MainWindow.JsonSettingsSet("info.notification", MainWindow.JsonSettingsGet("multipack.new_version"));
                    }
                    MainWindow.JsonSettingsSet("info.session", System.Diagnostics.Process.GetCurrentProcess().Id, "int");

                    MainWindow.Navigator();
                }
                catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("Update.xaml", "bUpdate_Click()", ex.Message, ex.StackTrace)); }
            }));
        }
コード例 #13
0
        private void bLauncher_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string game_path = ((string)MainWindow.JsonSettingsGet("game.path")).Replace(Properties.Resources.Default_JSON_Splitter, @"\");

                if (System.IO.File.Exists(game_path + "WoTLauncher.exe"))
                {
                    Task.Factory.StartNew(() => new Classes.Optimize().Start(
                                              (bool)MainWindow.JsonSettingsGet("settings.winxp"),
                                              (bool)MainWindow.JsonSettingsGet("settings.kill"),
                                              (bool)MainWindow.JsonSettingsGet("settings.force"),
                                              (bool)MainWindow.JsonSettingsGet("settings.aero"),
                                              (bool)MainWindow.JsonSettingsGet("settings.video"),
                                              (bool)MainWindow.JsonSettingsGet("settings.weak"),
                                              false
                                              ));

                    Task.Factory.StartNew(() => MainWindow.ProcessStart(game_path, "WoTLauncher.exe"));

                    Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        switch ((int)MainWindow.JsonSettingsGet("settings.launcher"))
                        {
                        case 1: MainWindow.State.Hide(); break;

                        case 2: MainWindow.State.WindowState = System.Windows.WindowState.Minimized; break;

                        case 3: MainWindow.State.Close(); break;

                        default: break;
                        }
                    }));
                }
                else
                {
                    MessageBox.Show(Lang.Set("MainProject", "Game_Not_Found", (string)MainWindow.JsonSettingsGet("info.language")));
                }
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("General.xaml", "bLauncher_Click()", ex.Message, ex.StackTrace)); }
        }
コード例 #14
0
        private void MultipackUpdate()
        {
            try
            {
                Classes.Language Lang = new Classes.Language();
                string           lang = (string)MainWindow.JsonSettingsGet("info.language");

                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    gbCaption.Header          = Lang.Set("PageUpdate", "gbCaption", lang);
                    lDownloadFromLink.Content = Lang.Set("PageUpdate", "lDownloadFromLink", lang);
                    cbNotify.Content          = Lang.Set("PageUpdate", "cbNotify", lang);
                    bUpdate.Content           = Lang.Set("PageUpdate", "bUpdate", lang);
                    bCancel.Content           = Lang.Set("PageUpdate", "bCancel", lang);

                    newVersion.Content = new Classes.Variables().VersionSharp((string)MainWindow.JsonSettingsGet("multipack.new_version"), false);
                    tbContent.Text     = ParseChangelog((string)MainWindow.JsonSettingsGet("multipack.changelog"));
                }));
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("Update.xaml", "MultipackUpdate()", ex.Message, ex.StackTrace)); }
        }
コード例 #15
0
        /// <summary>
        /// Сохранение неотправленных тикетов
        /// </summary>
        /// <param name="json"></param>
        private void SaveTicket(JObject json)
        {
            try
            {
                if (!Directory.Exists(MainWindow.SettingsDir + "tickets"))
                {
                    Directory.CreateDirectory(MainWindow.SettingsDir + "tickets");
                }

                string filename = String.Format("{0}_{1}.ticket", (string)MainWindow.JsonSettingsGet("info.user_id"), DateTime.Now.ToString("yyyy-MM-dd h-m-s.ffffff"));

                if (Properties.Resources.API_DEV_CRYPT == "1")
                {
                    string encoded = new Classes.Crypt().Encrypt(json.ToString(), (string)MainWindow.JsonSettingsGet("info.user_id"), true);
                    if (encoded != "FAIL")
                    {
                        File.WriteAllText(MainWindow.SettingsDir + @"tickets\" + filename, encoded, Encoding.UTF8);
                    }
                }
                else
                {
                    File.WriteAllText(MainWindow.SettingsDir + @"tickets\" + filename, json.ToString(), Encoding.UTF8);
                }

                // Очищаем поля
                tbMessage.Text = String.Empty;
                if (tbEmail.IsEnabled)
                {
                    tbEmail.Text = String.Empty;
                }

                // Выдаем сообщение о сохранении тикета
                MainWindow.Notifier.ShowBalloonTip(5000,
                                                   Lang.Set("PostClass", "AutoTicketWait", lang),
                                                   Lang.Set("PageFeedback", "TicketSaved", lang),
                                                   System.Windows.Forms.ToolTipIcon.Info);
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("PageFeedback", "SaveTicket()", ex.Message, ex.StackTrace)); }
        }
コード例 #16
0
 /// <summary>
 /// Вывод уведомления либо в строку статуса, либо всплывающим уведомлением в системном трее
 /// </summary>
 /// <param name="text">Текст отображения</param>
 /// <param name="caption">Заголовок</param>
 /// <param name="isPopup">TRUE - вывод в системном трее, иначе - в строке статуса формы</param>
 private void ShowNotify(string text, string caption = null, bool isPopup = true)
 {
     try
     {
         Dispatcher.BeginInvoke(new ThreadStart(delegate
         {
             if (isPopup)
             {
                 try
                 {
                     caption = caption != null ? caption : (string)MainWindow.JsonSettingsGet("info.ProductName");
                     MainWindow.Notifier.ShowBalloonTip(5000, caption, text, System.Windows.Forms.ToolTipIcon.Info);
                 }
                 catch (Exception ex0) { Task.Factory.StartNew(() => Debugging.Save("General.xaml", "ShowNotify()", "Caption: " + caption, text, "IsPopup = " + isPopup.ToString(), ex0.Message, ex0.StackTrace)); }
             }
             else
             {
                 lStatus.Text = text;
             }
         }));
     }
     catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("General.xaml", "ShowNotify()", "Caption: " + caption, text, "IsPopup = " + isPopup.ToString(), ex.Message, ex.StackTrace)); }
 }
コード例 #17
0
        private void bOptimize_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show(Lang.Set("Optimize", "Optimize", lang) + "?", (string)MainWindow.JsonSettingsGet("info.ProductName"), MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    StatusBarSet(true);

                    new Classes.Optimize().Start(
                        (bool)MainWindow.JsonSettingsGet("settings.winxp"),
                        true,
                        true,
                        true,
                        (bool)MainWindow.JsonSettingsGet("settings.video"),
                        (bool)MainWindow.JsonSettingsGet("settings.weak"),
                        true
                        );

                    StatusBarSet(true);
                }
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("General.xaml", "bOptimize_Click()", ex.Message, ex.StackTrace)); }
        }
コード例 #18
0
        private void GetLangNow()
        {
            try
            {
                switch ((string)MainWindow.JsonSettingsGet("info.language"))
                {
                case "en": cbLang.SelectedIndex = 1; break;

                case "de": cbLang.SelectedIndex = 2; break;

                case "ua": cbLang.SelectedIndex = 3; break;

                default: cbLang.SelectedIndex = 0; break;
                }

                if (IsManual)
                {
                    cbLangPriority.SelectedIndex = 2;
                    MainWindow.JsonSettingsSet("info.locale", cbLangPriority.SelectedIndex, "int");
                }
            }
            catch (Exception) { }
        }
コード例 #19
0
        private void cbLangPriority_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string newLang = String.Empty;

            switch (cbLangPriority.SelectedIndex)
            {
            //  Мультипак 0
            case 0: newLang = (string)MainWindow.JsonSettingsGet("multipack.language"); IsManual = false; break;

            //  Клиент игры 1
            case 1: newLang = (string)MainWindow.JsonSettingsGet("game.language"); IsManual = false; break;

            //  Вручную 2
            case 2: newLang = (string)MainWindow.JsonSettingsGet("info.language"); IsManual = true; break;

            default: newLang = Properties.Resources.Default_Lang; IsManual = true; break;
            }

            MainWindow.JsonSettingsSet("info.locale", cbLangPriority.SelectedIndex, "int");
            MainWindow.JsonSettingsSet("info.language", newLang);

            GetLangNow();
        }
コード例 #20
0
        private void PageFeedback_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if ((string)MainWindow.JsonSettingsGet("info.user_email") != null &&
                    (string)MainWindow.JsonSettingsGet("info.user_email") != "")
                {
                    tbEmail.Text      = (string)MainWindow.JsonSettingsGet("info.user_email");
                    tbEmail.IsEnabled = false;
                }
                else
                {
                    tbEmail.Text      = "";
                    tbEmail.IsEnabled = true;
                }
            }
            catch (Exception) { tbEmail.IsEnabled = true; }

            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                try { MainWindow.LoadPage.Visibility = Visibility.Hidden; }
                catch (Exception) { }
            }));
        }
コード例 #21
0
        private void UpdateCaptcha()
        {
            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                try
                {
                    Regex regexCaptcha = new Regex("<img class=js-captcha-image src=\"(.*)\"> </div>", RegexOptions.IgnoreCase);

                    var doc = WB.Document as HTMLDocument;

                    IHTMLElementCollection nodes = doc.getElementsByTagName("body");
                    foreach (IHTMLElement elem in nodes)
                    {
                        var body = (HTMLHeadElement)elem;


                        Match matchCaptcha = regexCaptcha.Match(body.innerHTML);
                        while (matchCaptcha.Success)
                        {
                            resultCaptcha = matchCaptcha.Value.Trim();
                            resultCaptcha = resultCaptcha
                                            .Replace("<IMG class=js-captcha-image src=\"", "")
                                            .Replace("<img class=js-captcha-image src=\"", "")
                                            .Replace("\"> </div>", "")
                                            .Replace("\"> </DIV>", "");

                            if (resultCaptcha == "")
                            {
                                matchCaptcha = matchCaptcha.NextMatch();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    // Компилируем изображение
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.CacheOption   = BitmapCacheOption.None;
                    bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    bi.UriSource     = new Uri("https://ru.wargaming.net" + resultCaptcha, UriKind.RelativeOrAbsolute);
                    bi.EndInit();

                    imgCaptcha.Source = bi;
                }
                catch (Exception ex)
                {
                    imgCaptcha.Source = new BitmapImage(new Uri(String.Format(@"pack://application:,,,/{0};component/Resources/reload.jpg", (string)MainWindow.JsonSettingsGet("info.ProductName"))));
                    Task.Factory.StartNew(() => Debugging.Save("WgOpenIdAIRUS.xaml", "UpdateCaptcha()", ex.Message, ex.StackTrace));
                }
            }));
        }
コード例 #22
0
 private void ClosePage(string page = "")
 {
     Dispatcher.BeginInvoke(new ThreadStart(delegate { MainWindow.LoadPage.Content = Lang.Set("PageLoading", "lLoading", (string)MainWindow.JsonSettingsGet("info.language")); }));
     LoaderShow();
     Dispatcher.BeginInvoke(new ThreadStart(delegate { MainWindow.Navigator(page); }));
 }
コード例 #23
0
        private void WB_LoadCompleted(object sender, NavigationEventArgs e)
        {
            try
            {
                Task.Factory.StartNew(() =>
                {
                    Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        try
                        {
                            if (WB.Source.ToString().IndexOf("status=ok") > -1)
                            {
                                JObject Token = WarAPI.Token(WB.Source.ToString());

                                MainWindow.JsonSettingsSet("token.access_token", (string)Token.SelectToken("access_token"));
                                MainWindow.JsonSettingsSet("token.expires_at", (string)Token.SelectToken("expires_at"));
                                MainWindow.JsonSettingsSet("token.nickname", (string)Token.SelectToken("nickname"));
                                MainWindow.JsonSettingsSet("token.account_id", (string)Token.SelectToken("account_id"));

                                MainWindow.JsonSettingsSet("info.user_name", (string)Token.SelectToken("nickname"));

                                try
                                {
                                    Task.Factory.StartNew(() => { LoaderShow(); });

                                    Dispatcher.BeginInvoke(new ThreadStart(delegate { MainWindow.Navigator("UserProfile"); }));
                                }
                                catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("WgOpenIdAIRUS.xaml", "WB_LoadCompleted()", ex.Message, ex.StackTrace)); }

                                ClosePage("UserProfile");
                            }

                            if (WB.Source.ToString().IndexOf("AUTH_CANCEL") > -1)
                            {
                                MessageBoxResult mbr = MessageBox.Show(Lang.Set("PageUser", "ActivateWarID", (string)MainWindow.JsonSettingsGet("info.language")) +
                                                                       Environment.NewLine +
                                                                       Lang.Set("PageUser", "RepeatActivation", (string)MainWindow.JsonSettingsGet("info.language")),
                                                                       (string)MainWindow.JsonSettingsGet("info.ProductName"), MessageBoxButton.YesNo, MessageBoxImage.Information);

                                if (mbr == MessageBoxResult.Yes)
                                {
                                    string uri = WarAPI.OpenID();
                                    if (uri != null)
                                    {
                                        WB.Source = new Uri(WarAPI.OpenID());
                                    }
                                    else
                                    {
                                        Debugging.Save("WgOpenIdAIRUS.xaml", "WB_LoadCompleted()", "WarAPI.OpenID() == null");
                                        ClosePage();
                                    }
                                }
                                else
                                {
                                    ClosePage();
                                }
                            }
                        }
                        catch (Exception) { }


                        /*
                         *   Парсим форму
                         *
                         *
                         *   form | IgnoreCase | Singleline
                         *           <form id=js-auth-form(.*)form>
                         *
                         *   csrfmiddlewaretoken | IgnoreCase
                         *           value=(.*) name=csrfmiddlewaretoken
                         *
                         *   next | IgnoreCase
                         *           value=(.*) name=next
                         *
                         *   captcha | IgnoreCase
                         *           <img class=js-captcha-image src="(.*)">
                         *
                         *   errors
                         *          <P class=js-form-errors-content>(.*)</P>
                         */

                        try
                        {
                            if (!pageParsed)
                            {
                                Regex regexForm = new Regex("<form id=js-auth-form(.*)form>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                Regex regexCsrf = new Regex("value=(.*) name=csrfmiddlewaretoken", RegexOptions.IgnoreCase);
                                Regex regexNext = new Regex("value=(.*) name=next", RegexOptions.IgnoreCase);

                                var doc = WB.Document as HTMLDocument;

                                IHTMLElementCollection nodes = doc.getElementsByTagName("html");
                                foreach (IHTMLElement elem in nodes)
                                {
                                    var form = (HTMLHeadElement)elem;

                                    // Ищем форму
                                    Match match = regexForm.Match(form.innerHTML);
                                    while (match.Success)
                                    {
                                        // Ищем Csrf
                                        Match matchCsrf = regexCsrf.Match(match.Value.Trim());
                                        while (matchCsrf.Success)
                                        {
                                            resultCsrf = matchCsrf.Value.Trim();
                                            resultCsrf = resultCsrf
                                                         .Replace("value=", "")
                                                         .Replace(" name=csrfmiddlewaretoken", "");

                                            matchCsrf = matchCsrf.NextMatch();
                                        }


                                        // Ищем Next
                                        Match matchNext = regexNext.Match(match.Value.Trim());
                                        while (matchNext.Success)
                                        {
                                            resultNext = matchNext.Value.Trim();
                                            resultNext = resultNext
                                                         .Replace("value=", "")
                                                         .Replace(" name=next", "");

                                            matchNext = matchNext.NextMatch();
                                        }

                                        match = match.NextMatch();
                                    }
                                }

                                // Подгружаем изображение
                                UpdateCaptcha();

                                pageParsed = true;

                                Task.Factory.StartNew(() => { LoaderShow(false); });
                            }
                        }
                        catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("WgOpenIdAIRUS.xaml", "WB_LoadCompleted()", "Parse form", ex.Message, ex.StackTrace)); }
                    }));
                }).Wait();
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("WgOpenIdAIRUS.xaml", "WB_LoadCompleted()", ex.Message, ex.StackTrace)); }
        }
コード例 #24
0
        public SettingsProcesses()
        {
            InitializeComponent();

            gbProcesses.Header = new Classes.Language().Set("PageSettingsProcesses", "lProcesses", (string)MainWindow.JsonSettingsGet("info.language"));
        }
コード例 #25
0
        public Error()
        {
            InitializeComponent();

            bClose.Content = new Classes.Language().Set("PageSettings", "bClose", (string)MainWindow.JsonSettingsGet("info.language"));
        }
コード例 #26
0
        private void lbLocales_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);

                MainWindow.JsonSettingsSet("info.language", lbi.Name);
                MainWindow.JsonSettingsSet("info.locale", 2, "int");

                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    try
                    {
                        bClose.Content          = Lang.Set("PageSettings", "bClose", lbi.Name);
                        MainWindow.PlayBtn.Text = Lang.Set("MainProject", "bPlay", lbi.Name);
                        MainWindow.Flag.Source  = new BitmapImage(new Uri(String.Format(@"pack://application:,,,/{0};component/Resources/flag_{1}.png", (string)MainWindow.JsonSettingsGet("info.ProductName"), lbi.Name)));

                        MainWindow.LoadPage.Visibility = Visibility.Hidden;
                    }
                    catch (Exception ex) { Debugging.Save("ChangeLocale.xaml", "lbLocales_SelectionChanged", "Innter Catch", ex.Message, ex.StackTrace); }
                }));
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("ChangeLocale.xaml", "lbLocales_SelectionChanged", ex.Message, ex.StackTrace)); }
        }
コード例 #27
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                JObject obj = Lang.Translated();

                Dispatcher.BeginInvoke(new ThreadStart(delegate { lbLocales.Items.Clear(); }));

                if (obj != null)
                {
                    foreach (var lang in obj)
                    {
                        Dispatcher.BeginInvoke(new ThreadStart(delegate
                        {
                            Grid grid   = new Grid();
                            grid.Width  = double.NaN;
                            grid.Margin = new Thickness(0);
                            grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;

                            ColumnDefinition cd1 = new ColumnDefinition();
                            ColumnDefinition cd2 = new ColumnDefinition();
                            cd1.Width            = new GridLength(1, GridUnitType.Auto);
                            cd2.Width            = new GridLength(1, GridUnitType.Star);
                            grid.ColumnDefinitions.Add(cd1);
                            grid.ColumnDefinitions.Add(cd2);

                            Image img = new Image();
                            img.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                            img.VerticalAlignment   = System.Windows.VerticalAlignment.Center;
                            img.Height = 20;
                            img.Width  = 20;
                            img.Margin = new Thickness(10, 10, 5, 10);
                            img.Source = new BitmapImage(new Uri(String.Format(@"pack://application:,,,/{0};component/Resources/flag_{1}.png", (string)MainWindow.JsonSettingsGet("info.ProductName"), (string)lang.Key)));

                            TextBlock tb           = new TextBlock();
                            tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                            tb.VerticalAlignment   = System.Windows.VerticalAlignment.Center;
                            tb.Margin       = new Thickness(5, 10, 10, 10);
                            tb.TextWrapping = TextWrapping.NoWrap;
                            tb.FontWeight   = FontWeights.Bold;
                            tb.FontSize     = 14;
                            tb.Text         = ((string)lang.Value).Remove(0, 3);
                            Grid.SetColumn(tb, 1);

                            grid.Children.Add(img);
                            grid.Children.Add(tb);

                            ListBoxItem lbi       = new ListBoxItem();
                            lbi.IsSelected        = (string)lang.Key == (string)MainWindow.JsonSettingsGet("info.language");
                            lbi.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                            lbi.Cursor            = Cursors.Hand;
                            lbi.Content           = grid;
                            lbi.Name = (string)lang.Key;
                            this.RegisterName(lbi.Name, lbi);

                            lbLocales.Items.Add(lbi);
                        }));
                    }
                }
            }
            catch (Exception ex) { Debugging.Save("ChangeLocale.xaml", "Page_Loaded", ex.Message, ex.StackTrace); }

            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                try { MainWindow.LoadPage.Visibility = Visibility.Hidden; }
                catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("ChangeLocale.xaml", "Page_Loaded", ex.Message, ex.StackTrace)); }
            }));
        }
コード例 #28
0
        /// <summary>
        /// Формирование и отправка сообщения на сайт разработчика
        ///
        /// Категории ответов:
        ///     OK - Сервер дал добро на добавление записи
        ///     ANSWER - Сервер вернул текстовый результат (ответил)
        ///     Hacking attempt! - Неавторизованный доступ к серверу
        ///     BANNED - Идентификатор пользователя заблокирован
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bSend_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (tbEmail.Text.Trim().Length > 0 && tbEmail.Text.Trim().IndexOf("@") == -1)
                {
                    MessageBox.Show(Lang.Set("PageFeedback", "UncorrectEmail", lang));
                }
                else
                if (tbMessage.Text.Length >= Convert.ToInt16(Properties.Resources.Developer_Feedback_Symbols))
                {
                    if (MessageBox.Show(Lang.Set("PageFeedback", "SendNow", lang), Application.Current.GetType().Assembly.GetName().Name, MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                    {
                        Task.Factory.StartNew(() =>
                                              Dispatcher.BeginInvoke(new ThreadStart(delegate
                        {
                            string cat    = String.Empty;
                            string status = string.Empty;

                            try
                            {
                                Classes.POST POST = new Classes.POST();

                                /*
                                 *  Получаем тикет
                                 *
                                 *  api             код API
                                 *  user_id         идентификатор пользователя
                                 *  user_name       имя юзера, если авторизован
                                 *  user_email      мыло юзера, если авторизован
                                 *  modpack_type    тип мультипака
                                 *  modpack_ver     версия мультипака
                                 *  launcher        версия лаунчера
                                 *  youtube         канал ютуба (идентификатор мододела)
                                 *  lang            язык запроса
                                 *  os              версия ОС
                                 */

                                if (rbWishMultipack.IsChecked == true)
                                {
                                    cat = "WM";
                                }
                                else if (rbWishLauncher.IsChecked == true)
                                {
                                    cat = "WL";
                                }
                                else if (rbWishInstaller.IsChecked == true)
                                {
                                    cat = "WI";
                                }
                                else if (rbErrorMultipack.IsChecked == true)
                                {
                                    cat = "EM";
                                }
                                else if (rbErrorLauncher.IsChecked == true)
                                {
                                    cat = "EL";
                                }
                                else if (rbErrorInstaller.IsChecked == true)
                                {
                                    cat = "EI";
                                }

                                JObject json = new JObject(
                                    new JProperty("code", Properties.Resources.API),
                                    new JProperty("user_id", (string)MainWindow.JsonSettingsGet("info.user_id")),
                                    new JProperty("user_name", (string)MainWindow.JsonSettingsGet("info.user_name")),
                                    new JProperty("user_email", POST.Shield(tbEmail.Text.Trim())),
                                    new JProperty("modpack_type", (string)MainWindow.JsonSettingsGet("multipack.type")),
                                    new JProperty("modpack_ver", (string)MainWindow.JsonSettingsGet("multipack.version")),
                                    new JProperty("launcher", (string)MainWindow.JsonSettingsGet("info.ProductName")),
                                    new JProperty("youtube", Properties.Resources.Youtube_Channel),
                                    new JProperty("lang", lang),
                                    new JProperty("os", "disabled"),
                                    new JProperty("category", cat),
                                    new JProperty("message", POST.Shield(tbMessage.Text.Trim()))
                                    );

                                JObject answer = JObject.Parse(POST.Send(Properties.Resources.API_DEV_Address + Properties.Resources.API_DEV_Ticket, json));

                                if (answer["status"].ToString() != "FAIL" && answer["code"].ToString() == Properties.Resources.API)
                                {
                                    switch (answer["status"].ToString())
                                    {
                                    case "OK":
                                        status         = Lang.Set("PageFeedback", "OK", lang, answer["id"].ToString());
                                        tbMessage.Text = String.Empty;
                                        if (tbEmail.IsEnabled)
                                        {
                                            tbEmail.Text = String.Empty;
                                        }
                                        break;

                                    case "BANNED":
                                        status         = Lang.Set("PageFeedback", "BANNED", lang);
                                        tbMessage.Text = String.Empty;
                                        if (tbEmail.IsEnabled)
                                        {
                                            tbEmail.Text = String.Empty;
                                        }
                                        break;

                                    default:
                                        SaveTicket(json);             // Сохранение тикета для последующей отправки
                                        status = Lang.Set("PageFeedback", answer["status"].ToString(), lang) +
                                                 Lang.Set("PageFeedback", answer["content"].ToString(), lang, answer["message"].ToString());
                                        break;
                                    }
                                }
                                else
                                {
                                    SaveTicket(json);         // Сохранение тикета для последующей отправки
                                    status = Lang.Set("PageFeedback", "FAIL", lang, Lang.Set("PageFeedback", answer["content"].ToString(), lang));
                                }
                            }
                            catch (Exception ex)
                            {
                                Task.Factory.StartNew(() => Debugging.Save("Feedback.xaml", "bSend_Click()", "Intro function", ex.Message, ex.StackTrace));
                                status = Lang.Set("PageFeedback", "TICKET_ADD_ERROR", lang);
                            }

                            MessageBox.Show(status);
                        })));
                    }
                }
                else
                {
                    MessageBox.Show(Lang.Set("PageFeedback", "MinimumSymbols", lang, Properties.Resources.Developer_Feedback_Symbols));
                }
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("Feedback.xaml", "bSend_Click()", ex.Message, ex.StackTrace)); }
        }
コード例 #29
0
        /// <summary>
        /// Получаем информацию по аккаунту.
        /// Если токен активен, сразу выводим.
        /// Если нет, вначале запрашиваем авторизацию, после чего получаем информацию.
        /// </summary>
        private void AccountInfo()
        {
            // Копируем ник юзера в блок Info XML
            try
            {
                string user_name = (string)MainWindow.JsonSettingsGet("token.nickname");
                if (user_name != null && user_name != "")
                {
                    MainWindow.JsonSettingsSet("info.user_name", user_name);
                }
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Set username", ex.Message, ex.StackTrace)); }

            // Apply language
            try
            {
                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    bClose.Content = Lang.Set("PageSettings", "bClose", lang);

                    gbSostav.Header  = Lang.Set("PageUser", "tbPersonnel", lang);
                    dataonTitle.Text = Lang.Set("PageUser", "tbDataOn", lang);
                }));
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Apply language", ex.Message, ex.StackTrace)); }


            try
            {
                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    try
                    {
                        MainWindow.LoadPage.Visibility = System.Windows.Visibility.Visible;
                        Thread.Sleep(Convert.ToInt16(Properties.Resources.Default_Navigator_Sleep));

                        if (!(CheckElement("access_token") && CheckElement("expires_at") && CheckElement("nickname") && CheckElement("account_id")))
                        {
                            try
                            {
                                MainWindow.JsonSettingsRemove("token");
                                MainWindow.Navigator();
                            }
                            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Token is FAIL", ex.Message, ex.StackTrace)); }
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(new ThreadStart(delegate
                            {
                                try
                                {
                                    nickname     = (string)MainWindow.JsonSettingsGet("token.nickname");
                                    account_id   = (string)MainWindow.JsonSettingsGet("token.account_id");
                                    access_token = (string)MainWindow.JsonSettingsGet("token.access_token");

                                    PlayerName.Text = nickname;

                                    JObject JAccountInfo = WarAPI.AccountInfo(account_id, access_token);
                                    JObject
                                    Clan      = null,
                                    Battles   = null,
                                    Provinces = null;


                                    if ((string)JAccountInfo.SelectToken("status") == "ok")
                                    {
                                        /* =========================================
                                         *       Проверяем клан
                                         *       Если параметр пуст - деактивируем вкладки
                                         * =========================================*/
                                        try
                                        {
                                            if (JAccountInfo.SelectToken(String.Format("data.{0}.clan_id", account_id)) == null)
                                            {
                                                tiClanInfo.IsEnabled      = false;
                                                tiClanBattles.IsEnabled   = false;
                                                tiClanProvinces.IsEnabled = false;
                                            }
                                            else
                                            {
                                                //obj["data"]["2732865"]["clan_id"] = 60118; // Подставной клан
                                                clan_id = (string)JAccountInfo.SelectToken(String.Format("data.{0}.clan_id", account_id));

                                                Clan      = WarAPI.ClanInfo(clan_id, access_token);
                                                Battles   = WarAPI.ClanBattles(clan_id, access_token);
                                                Provinces = WarAPI.ClanProvinces(clan_id, access_token, "type,name,arena_i18n,prime_time,revenue,occupancy_time,attacked");
                                            }
                                        }
                                        catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Check Clan", ex.Message, ex.StackTrace)); }


                                        /* =========================================
                                         *       Общая информация о пользователе
                                         * =========================================*/
                                        try
                                        {
                                            if ((string)Clan.SelectToken("status") == "ok")
                                            {
                                                DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                                                dt          = dt.AddSeconds((double)Clan.SelectToken(String.Format("data.{0}.members.{1}.created_at", clan_id, account_id)));
                                                TimeSpan ts = DateTime.Now - dt;

                                                PlayerClan.Text = "[" + (string)Clan.SelectToken(String.Format("data.{0}.abbreviation", clan_id)) + "]";

                                                PlayerClan2.Text  = (string)Clan.SelectToken(String.Format("data.{0}.name", clan_id));
                                                ClanFullname.Text = PlayerClan2.Text;

                                                PlayerZvanie.Text = Lang.Set("Rank", (string)Clan.SelectToken(String.Format("data.{0}.members.{1}.role", clan_id, account_id)), lang);

                                                BitmapImage bitmap = new BitmapImage();
                                                bitmap.BeginInit();
                                                bitmap.UriSource = new Uri((string)Clan.SelectToken(String.Format("data.{0}.emblems.medium", clan_id)), UriKind.Absolute);
                                                bitmap.EndInit();

                                                ClanEmblem.Source  = bitmap;
                                                ClanEmblem2.Source = bitmap;
                                            }
                                            else
                                            {
                                                PlayerClan2.Text  = Lang.Set("PageUser", "NotClan", lang);
                                                PlayerZvanie.Text = String.Empty;
                                            }

                                            // Процент побед
                                            PercWins.Text     = Lang.Set("PageUser", "tbPercentWins", lang);
                                            PercWinsPerc.Text = (Math.Round(((double)JAccountInfo.SelectToken(String.Format("data.{0}.statistics.all.wins", account_id)) / (double)JAccountInfo.SelectToken(String.Format("data.{0}.statistics.all.battles", account_id))) * 100, 2)).ToString();

                                            // Личный рейтинг
                                            MyRating.Text     = Lang.Set("PageUser", "tbMyRating", lang);
                                            MyRatingPerc.Text = SetSumm((string)JAccountInfo.SelectToken(String.Format("data.{0}.global_rating", account_id)));

                                            // Средний опыт за бой
                                            AvgXP.Text     = Lang.Set("PageUser", "tbAvgXP", lang);
                                            AvgXPPerc.Text = SetSumm((string)JAccountInfo.SelectToken(String.Format("data.{0}.statistics.all.battle_avg_xp", account_id)));

                                            // Количество боев
                                            BattleCount.Text     = Lang.Set("PageUser", "tbCountWars", lang);
                                            BattleCountPerc.Text = SetSumm((string)JAccountInfo.SelectToken(String.Format("data.{0}.statistics.all.battles", account_id)));

                                            // Средний нанесенный урон за бой
                                            AvgDamage.Text     = Lang.Set("PageUser", "tbAvgDamage", lang);
                                            AvgDamagePerc.Text = SetSumm((string)JAccountInfo.SelectToken(String.Format("data.{0}.statistics.all.avg_damage_assisted", account_id)));
                                        }
                                        catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "User Info", ex.Message, ex.StackTrace)); }

                                        try
                                        {
                                            PlayerGold.Text     = SetSumm((string)JAccountInfo.SelectToken(String.Format("data.{0}.private.gold", account_id)));
                                            PlayerCredit.Text   = SetSumm((string)JAccountInfo.SelectToken(String.Format("data.{0}.private.credits", account_id)));
                                            PlayerXP.Text       = SetSumm((string)JAccountInfo.SelectToken(String.Format("data.{0}.private.free_xp", account_id)));
                                            iAccountType.Source = new BitmapImage(new Uri(String.Format(@"pack://application:,,,/{0};component/Resources/{1}", (string)MainWindow.JsonSettingsGet("info.ProductName"), (bool)JAccountInfo.SelectToken(String.Format("data.{0}.private.is_premium", account_id)) ? "ico-account-premium.png" : "ico-account-base.png")));

                                            iAccountType.ToolTip = Lang.Set("Global", (bool)JAccountInfo.SelectToken(String.Format("data.{0}.private.is_premium", account_id)) ? "IsPremium" : "IsBase", lang);
                                        }
                                        catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "User Credits", ex.Message, ex.StackTrace)); }

                                        /*Batles.Text = SelectToken(obj, "statistics.all.battles");
                                         * Wins.Text = SelectToken(obj, "statistics.all.wins");
                                         * Loss.Text = SelectToken(obj, "statistics.all.losses");
                                         *
                                         * WinsPercent.Text = (Math.Round(((Convert.ToDouble(SelectToken(obj, "statistics.all.wins")) / Convert.ToDouble(SelectToken(obj, "statistics.all.battles"))) * 100), 2)).ToString();
                                         * LossPercent.Text = (Math.Round(((Convert.ToDouble(SelectToken(obj, "statistics.all.losses")) / Convert.ToDouble(SelectToken(obj, "statistics.all.battles"))) * 100), 2)).ToString();
                                         * WhoPercent.Text = (Math.Round(((Convert.ToDouble(SelectToken(obj, "statistics.all.draws")) / Convert.ToDouble(SelectToken(obj, "statistics.all.battles"))) * 100), 2)).ToString();
                                         *
                                         * AvgXP.Text = SelectToken(obj, "statistics.all.battle_avg_xp");*/


                                        /*
                                         *   ГРАФИК
                                         */
                                        /*try
                                         * {
                                         *  this.DataContext = new ObservableCollection<AssetClass>(AssetClass.ConstructTestData(new JObject(
                                         *      new JProperty("wins",
                                         *          new JObject(
                                         *              new JProperty("name", "Победы"),
                                         *              new JProperty("total", Convert.ToInt16(SelectToken(obj, "statistics.all.wins")))
                                         *          )
                                         *      ),
                                         *      new JProperty("losses",
                                         *          new JObject(
                                         *              new JProperty("name", "Поражения"),
                                         *              new JProperty("total", Convert.ToInt16(SelectToken(obj, "statistics.all.losses")))
                                         *          )
                                         *      ),
                                         *      new JProperty("draws",
                                         *          new JObject(
                                         *              new JProperty("name", "Ничьи"),
                                         *              new JProperty("total", Convert.ToInt16(SelectToken(obj, "statistics.all.draws")))
                                         *          )
                                         *      )
                                         *  )));
                                         * }
                                         * catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Graphic", ex.Message, ex.StackTrace)); }
                                         */



                                        /* =========================================
                                         *       Общая информация о клане
                                         * =========================================*/
                                        if (Clan != null)
                                        {
                                            try
                                            {
                                                ClanDesc.Text  = (string)Clan.SelectToken(String.Format("data.{0}.motto", clan_id));
                                                ClanCount.Text = (string)Clan.SelectToken(String.Format("data.{0}.members_count", clan_id));

                                                dataonTitle.Text = Lang.Set("PageUser", "tbDataOn", lang);
                                                dataon.Text      = DateFormat((double)Clan.SelectToken(String.Format("data.{0}.updated_at", clan_id)));
                                            }
                                            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Clan", ex.Message, ex.StackTrace)); }


                                            /* =========================================
                                             *       Члены клана
                                             * =========================================*/
                                            try
                                            {
                                                ClanMembers.Items.Clear();
                                                int i = 1;

                                                foreach (var member in (JObject)Clan.SelectToken(String.Format("data.{0}.members", clan_id)))
                                                {
                                                    Grid gr = new Grid();
                                                    gr.SetResourceReference(Grid.StyleProperty, "GridW470");

                                                    ColumnDefinition cd1 = new ColumnDefinition();
                                                    ColumnDefinition cd2 = new ColumnDefinition();
                                                    ColumnDefinition cd3 = new ColumnDefinition();
                                                    ColumnDefinition cd4 = new ColumnDefinition();

                                                    cd1.Width = new GridLength(30, GridUnitType.Auto);
                                                    cd2.Width = new GridLength(1, GridUnitType.Star);
                                                    cd3.Width = new GridLength(130, GridUnitType.Auto);
                                                    cd4.Width = new GridLength(80, GridUnitType.Auto);

                                                    gr.ColumnDefinitions.Add(cd1);
                                                    gr.ColumnDefinitions.Add(cd2);
                                                    gr.ColumnDefinitions.Add(cd3);
                                                    gr.ColumnDefinitions.Add(cd4);

                                                    TextBlock tbID = new TextBlock();
                                                    tbID.Text      = (i++).ToString();
                                                    tbID.SetResourceReference(TextBlock.StyleProperty, "CmID");
                                                    Grid.SetColumn(tbID, 0);

                                                    TextBlock CmName = new TextBlock();
                                                    CmName.Text      = (string)member.Value["account_name"];
                                                    CmName.SetResourceReference(TextBlock.StyleProperty, "CmName");
                                                    Grid.SetColumn(CmName, 1);

                                                    TextBlock CmTitle = new TextBlock();
                                                    CmTitle.Text      = Lang.Set("Rank", (string)member.Value["role"], lang);
                                                    CmTitle.SetResourceReference(TextBlock.StyleProperty, "CmTitle");
                                                    Grid.SetColumn(CmTitle, 2);

                                                    TextBlock CmDate = new TextBlock();
                                                    CmDate.Text      = DateFormat((double)member.Value["created_at"]);
                                                    CmDate.SetResourceReference(TextBlock.StyleProperty, "CmDate");
                                                    Grid.SetColumn(CmDate, 3);

                                                    gr.Children.Add(tbID);
                                                    gr.Children.Add(CmName);
                                                    gr.Children.Add(CmTitle);
                                                    gr.Children.Add(CmDate);


                                                    ListBoxItem lbi = new ListBoxItem();
                                                    lbi.SetResourceReference(ListBoxItem.StyleProperty, "lbiProcess");
                                                    lbi.Content = gr;

                                                    ClanMembers.Items.Add(lbi);
                                                }
                                            }
                                            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Clan members", ex.Message, ex.StackTrace)); }



                                            /* =========================================
                                             *       Бои клана
                                             * =========================================*/
                                            try
                                            {
                                                tbBattles.Text = Lang.Set("PageUser", "tbBattles", lang);

                                                if ((string)Battles.SelectToken("status") == "ok")
                                                {
                                                    JArray arr = (JArray)Battles.SelectToken("data." + clan_id);

                                                    if (arr.Count > 0)
                                                    {
                                                        ClanBattles.Items.Clear();

                                                        foreach (var battle in arr)
                                                        {
                                                            /*
                                                             * Тип
                                                             * Время
                                                             * Провинция
                                                             * Игровая карта
                                                             *
                                                             * Тип боя:
                                                             *       for_province — бой за провинцию;
                                                             *       meeting_engagement — встречный бой;
                                                             *       landing — бой за высадку.
                                                             */
                                                            //JObject GlobalProvinces = WarAPI.GlobalProvinces((string)battle["provinces"][0]);


                                                            Grid gr = new Grid();
                                                            gr.SetResourceReference(Grid.StyleProperty, "ClanBattlesGrid");

                                                            ColumnDefinition cd1 = new ColumnDefinition();
                                                            ColumnDefinition cd2 = new ColumnDefinition();
                                                            ColumnDefinition cd3 = new ColumnDefinition();
                                                            ColumnDefinition cd4 = new ColumnDefinition();

                                                            cd1.Width = new GridLength(1, GridUnitType.Auto);
                                                            //cd2.Width = new GridLength(250, GridUnitType.Pixel);
                                                            cd3.Width = new GridLength(1, GridUnitType.Auto);
                                                            cd4.Width = new GridLength(1, GridUnitType.Auto);

                                                            gr.ColumnDefinitions.Add(cd1);
                                                            gr.ColumnDefinitions.Add(cd2);
                                                            gr.ColumnDefinitions.Add(cd3);
                                                            gr.ColumnDefinitions.Add(cd4);

                                                            Image im = new Image();
                                                            im.SetResourceReference(Image.StyleProperty, "Icon_" + (string)battle["type"]);

                                                            TextBlock tbID = new TextBlock();
                                                            tbID.Text      = DateFormat((double)battle["time"], "HH:mm");
                                                            tbID.SetResourceReference(TextBlock.StyleProperty, "CmTIME");
                                                            Grid.SetColumn(tbID, 3);

                                                            TextBlock CmName = new TextBlock();
                                                            //CmName.Text = SelectTokenNoClan(GlobalProvinces, (string)battle["provinces"][0] + ".province_i18n");
                                                            CmName.Text = (string)battle["provinces_i18n"][0]["name_i18n"];
                                                            CmName.SetResourceReference(TextBlock.StyleProperty, "CmName");
                                                            Grid.SetColumn(CmName, 1);

                                                            TextBlock CmTitle = new TextBlock();
                                                            CmTitle.Text      = (string)battle["arenas"][0]["name_i18n"];
                                                            CmTitle.SetResourceReference(TextBlock.StyleProperty, "CmTitle");
                                                            Grid.SetColumn(CmTitle, 2);

                                                            gr.Children.Add(im);
                                                            gr.Children.Add(tbID);
                                                            gr.Children.Add(CmName);
                                                            gr.Children.Add(CmTitle);

                                                            ListBoxItem lbi         = new ListBoxItem();
                                                            lbi.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                                                            lbi.SetResourceReference(Grid.StyleProperty, "ClanBattles");
                                                            lbi.Content = gr;

                                                            ClanBattles.Items.Add(lbi);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //ClanBattlesNoRecords.Text = Lang.Set("PageUser", "ClanBattlesNoRecords", lang);

                                                        ListBoxItem lbi = new ListBoxItem();
                                                        lbi.SetResourceReference(ListBoxItem.StyleProperty, "rec_not_found");

                                                        TextBlock tb = new TextBlock();
                                                        tb.Text      = Lang.Set("PageUser", "ClanBattlesNoRecords", lang);

                                                        lbi.Content = tb;

                                                        ClanBattles.Items.Clear();
                                                        ClanBattles.Items.Add(lbi);
                                                    }
                                                }
                                            }
                                            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Clan battles", ex.Message, ex.StackTrace)); }


                                            /*
                                             *       Провинции клана
                                             *
                                             * Тип:
                                             *   Стартовая
                                             *   Обычная
                                             *   Ключевая
                                             * Название
                                             * Игровая карта
                                             * Прайм-тайм
                                             * Доход
                                             * Время владения
                                             * Провинция атакована
                                             *
                                             * type
                                             * name
                                             * arena_i18n
                                             * prime_time
                                             * revenue
                                             * occupancy_time
                                             * attacked
                                             */
                                            try
                                            {
                                                tbProvinces.Text = Lang.Set("PageUser", "tbProvinces", lang);

                                                if ((string)Provinces.SelectToken("status") == "ok")
                                                {
                                                    JObject arr = (JObject)Provinces["data"];
                                                    if (arr.Count > 0)
                                                    {
                                                        ClanProvinces.Items.Clear();

                                                        foreach (var province in arr)
                                                        {
                                                            Grid gr = new Grid();
                                                            gr.SetResourceReference(Grid.StyleProperty, "ClanBattlesGrid");

                                                            ColumnDefinition cd1 = new ColumnDefinition();
                                                            ColumnDefinition cd2 = new ColumnDefinition();
                                                            ColumnDefinition cd3 = new ColumnDefinition();
                                                            ColumnDefinition cd4 = new ColumnDefinition();
                                                            ColumnDefinition cd5 = new ColumnDefinition();
                                                            ColumnDefinition cd6 = new ColumnDefinition();
                                                            ColumnDefinition cd7 = new ColumnDefinition();

                                                            cd1.Width = new GridLength(1, GridUnitType.Auto);
                                                            //cd2.Width = new GridLength(1, GridUnitType.Auto);
                                                            cd3.Width = new GridLength(1, GridUnitType.Auto);
                                                            cd4.Width = new GridLength(50, GridUnitType.Pixel);
                                                            cd5.Width = new GridLength(1, GridUnitType.Auto);
                                                            cd6.Width = new GridLength(50, GridUnitType.Pixel);

                                                            gr.ColumnDefinitions.Add(cd1);
                                                            gr.ColumnDefinitions.Add(cd2);
                                                            gr.ColumnDefinitions.Add(cd3);
                                                            gr.ColumnDefinitions.Add(cd4);
                                                            gr.ColumnDefinitions.Add(cd5);
                                                            gr.ColumnDefinitions.Add(cd6);

                                                            Image im = new Image();
                                                            im.SetResourceReference(Image.StyleProperty, "province_types_" + (string)province.Value["type"]);

                                                            TextBlock t1 = new TextBlock();
                                                            t1.Text      = (string)province.Value["name"];
                                                            t1.SetResourceReference(TextBlock.StyleProperty, "t1");
                                                            Grid.SetColumn(t1, 1);

                                                            TextBlock t2 = new TextBlock();
                                                            t2.Text      = (string)province.Value["arena_i18n"];
                                                            t2.SetResourceReference(TextBlock.StyleProperty, "t2");
                                                            Grid.SetColumn(t2, 2);

                                                            TextBlock t3 = new TextBlock();
                                                            t3.Text      = DateFormat((double)province.Value["prime_time"], "HH:mm");
                                                            t3.SetResourceReference(TextBlock.StyleProperty, "t3");
                                                            Grid.SetColumn(t3, 3);

                                                            TextBlock t4 = new TextBlock();
                                                            t4.Text      = (string)province.Value["revenue"];
                                                            t4.SetResourceReference(TextBlock.StyleProperty, "t4");
                                                            Grid.SetColumn(t4, 4);

                                                            TextBlock t5 = new TextBlock();
                                                            t5.Text      = (string)province.Value["occupancy_time"];
                                                            t5.SetResourceReference(TextBlock.StyleProperty, "t5");
                                                            Grid.SetColumn(t5, 5);

                                                            gr.Children.Add(im);
                                                            gr.Children.Add(t1);
                                                            gr.Children.Add(t2);
                                                            gr.Children.Add(t3);
                                                            gr.Children.Add(t4);
                                                            gr.Children.Add(t5);

                                                            ListBoxItem lbi         = new ListBoxItem();
                                                            lbi.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                                                            lbi.SetResourceReference(ListBoxItem.StyleProperty, (bool)province.Value["attacked"] ? "ClanProvincesAttacked" : "ClanProvincesNonAttacked");
                                                            lbi.Content = gr;

                                                            ClanProvinces.Items.Add(lbi);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //ClanProvincesNoRecords.Text = Lang.Set("PageUser", "ClanProvincesNoRecords", lang);

                                                        ListBoxItem lbi = new ListBoxItem();
                                                        lbi.SetResourceReference(ListBoxItem.StyleProperty, "rec_not_found");

                                                        TextBlock tb = new TextBlock();
                                                        tb.Text      = Lang.Set("PageUser", "ClanProvincesNoRecords", lang);

                                                        lbi.Content = tb;

                                                        ClanProvinces.Items.Clear();
                                                        ClanProvinces.Items.Add(lbi);
                                                    }
                                                }
                                            }
                                            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "Clan provincies", ex.Message, ex.StackTrace)); }
                                        }
                                    }
                                    else
                                    {
                                        MainWindow.JsonSettingsRemove("token");

                                        switch ((string)JAccountInfo.SelectToken("error.message"))
                                        {
                                        case "INVALID_ACCESS_TOKEN": MessageBox.Show(Lang.Set("PageUser", "ActivateWarID", lang)); break;

                                        default: MessageBox.Show(Lang.Set("PageUser", "ErrorDataJson", lang)); break;
                                        }

                                        try { MainWindow.Navigator(); }
                                        catch (Exception) { }
                                    }
                                }
                                catch (Exception e) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", "if (!active)", e.Message, e.StackTrace)); }
                            }));
                        }
                    }
                    catch (Exception e) { Task.Factory.StartNew(() => Debugging.Save("UserProfile.xaml", "AccountInfo()", e.Message, e.StackTrace)); }
                    finally
                    {
                        MainWindow.LoadPage.Visibility = System.Windows.Visibility.Hidden;
                        Thread.Sleep(Convert.ToInt16(Properties.Resources.Default_Navigator_Sleep));
                    }
                }));
            }
            catch (Exception) { }
        }
コード例 #30
0
        public Donate()
        {
            InitializeComponent();

            Task.Factory.StartNew(() => { Dispatcher.BeginInvoke(new ThreadStart(delegate { bClose.Content = new Classes.Language().Set("Button", "Close", (string)MainWindow.JsonSettingsGet("info.language")); })); });
        }