Ejemplo n.º 1
0
        private void Mouse_Click(object sender, MouseEventArgs e)
        {
            ;

            if (wybranyItem == Item.pipeta) //nie da się pobrać koloru bezpośrednio, dlatego trzeba zrobić screena
            {                               // robi zrzut ekranu (prostokątna bitmapa będąca kopią przestrzeni rysowania)
                Bitmap    bmp  = new Bitmap(PB.Width, PB.Height);
                Graphics  g    = Graphics.FromImage(bmp);
                Rectangle rect = PB.RectangleToScreen(PB.ClientRectangle);
                g.CopyFromScreen(rect.Location, Point.Empty, PB.Size);
                g.Dispose();

                maluj_kolor             = bmp.GetPixel(e.X, e.Y);
                wybrany_kolor.BackColor = maluj_kolor;
            }
            if (wybranyItem == Item.tekst)
            {
                Bitmap imgbmp = copy.Clone() as Bitmap;

                Graphics tk = Graphics.FromImage(imgbmp);

                int xx = e.X;
                int yy = e.Y;


                tk.DrawString(textBox1.Text, new Font(toolStripComboBox1.Text, Convert.ToInt32(toolStripTextBox1.Text), FontStyle.Regular), new SolidBrush(maluj_kolor), new PointF(e.X - Convert.ToInt32(toolStripTextBox1.Text), e.Y - Convert.ToInt32(toolStripTextBox1.Text)));
                tk.Dispose();
                PB.Image = imgbmp;
            }
        }
Ejemplo n.º 2
0
    IEnumerator ClimbLadder()
    {
        PB.StartCoroutine(PB.StunCoroutine(upClimbTime));
        Vector3 oPos         = Body.position;
        Vector3 targetMidPos = Vector3.Lerp(oPos, currentLadder.ClimbPosition, 0.5f);
        Vector3 targetPos    = currentLadder.ClimbPosition;

        float count = 0f;

        while (count < upClimbTime * 0.5f)
        {
            Body.position = Vector3.Lerp(oPos, targetMidPos, Mathf.Pow(count / (upClimbTime * 0.5f), upClimbStartLinearity));
            Body.position = Body.position.SetY(Utilities.Lerp(oPos.y, targetPos.y, Mathf.Pow(count / upClimbTime, 0.5f)));

            yield return(null);

            count += Time.deltaTime;
        }
        count -= upClimbTime * 0.5f;
        while (count < upClimbTime * 0.5f)
        {
            Body.position = Vector3.Lerp(targetMidPos, targetPos, Mathf.Pow(count / (upClimbTime * 0.5f), upClimbEndLinearity));
            Body.position = Body.position.SetY(Utilities.Lerp(oPos.y, targetPos.y, Mathf.Pow((count + upClimbTime * 0.5f) / upClimbTime, 0.5f)));

            yield return(null);

            count += Time.deltaTime;
        }

        Body.position = targetPos;
        GiveUpLadder();
    }
Ejemplo n.º 3
0
        private string GetEntry(int value, bool sjis, bool SaveLoad)
        {
            foreach (var text in Source.Entries)
            {
                if (value.ToString() == text.Context)
                {
                    string replaced = string.IsNullOrEmpty(text.Translated) ?
                                      text.Original : text.Translated;
                    if (PB.BP.DictionaryEnabled && !SaveLoad)
                    {
                        replaced = PB.BP.ReplaceText(replaced, false);
                    }

                    if (sjis)
                    {
                        return(ReplaceText(PB.ToFullWidth(replaced), true));
                    }

                    if (DictionarySaveLoadEnabled && SaveLoad)
                    {
                        replaced = ReplaceSaveLoadText(replaced, true);
                    }

                    return(ReplaceText(replaced, true));
                }
            }
            return(null);
        }
Ejemplo n.º 4
0
        // StringBuilder sb = new StringBuilder();
        // ERROR: Handles clauses are not supported in C#
        private void UpdaterCommunication_BytesRecievedAsync(object sender, BytesRecievedEventArgs e)
        {
            DataStream Buffer = new DataStream(e.Bytes);

            /*sb.Clear();
             * for (int i = 0; i < e.Bytes.Length; i++)
             * {
             *  sb.Append(e.Bytes[i] + ",");
             * }
             * Console.WriteLine(sb.ToString());*/
            while (Buffer.BytesLeft > 0)
            {
                PB.AppendBytes(Buffer);
                if (PB.State == TCPPacketBuilder.PacketState.Complete)
                {
                    var dgram = PB.GetPacketDgram();


                    OnPacketRecievedAsync(null, new PacketRecievedEventArgs(dgram, TempEndPoint));
                }
                else
                {
                    break; // TODO: might not be correct. Was : Exit Do
                }
            }
        }
Ejemplo n.º 5
0
        private void phòngBanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
            PB pb = new PB();

            pb.Visible = true;
        }
Ejemplo n.º 6
0
 virtual public void RecompilePBs()
 {
     foreach (IMyProgrammableBlock PB in Term.GetBlocksOfType <IMyProgrammableBlock>())
     {
         PB.Recompile();
     }
 }
Ejemplo n.º 7
0
        public void SendPacket(byte[] dgram, TCPPacketBuilder.TCPPacketFlags Flags)
        {
            byte[] bytes = PB.BuildPacket(dgram, Flags);


            SendPacket(bytes, TempEndPoint);
        }
Ejemplo n.º 8
0
    public PB Add <PB>() where PB : PlayerBehaviour, new()
    {
        PB pb = PlayerBehavioursStorer.Instance.Get <PB>();

        base.Add(pb);
        return(pb);
    }
Ejemplo n.º 9
0
        private CookieContainer GetCookie(string loginPage, string accountNumber, string username, string password)
        {
            string reqString = "AccountNumber=" + accountNumber + "&UserName="******"&Password="******"POST";
                request.ContentType     = "application/x-www-form-urlencoded";
                request.ContentLength   = data.Length;

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                Errors.LoginPageError(ex);
                PB.Close();
            }
            return(cookieContainer);
        }
Ejemplo n.º 10
0
        private CookieContainer GetCookie(string loginPage, string username, string password)
        {
            try
            {
                cd.Url = loginPage;
                IWebElement element;

                element = cd.FindElement(By.Id("_username"));
                element.SendKeys(username);
                element = cd.FindElement(By.Id("_password"));
                element.SendKeys(password);

                element = cd.FindElement(By.XPath("//*[@class = 'btn btn-success']"));
                element.Click();

                foreach (OpenQA.Selenium.Cookie c in cd.Manage().Cookies.AllCookies)
                {
                    string name  = c.Name;
                    string value = c.Value;
                    cookieContainer.Add(new System.Net.Cookie(name, value, c.Path, c.Domain));
                }
                cd.Quit();
            }
            catch (Exception ex)
            {
                cd.Quit();
                PB.Close();
                Errors.LoginPageError(ex);
            }
            return(cookieContainer);
        }
Ejemplo n.º 11
0
        public void SpisokView(ICollectionView SpisokFiltered)
        {
            int vacCount = SpisokFiltered.Cast <object>().Count();

            VacancyCount.Content = vacCount;

            if (vacCount != 0)
            {
                SC.Post(new SendOrPostCallback(o => { PB.Value = 0; PB.Maximum = 100; }), 2);
                SC.Post(new SendOrPostCallback(o => { PBtext.Text = ""; }), 2);
                SC.Post(new SendOrPostCallback(o => { PB.Refresh(); }), 2);
                MyGrid.ItemsSource = SpisokFiltered;
                MyGrid.RowHeight   = 20;
                Button1.IsEnabled  = true;
                Button4.IsEnabled  = true;
                Button5.IsEnabled  = true;
                Button3.IsEnabled  = true;
                Button6.IsEnabled  = false;
            }

            //MyGrid.ItemsSource = null;
            //MyGrid.Refresh();
            //this.DataContext = Spisok;
            //if (MyGrid.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            //{
            //    var row = (DataGridRow)MyGrid.ItemContainerGenerator.ContainerFromIndex(1);
            //    row.Background = Brushes.Red;
            //    //foreach (var dataItem in DisplayDataGrid.ItemsSource)
            //    //{
            //    //    var gridRow = DisplayDataGrid.ItemContainerGenerator.ContainerFromItem(dataItem) as DataGridRow;
            //    //}
            //    //DataGridRow rowColor = (DataGridRow)dataGridViewMyGroups.ItemContainerGenerator.ContainerFromIndex(number);
            //    //row.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(223, 227, 238));
            //}
        }
Ejemplo n.º 12
0
        public void AutoImplementStubProperty()
        {
            Type        tA = typeof(PA);
            TypeBuilder bA = CreateTypeBuilder(tA);

            EmitHelper.ImplementStubProperty(bA, tA.GetProperty("PublicWriteableValue"), true);
            EmitHelper.ImplementStubProperty(bA, tA.GetProperty("ProtectedWriteableValue"), true);
            Type builtTypeA = bA.CreateTypeInfo().AsType();
            PA   oA         = (PA)Activator.CreateInstance(builtTypeA);

            oA.PublicWriteableValue = 4548;
            oA.SetProtectedValues(2121);
            Assert.That(oA.PublicWriteableValue, Is.EqualTo(4548));
            Assert.That(oA.ProtectedWriteableValue, Is.EqualTo(2121));

            Type        tB = typeof(PB);
            TypeBuilder bB = CreateTypeBuilder(tB);

            EmitHelper.ImplementStubProperty(bB, tB.GetProperty("PublicWriteableValue"), true);
            EmitHelper.ImplementStubProperty(bB, tB.GetProperty("ProtectedWriteableValue"), true);
            Type builtTypeB = bB.CreateTypeInfo().AsType();
            PB   oB         = (PB)Activator.CreateInstance(builtTypeB);

            oB.PublicWriteableValue = 4548;
            oB.SetProtectedValues(2121);
            Assert.That(oB.PublicWriteableValue, Is.EqualTo(4548));
            Assert.That(oB.ProtectedWriteableValue, Is.EqualTo(2121));
            Assert.That(oB.PublicProperty, Is.EqualTo(2121 % 255));
        }
Ejemplo n.º 13
0
 private void RecompilePBs()
 {
     foreach (IMyProgrammableBlock PB in Grid.GetTerminalSystem().GetBlocksOfType <IMyProgrammableBlock>())
     {
         PB.Recompile();
     }
 }
Ejemplo n.º 14
0
        private void Button_Clear_Click(object sender, RoutedEventArgs e)
        {
            int Buf = Convert.ToInt16(textBlock1.Text);

            Buf++;
            textBlock1.Text = Buf.ToString();
            PB.Clear();
        }
Ejemplo n.º 15
0
        public void PB_Update(MyEventArgs e)
        {
            //Application.Current.Dispatcher.BeginInvoke(new Action(() => { PB.Value = e.Value; PB.Maximum = e.MaxValue; }));
            SC.Post(new SendOrPostCallback(o => { PB.Value = e.Value; PB.Maximum = e.MaxValue; }), e);
            SC.Post(new SendOrPostCallback(o => { PBtext.Text = e.Value + " (" + e.Value2 + ") / " + e.MaxValue; }), e);
            SC.Post(new SendOrPostCallback(o => { PB.Refresh(); }), e);

            //synchronizationContext.Post(new SendOrPostCallback(o => {MyGrid.ItemsSource = Spisok;}),Spisok);
        }
Ejemplo n.º 16
0
        private void PB_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Duration duration = new Duration(TimeSpan.FromSeconds(1));

            aMedia.Position += TimeSpan.FromSeconds(10);
            DoubleAnimation d = new DoubleAnimation(PB.Value + 10, duration);

            PB.BeginAnimation(ProgressBar.ValueProperty, d);
        }
Ejemplo n.º 17
0
        private void phòngBanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PB pb = new PB();

            panelMain.Controls.Clear();

            pb.Dock = DockStyle.Fill;
            panelMain.Controls.Add(pb);
            pb.Show();
        }
Ejemplo n.º 18
0
 public CastSpellAction(Recipe recipe, int repeat, RepeatCalculationType repeatType)
     : this()
 {
     Recipe     = recipe;
     Repeat     = new DynamicProperty <int>("Repeat", this, repeat.ToString(CultureInfo.InvariantCulture));
     Entry      = new DynamicProperty <uint>("Entry", this, recipe.SpellId.ToString(CultureInfo.InvariantCulture));
     RepeatType = repeatType;
     //Properties["Recipe"].Show = true;
     Properties["SpellName"].Value = SpellName;
     PB.UpdateMaterials();
 }
Ejemplo n.º 19
0
        public MainWindow()
        {
            InitializeComponent();
            Binding b = new Binding();

            b.Source = sl;
            b.Path   = new PropertyPath("Value");


            PB.SetBinding(ProgressBar.ValueProperty, b);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Base constructor
        /// </summary>
        public SplashScreenForm()
        {
            InitializeComponent();
            this.labelMessage.Parent    = this.SplashView;
            this.labelMessage.BackColor = Color.Transparent;
            labelMessage.ForeColor      = Color.Green;

            //this.progressBar1.Parent = this.pictureBox1;
            //this.progressBar1.BackColor = Color.Transparent;

            PB.Show();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Событие нажатия на PictureBox
        /// </summary>
        public void CellClick(object sender, EventArgs e)
        {
            //Представление PictureBox-а как объекта PB
            PB cell = sender as PB;

            //Извлечение из ячейки её координат
            int X = cell.X;
            int Y = cell.Y;


            if (IsSoomeSelected)            //Если какая-то ячейка уже выбрана...
            {
                if (Cells[X, Y].IsSelected) //...отменить выбор
                {
                    CellSelection(Cells[X, Y]);
                }
                else if (CellsComparison(Cells[X, Y], Cells[SelectedCellX, SelectedCellY]))//...убрать обе ячейки
                {
                    DeleteCell(Cells[X, Y]);
                    DeleteCell(Cells[SelectedCellX, SelectedCellY]);
                    IsSoomeSelected = false;
                }
            }
            else//Иначе - выбрать ячейку
            {
                CellSelection(Cells[X, Y]);
            }

            //Нахождение и открытие ячеек
            UnlockCheck();

            //Проверка победы
            if (WinCheck())
            {
                MessageBox.Show("Вы победили", "Победа!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                RandomizeDominos();
                StartGame();
            }

            //Проверка поражения
            if (LosingCheck())
            {
                MessageBox.Show("Вы проиграли", "Поражение", MessageBoxButtons.OK, MessageBoxIcon.Information);

                RandomizeDominos();
                StartGame();
            }

            //Вывод информации о кол-ве ячеек на форму
            GetCells();
        }
Ejemplo n.º 22
0
 private void trackBar1_Scroll(object sender, EventArgs e)
 {
     k = trackBar1.Value / 10.0;
     g.Clear(Color.White);
     S = new Point(PB.Width / 10, 4 * PB.Height / 5);
     for (int i = 0; i <= gear; i++)
     {
         DrawST(g, p, i);
     }
     p.Color = Color.Red;
     if (gear >= 0)
     {
         g.DrawLine(p, S.X, S.Y - (int)(k * P.l2[gear] / 2), S.X - (int)(k * (P.B2[gear] + P.S2[gear] + P.B1[gear] + P.sd[gear])) * (gear + 1), S.Y - (int)(k * P.l1[0] / 2));
     }
     PB.Refresh();
 }
Ejemplo n.º 23
0
        private CookieContainer GetCookie(string loginPage, string accountNumber, string username, string password)
        {
            // Сначала получаем токен:
            request = (HttpWebRequest)WebRequest.Create(loginPage);
            request.CookieContainer = cookieContainer;

            response = (HttpWebResponse)request.GetResponse();
            sr       = new StreamReader(response.GetResponseStream());
            string pageSource = sr.ReadToEnd();

            string searchWord = "name=\"cmsauthenticitytoken\" value=\"";
            string token      = pageSource.Substring(pageSource.IndexOf(searchWord) + searchWord.Length);

            token = token.Remove(token.IndexOf("\""));
            //==================================================================================================

            string reqString =
                "module_fnc%5Bprimary%5D=Login&sSuccessURL=&sFailureURL=&sConsumer=loginBox"
                + "&customerNumber=" + accountNumber
                + "&slogin="******"&password="******"&cmsauthenticitytoken=" + token;

            byte[] data = Encoding.UTF8.GetBytes(reqString);
            try
            {
                request = (HttpWebRequest)WebRequest.Create(loginPage);
                request.CookieContainer = cookieContainer;
                request.Method          = "POST";
                request.ContentType     = "application/x-www-form-urlencoded";
                request.ContentLength   = data.Length;

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                Errors.LoginPageError(ex);
                PB.Close();
            }
            return(cookieContainer);
        }
Ejemplo n.º 24
0
        void Start(string H)
        {
            switch (H)
            {
            case "H":
                Butt.Hide();
                PB.Hide();
                break;

            case "S":
                Butt.Show();
                PB.Show();
                break;

            default:
                break;
            }
        }
        private void exportBMP_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.Title  = "Save Dialog";
                dlg.Filter = "Bitmap Images (*.bmp)|*.bmp";
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    using (Bitmap bmp = new Bitmap(PB.Width, PB.Height))
                    {
                        PB.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
                        PB.Image = new Bitmap(PB.Width, PB.Height);

                        bmp.Save(dlg.FileName);
                        MessageBox.Show("Saved Successfully");
                    }
                }
            }
        }
Ejemplo n.º 26
0
        // check tradeskill list if spell is a recipe the player knows and updates Recipe if so.

        public void CheckTradeskillList()
        {
            if (PB.IsTradeSkillsLoaded)
            {
                Recipe =
                    PB.TradeSkillList.Where(t => t.KnownRecipes.ContainsKey(Entry)).Select(t => t.KnownRecipes[Entry]).
                    FirstOrDefault();
                if (IsRecipe)
                {
                    //Properties["Recipe"].Show = true;
                    Properties["SpellName"].Value = SpellName;
                    PB.UpdateMaterials();
                }
                else
                {
                    //Properties["Recipe"].Show = false;
                    Properties["SpellName"].Value = SpellName;
                }
            }
        }
Ejemplo n.º 27
0
 private void SelectionChange_CB1(object sender, SelectionChangedEventArgs e)
 {
     PB.Clear();
     if (CB1.SelectedIndex == 0)
     {
         PB.PasswordChar = (Char)42;
     }
     else if (CB1.SelectedIndex == 1)
     {
         PB.PasswordChar = (Char)43;
     }
     else if (CB1.SelectedIndex == 2)
     {
         PB.PasswordChar = (Char)176;
     }
     else
     {
         PB.PasswordChar = (Char)174;
     }
     PB.IsEnabled = true;
 }
Ejemplo n.º 28
0
        private byte[][] ParseString(string line)
        {
            byte[][] result;

            string[] linesplitted = line.Split('\n');
            result = new byte[linesplitted.Length][];

            for (int i = 0; i < linesplitted.Length; i++)
            {
                string lineresult = PB.ToFullWidth(PB.BP.ReplaceText(linesplitted[i], false));
                byte[] linesjis   = Binary2Po.SJIS.GetBytes(lineresult + '\0');
                result[i]    = new byte[linesjis.Length + 2];
                result[i][0] = 0x32;
                result[i][1] = (byte)linesjis.Length;
                for (int e = 0; e < linesjis.Length; e++)
                {
                    result[i][e + 2] = linesjis[e];
                }
            }

            return(result);
        }
Ejemplo n.º 29
0
 public FibonacciNumbers()
 {
     InitializeComponent();
     write = rtbWrite;
     progress = pbProgress;
 }
Ejemplo n.º 30
0
    protected void OnInstantiateLightmaps(GameControllerBase mainGame, PB.Common.LightmapInfo lightmap)
    {
        if (lightmap.lightmapsMode != "" && lightmap.lightmapsMode != null && lightmap.lightmaps.Count > 0)
        {
            LightmapsMode mode = (LightmapsMode)Enum.Parse(typeof(LightmapsMode), lightmap.lightmapsMode);
            LightmapSettings.lightmapsMode = mode;

            List<LightmapData> maps = new List<LightmapData>();
            Level level = mainGame.Game.WorldData.Level;
            foreach (LightmapDataInfo lmData in level.Lightmap.lightmaps)
            {
                LightmapData data = new LightmapData();

                string nearKey = string.Format("{0}{1}/{2}.unity3d", PopBloopSettings.LevelAssetsUrl, level.Path, lmData.nearLightmap);
                string farKey = string.Format("{0}{1}/{2}.unity3d", PopBloopSettings.LevelAssetsUrl, level.Path, lmData.farLightmap);

                if (lmData.nearLightmap != "" && AssetsManager.Bundles.ContainsKey(nearKey))
                {
                    WWW www = AssetsManager.Bundles[nearKey];

                    if (www.assetBundle != null)
                    {
                        data.lightmapNear = (Texture2D)www.assetBundle.mainAsset;
                    }
                    else
                    {
                        Debug.LogWarning("OnInstantiateLightmaps.NearLightMaps: AssetBundle not found on " + nearKey);
                    }
                }

                // Setup Far Lightmap if there is
                if (lmData.farLightmap != "" && AssetsManager.Bundles.ContainsKey(farKey))
                {
                    WWW www = AssetsManager.Bundles[farKey];

                    if (www.assetBundle != null)
                    {
                        data.lightmapFar = (Texture2D)www.assetBundle.mainAsset;
                    }
                    else
                    {
                        Debug.LogWarning("OnInstantiateLightmaps.FarLightMaps: AssetBundle not found on " + farKey);
                    }
                }

                maps.Add(data);
            }

            if (maps.Count > 0)
            {
                LightmapSettings.lightmaps = maps.ToArray();
            }
        }
    }
Ejemplo n.º 31
0
        public BookDepository(string[] isbns)
        {
            string isbnUrl    = "https://www.bookdepository.com/search?searchTerm=";
            string pageSource = string.Empty;
            string temp       = string.Empty;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            try
            {
                for (int i = 0; i < isbns.Length; i++)
                {
                    // Пауза чтобы не нагружать сервер :)
                    Thread.Sleep(2000);

                    // Присваиваем порядковый номер
                    number = (i + 1).ToString();

                    // Присваиваем ISBN
                    isbn = isbns[i].Replace("\n", "");
                    isbn = isbn.Replace("\r", "");

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту BookDepository. Обработано {i + 1} из {isbnsLength}";
                    PB.progressBar.Value++;
                    progressvalue++;
                    Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                          new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                    //==================================================================================================

                    // Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
                    if (isbn != "")
                    {
                        request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
                        request.CookieContainer = cookieContainer;
                        request.UserAgent       = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"; // 537.36

                        response   = (HttpWebResponse)request.GetResponse();
                        sr         = new StreamReader(response.GetResponseStream());
                        pageSource = sr.ReadToEnd();
                    }
                    //==================================================================================================

                    // Блок обработки страницы с ответом
                    if (pageSource != string.Empty && isbn != "")
                    {
                        //pageSource = AlphabetCheck.Check(pageSource);

                        // Блок проверки соответствия ISBN. Сравниваем тот ISBN который был в списке с тем что нашли.
                        // Если они не равны, тогда в столбце ISBN2 указываем что ISBN не совпадает.
                        temp = "<span itemprop=\"isbn\">";
                        string checkISBN = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                        checkISBN = checkISBN.Remove(checkISBN.IndexOf("<"));

                        if (isbn != checkISBN && !pageSource.Contains("Advanced Search"))
                        {
                            isbn2 = "ISBN не совпадает: " + checkISBN;
                        }

                        // Присваиваем наименование
                        temp = "<h1 itemprop=\"name\">";
                        if (pageSource.Contains(temp))
                        {
                            title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            title = title.Remove(title.IndexOf("<"));
                            title = AlphabetCheck.Check(title);
                        }

                        // Присваиваем автора. Авторов может быть несколько ищем все строки
                        temp = "<div class=\"author-info";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            temp = temp.Remove(temp.IndexOf("</div>"));

                            string[] rows = temp.Split('\n');

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("itemscope=\""))
                                {
                                    temp    = rows[j].Substring(rows[j].IndexOf("itemscope=\"") + 11);
                                    temp    = temp.Remove(temp.IndexOf("\""));
                                    author += temp + ", ";
                                }
                            }
                            try
                            {
                                author = author.Remove(author.LastIndexOf(","));
                                author = AlphabetCheck.Check(author);
                            }
                            catch
                            {
                                author = string.Empty;
                            }
                        }

                        // Присваиваем дату издания
                        temp = "<span itemprop=\"datePublished\">";
                        if (pageSource.Contains(temp))
                        {
                            pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            pubDate = AlphabetCheck.Check(pubDate);
                        }

                        // Присваиваем издательство
                        temp = "<span itemprop=\"publisher\"";
                        if (pageSource.Contains(temp))
                        {
                            publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            publisher = publisher.Substring(publisher.IndexOf("itemscope=\"") + 11);
                            publisher = publisher.Remove(publisher.IndexOf("\""));
                            publisher = AlphabetCheck.Check(publisher);
                        }

                        // Присваиваем импринт
                        temp = "<label>Imprint</label>";
                        if (pageSource.Contains(temp))
                        {
                            imprint = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            imprint = imprint.Substring(imprint.IndexOf(">") + 1);
                            imprint = imprint.Remove(imprint.IndexOf("<"));
                            imprint = AlphabetCheck.Check(imprint);
                        }

                        // Присваиваем цену с валютой и без нее
                        temp = "<span class=\"sale-price\">";
                        if (pageSource.Contains(temp))
                        {
                            priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
                            priceWithCurrency = priceWithCurrency.Replace("US$", "") + " USD";
                            priceWithCurrency = priceWithCurrency.Replace(".", ",");
                            price             = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
                        }

                        // Проверяем, есть ли строка, говорящая о недоступности
                        temp = "<p class=\"list-price\">";
                        if (pageSource.Contains(temp))
                        {
                            availability       = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            priceWithCurrency  = availability.Substring(availability.IndexOf("$") + 1);
                            priceWithCurrency  = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
                            priceWithCurrency += " USD";
                            priceWithCurrency  = priceWithCurrency.Replace(".", ",");
                            price              = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));

                            availability = availability.Substring(availability.IndexOf(">") + 1);

                            if (availability.Contains("<p class=\"red-text bold\">"))
                            {
                                availability = availability.Substring(availability.IndexOf(">") + 1);
                                availability = availability.Remove(availability.IndexOf("<"));
                            }
                        }

                        // Присваиваем доступность
                        temp = "<div class=\"availability-text\">";
                        if (pageSource.Contains(temp))
                        {
                            availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            availability = availability.Substring(availability.IndexOf("<p>") + 3);
                            availability = availability.Remove(availability.IndexOf("<"));
                            availability = AlphabetCheck.Check(availability);
                        }

                        // Присваиваем вес
                        temp = "<label>Dimensions</label>";
                        if (pageSource.Contains(temp))
                        {
                            try
                            {
                                weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                weight = weight.Remove(weight.IndexOf("</span>"));
                                weight = weight.Substring(weight.IndexOf("| ") + 1);
                                weight = weight.Remove(weight.IndexOf("g"));
                                weight = weight.Replace(",", "");
                                weight = weight.Replace(".", ",");

                                weight = AlphabetCheck.Check(weight);

                                weight = Math.Round((double.Parse(weight)) / 1000, 3).ToString();
                            }
                            catch
                            {
                                weight = string.Empty;
                            }
                        }

                        // Присваиваем размеры
                        temp = "<label>Dimensions</label>";
                        if (pageSource.Contains(temp))
                        {
                            dimensions = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            dimensions = dimensions.Replace("<span>", "");
                            dimensions = dimensions.Remove(dimensions.IndexOf("mm"));
                            dimensions = AlphabetCheck.Check(dimensions);

                            string[] dim = dimensions.Split('x');
                            try
                            {
                                length = Math.Round(double.Parse(dim[1].Replace('.', ','))).ToString();
                                width  = Math.Round(double.Parse(dim[0].Replace('.', ','))).ToString();
                                height = Math.Round(double.Parse(dim[2].Replace('.', ','))).ToString();
                            }
                            catch { }
                        }

                        // Присваиваем страну происхождения
                        temp = "<label>Publication City/Country</label>";
                        if (pageSource.Contains(temp))
                        {
                            pubCountry = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pubCountry = pubCountry.Replace("<span>", "");
                            pubCountry = pubCountry.Remove(pubCountry.IndexOf("<"));
                            pubCountry = AlphabetCheck.Check(pubCountry);
                        }

                        // Присваиваем обложку
                        temp = "<label>Format</label>";
                        if (pageSource.Contains(temp))
                        {
                            bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            bookCover = bookCover.Substring(bookCover.IndexOf(">") + 1);
                            bookCover = bookCover.Remove(bookCover.IndexOf("<"));

                            // Здесь может быть ошибка. Т.к. не всегда присутствует элемент " | "
                            try
                            {
                                if (bookCover.IndexOf('|') >= 0)
                                {
                                    bookCover = bookCover.Remove(bookCover.IndexOf("|"));
                                }
                            }
                            catch { }
                            bookCover = AlphabetCheck.Check(bookCover);
                        }

                        // Присваиваем страницы
                        temp = "<span itemprop=\"numberOfPages\">";
                        if (pageSource.Contains(temp))
                        {
                            pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pages = pages.Remove(pages.IndexOf(" "));
                        }

                        // Присваиваем описание
                        temp = "<div class=\"item-excerpt trunc\" itemprop=\"description\" data-height=\"230\">";
                        if (pageSource.Contains(temp))
                        {
                            try
                            {
                                description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                description = description.Remove(description.IndexOf("</div>"));
                                description = description.Remove(description.IndexOf("<a class"));
                                //description = description.Remove(description.LastIndexOf("<br />"));
                                //description = description.Replace("<br />", " ");

                                if (description.StartsWith("-"))
                                {
                                    description = description.Replace("-", "'-");
                                }

                                // Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
                                // Когда нашли индексы убираем содержимое между ними методом Remove
                                if (description.Contains("<a href"))
                                {
                                    bool isContainsLink = true;

                                    while (isContainsLink != false)
                                    {
                                        int startIndex = description.IndexOf("<a href");
                                        int lastIndex  = description.IndexOf(">", startIndex) + 1;
                                        description = description.Remove(startIndex, lastIndex - startIndex);
                                        description = description.Replace("</a>", "");

                                        if (!description.Contains("<a href"))
                                        {
                                            isContainsLink = false;
                                        }
                                    }
                                }
                                description = AlphabetCheck.Check(description);
                            }
                            catch
                            {
                                description = string.Empty;
                            }
                            //==================================================================================================
                        }

                        // Присваиваем ссылку на картинку
                        temp = "<div class=\"item-img-content\">";
                        if (pageSource.Contains(temp))
                        {
                            imageUrl = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            imageUrl = imageUrl.Substring(imageUrl.IndexOf("\"") + 1);
                            imageUrl = imageUrl.Remove(imageUrl.IndexOf("\" "));
                        }

                        AddBookToList();
                        ClearBookList();
                    }
                    else
                    {
                        AddBookToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Errors.CustomError(ex);
            }
            WorkWithFile.SaveFile(book);

            PB.Close();
        }
Ejemplo n.º 32
0
        public PubEasy(string[] isbns)
        {
            string loginPage = "https://beta.pubeasy.com/static/pubeasy/index.html";
            string login     = "******";
            string username  = "******";
            string password  = "******";
            bool   notFound  = false;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            WebDriverWait wait5  = new WebDriverWait(cd, TimeSpan.FromSeconds(5));
            WebDriverWait wait10 = new WebDriverWait(cd, TimeSpan.FromSeconds(10));
            WebDriverWait wait16 = new WebDriverWait(cd, TimeSpan.FromSeconds(16));

            try
            {
                cd.Url = loginPage;
                IWebElement element;

                element = cd.FindElement(By.XPath("//li/a[contains(@href, 'login')]"));
                element.Click();

                // КОД для логина и пароля
                element = cd.FindElement(By.Id("login-id"));
                element.SendKeys(login);
                element = cd.FindElement(By.Id("user-id"));
                element.SendKeys(username);
                element = cd.FindElement(By.Id("login-password"));
                element.SendKeys(password);

                element = cd.FindElement(By.XPath("//input[contains(@type, 'submit')]"));
                element.Click();
                element = cd.FindElement(By.XPath("//a[contains(text(), 'SEARCH NOW >')]"));
                element.Click();

                try
                {
                    for (int i = 0; i < isbns.Length; i++)
                    {
                        // Присваиваем порядковый номер
                        number = (i + 1).ToString();

                        // Присваиваем ISBN
                        isbn = isbns[i].Replace("\n", "");
                        isbn = isbn.Replace("\r", "");

                        // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                        PB.Title = $"Поиск по сайту PubEasy. Обработано {i + 1} из {isbnsLength}";
                        PB.progressBar.Value++;
                        progressvalue++;
                        Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                              new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                        //==================================================================================================


                        if (isbn != string.Empty)
                        {
                            // Переключаем драйвер на первую вкладку браузера
                            cd.SwitchTo().Window(cd.WindowHandles.First());

                            element = cd.FindElement(By.XPath("//*[@id = 'search']/input"));
                            element.Clear();
                            element.SendKeys(isbn);
                            element.SendKeys(Keys.Enter);

                            try
                            {
                                // КОД для определения нашлась ли искомая позиция
                                element  = cd.FindElement(By.XPath("//strong[contains(text(), 'No records found')]"));
                                notFound = true;
                                cd.Navigate().Back();
                            }
                            catch { }

                            if (notFound != true)
                            {
                                try // Поиск наименования
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']//a[2]/font"));
                                    title   = element.Text;
                                    title   = title.Replace("\n", " ");
                                    title   = title.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск автора
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[2]"));
                                    author  = element.Text;
                                }
                                catch { }

                                try // Поиск даты издания
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[6]"));
                                    pubDate = element.Text;
                                    pubDate = pubDate.Replace("\n", " ");
                                    pubDate = pubDate.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск издательства
                                {
                                    element   = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[4]"));
                                    publisher = element.Text;
                                }
                                catch { }

                                try // Поиск поставщика
                                {
                                    element  = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[5]"));
                                    supplier = element.Text;
                                }
                                catch { }

                                try // Поиск цены
                                {
                                    element           = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[7]"));
                                    priceWithCurrency = element.Text;
                                    priceWithCurrency = priceWithCurrency.Replace("\r", " ");
                                    priceWithCurrency = priceWithCurrency.Replace("\n", " ");
                                    priceWithCurrency = priceWithCurrency.Replace(" (Retail)", "");
                                    priceWithCurrency = priceWithCurrency.Replace(" (List)", "");
                                    price             = priceWithCurrency.Replace(" GBP", "");
                                    price             = price.Replace(".", ",");
                                }
                                catch { }

                                try // Поиск доступности
                                {
                                    element      = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[8]"));
                                    availability = element.Text;
                                    availability = availability.Replace("\n", " ");
                                    availability = availability.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск обложки
                                {
                                    element   = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[3]"));
                                    bookCover = element.Text;
                                }
                                catch { }

                                if (supplier.StartsWith("bertram", StringComparison.OrdinalIgnoreCase) |
                                    supplier.StartsWith("gardners", StringComparison.OrdinalIgnoreCase))
                                {
                                    ClearBookList();
                                }

                                try
                                {
                                    // Пытаемся перейти по ссылке Availability ==========
                                    element = cd.FindElement(By.XPath("//*[@class = 'odd']/td[8]/a"));
                                    element.Click();
                                    // ==================================================

                                    try
                                    {
                                        cd.SwitchTo().Window(cd.WindowHandles.Last());

                                        element = cd.FindElement(By.XPath("//iframe[@class = 'embed-responsive-item']"));
                                        cd.SwitchTo().Frame(element);

                                        wait16.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath("//*[@class = 'table-responsive']/table/tbody/tr[6]/td[2]")));

                                        //Меняем наименование ===============================
                                        title = cd.FindElement(By.XPath("//*[@class = 'table-responsive']/table/tbody/tr/td[2]")).Text;
                                        // ==================================================

                                        //Проверка соответсвия цены =========================

                                        try
                                        {
                                            element          = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Price')]]/td[2]"));
                                            priceComparision = element.Text;
                                            priceComparision = priceComparision.Replace("\r\n", " ");
                                            priceComparision = priceComparision.Replace(" (Retail)", "");
                                            priceComparision = priceComparision.Replace("(Retail)", "");
                                            priceComparision = priceComparision.Replace(" (British Pounds)", "");
                                            priceComparision = priceComparision.Replace("(British Pounds)", "");
                                            priceComparision = priceComparision.Replace(" (List)", "");
                                            priceComparision = priceComparision.Replace("(List)", "");
                                            priceComparision = priceComparision.Replace(" GBP", "");
                                            priceComparision = priceComparision.Replace(".", ",");
                                            priceComparision = priceComparision.Replace("Not applicable", "");

                                            if (price == priceComparision)
                                            {
                                                priceComparision = string.Empty;
                                            }
                                        }
                                        catch { }
                                        // ==================================================

                                        //Поиск скидки ==========================================
                                        try
                                        {
                                            element  = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Base Discount')]]/td[2]"));
                                            discount = element.Text;
                                            discount = discount.Replace("%", "");
                                            discount = discount.Replace(".", ",");
                                        }
                                        catch { }
                                        // ==================================================

                                        // Market Restrictions ==============================
                                        try
                                        {
                                            element            = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Market Restrictions')]]/td[2]"));
                                            marketRestrictions = element.Text;
                                        }
                                        catch { }
                                        // ==================================================

                                        // Availability со второй страницы ==================
                                        try
                                        {
                                            element       = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Availability')]]/td[2]"));
                                            availability2 = element.Text;
                                            availability2 = availability2.Replace("\n", "");
                                            availability2 = availability2.Replace("\r", "");
                                        }
                                        catch { }
                                        // ==================================================

                                        cd.Close();
                                    }
                                    catch
                                    {
                                        priceComparision = "Страница не загрузилась.";
                                        cd.Close();
                                    }
                                }
                                catch
                                { }
                            }
                            notFound = false;
                            AddBookToList();
                            ClearBookList();
                        }
                    }
                }
                catch (Exception ex)
                {
                    cd.Quit();
                    PB.Close();
                    Errors.CustomError(ex);
                }
                cd.Quit();
                PB.Close();
                WorkWithFile.SaveFile(book);
            }
            catch (Exception ex)
            {
                cd.Quit();
                PB.Close();
                Errors.LoginPageError(ex);
            }
        }
Ejemplo n.º 33
0
 public override void OnReceivedChatMessage(GameControllerBase mainGame, PB.Client.Item item, string[] group, string message)
 {
     base.OnReceivedChatMessage(mainGame, item, group, message);
 }