Ejemplo n.º 1
0
        public ActionResult <bool> GetById(string input)
        {
            AlphabetCheck ac     = new AlphabetCheck();
            bool          result = ac.ContainsEntireAlphabet(input);

            return(result);
        }
Ejemplo n.º 2
0
        public void TestOverlyMixed()
        {
            AlphabetCheck ac = new AlphabetCheck();

            bool result = ac.ContainsEntireAlphabet("!@$%^^*aBc%^&DeFgHiJk$%^@#LmNoPq%^*&$RsTuVwXyZ");

            Assert.AreEqual(true, result);
        }
Ejemplo n.º 3
0
        public void TestMix()
        {
            AlphabetCheck ac = new AlphabetCheck();

            bool result = ac.ContainsEntireAlphabet("aBcDeFgHiJkLmNoPqRsTuVwXyZ");

            Assert.AreEqual(true, result);
        }
Ejemplo n.º 4
0
        public void TestUppers()
        {
            AlphabetCheck ac = new AlphabetCheck();

            bool result = ac.ContainsEntireAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

            Assert.AreEqual(true, result);
        }
Ejemplo n.º 5
0
        public void TestLowers()
        {
            AlphabetCheck ac = new AlphabetCheck();

            bool result = ac.ContainsEntireAlphabet("abcdefghijklmnopqrstuvwxyz");

            Assert.AreEqual(true, result);
        }
Ejemplo n.º 6
0
        public void TestShortString()
        {
            AlphabetCheck ac = new AlphabetCheck();

            bool result = ac.ContainsEntireAlphabet("abcde");

            Assert.AreEqual(false, result);
        }
Ejemplo n.º 7
0
        public void TestAllButOne()
        {
            AlphabetCheck ac = new AlphabetCheck();

            // Missing u
            bool result = ac.ContainsEntireAlphabet("aBcDeFgHiJkLmNoPqRsTVwXyZ");

            Assert.AreEqual(false, result);
        }
Ejemplo n.º 8
0
        public void TestEmptyAndNull()
        {
            AlphabetCheck ac = new AlphabetCheck();

            bool result = ac.ContainsEntireAlphabet(string.Empty);

            Assert.AreEqual(false, result);

            ac.ContainsEntireAlphabet(null);
            Assert.AreEqual(false, result);
        }
Ejemplo n.º 9
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.º 10
0
        public ABEIPS(string[] isbns)
        {
            string loginPage = "https://biznes.abe.pl/login";
            string isbnUrl   = "https://biznes.abe.pl/search/?search_param=all&q=";
            string username  = "******";
            string password  = "******";

            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 });
            //==================================================================================================

            var cookieContainer = GetCookie(loginPage, username, password);

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

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

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

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

                    // Отправляем первый запрос по ISBN. Ответом нам будет страница со списком, которую мы записываем в переменную PageSource
                    if (isbn != "")
                    {
                        request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
                        request.CookieContainer = cookieContainer;

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

                    // Проверка, удалось ли залогиниться, если на сранице есть текст "Login" значит прерываем цикл.
                    if (pageSource.Contains("Login"))
                    {
                        MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
                        break;
                    }
                    //==================================================================================================

                    // Блок обработки страницы с результатом первого запроса.
                    // Так как на странице с результатом может быть несколько ссылок на книги, пробуем найти нужную нам.
                    // Найденную ссылку передаем в следующий запрос

                    string delimeter = "<div class=\"col-md-6\">";

                    if (pageSource.Contains(delimeter))
                    {
                        // Разбиваем текст страницы на строки и считаем сколько строк содержит наш delimeter
                        // Это нужно чтобы создать массив с нужными нам элементами
                        string[] rows     = pageSource.Split('\n');
                        int      divCount = 0;

                        for (int j = 0; j < rows.Length; j++)
                        {
                            if (rows[j].Contains(delimeter))
                            {
                                divCount++;
                            }
                        }

                        // Собираем все строки содержащие delimeter в массив divs,
                        // в них нужно найти ту строку в которой упоминается ISBN нашей книги.
                        // Правильная строка обрабатывается и присваивается переменной href.
                        string[] div = new string[divCount];

                        int    divStartIndex = 0;
                        int    divEndIndex   = 0;
                        string href          = "";

                        for (int j = 0; j < divCount; j++)
                        {
                            divStartIndex = pageSource.IndexOf(delimeter, divEndIndex);
                            divEndIndex   = pageSource.IndexOf("</div>", divStartIndex);

                            div[j] = pageSource.Substring(divStartIndex);
                            div[j] = div[j].Remove(divEndIndex - divStartIndex);

                            if (div[j].Replace("-", "").Contains(isbn) == true)
                            {
                                href = div[j].Substring(div[j].IndexOf(delimeter) + delimeter.Length);
                                href = href.Substring(href.IndexOf("\"") + 1);
                                href = href.Remove(href.IndexOf("\""));
                                href = "https://biznes.abe.pl" + href;
                                break;
                            }
                            else
                            {
                                // Если ни одна строка не содержит искомого ISBN тогда берем первую строку и забираем из нее ссылку
                                href = div[0].Substring(div[0].IndexOf(delimeter) + delimeter.Length);
                                href = href.Substring(href.IndexOf("\"") + 1);
                                href = href.Remove(href.IndexOf("\""));
                                href = "https://biznes.abe.pl" + href;
                            }
                        }
                        //==================================================================================================

                        request = (HttpWebRequest)WebRequest.Create(href);
                        request.CookieContainer = cookieContainer;

                        try
                        {
                            response   = (HttpWebResponse)request.GetResponse();
                            sr         = new StreamReader(response.GetResponseStream());
                            pageSource = sr.ReadToEnd();
                        }
                        catch
                        {
                            pageSource = string.Empty;
                        }
                        //==================================================================================================

                        // Блок обработки карточки товара. Пытаемся получить всю доступную информацию
                        if (pageSource != string.Empty)
                        {
                            pageSource = AlphabetCheck.Check(pageSource);

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

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

                            // Присваиваем наименование
                            temp  = "<div class=\"page-header\">";
                            title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            title = title.Substring(title.IndexOf("class=\"\">") + 9);
                            title = title.Remove(title.IndexOf("<"));

                            // Присваиваем автора
                            temp = "<dt>Author</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                author = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                author = author.Remove(author.IndexOf("<"));
                            }

                            // Присваиваем дату издания
                            temp = "<dt>Date</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            }

                            // Присваиваем Division
                            temp = "<dt>Division</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                imprint = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                imprint = imprint.Substring(imprint.IndexOf(">") + 1);
                                imprint = imprint.Remove(imprint.IndexOf("<"));
                            }

                            // Присваиваем издательство
                            temp = "<dt>Publisher</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                publisher = publisher.Substring(publisher.IndexOf(">") + 1);
                                publisher = publisher.Remove(publisher.IndexOf("<"));
                            }

                            // Присваиваем цену с валютой и без нее
                            temp = "<small class='text-green'>List price</small>";
                            if (pageSource.Contains(temp))
                            {
                                priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                priceWithCurrency = priceWithCurrency.Substring(priceWithCurrency.IndexOf("> ") + 2);
                                priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
                                price             = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
                                price             = price.Replace(".", ",");
                            }

                            // Присваиваем цену со скидкой
                            temp = "<small class='text-green'>Your price</small>";
                            if (pageSource.Contains(temp))
                            {
                                discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                discount = discount.Substring(discount.IndexOf("> ") + 2);
                                discount = discount.Remove(discount.IndexOf("<"));
                                discount = discount.Remove(discount.IndexOf(" "));
                                discount = discount.Replace(".", ",");
                            }

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

                            // Присваиваем читательскую группу
                            temp = "<dt>Readership level</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                readership = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                readership = readership.Remove(readership.IndexOf("<"));
                            }

                            // Присваиваем издание
                            temp = "<dt>Edition</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                edition = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                edition = edition.Remove(edition.IndexOf("<"));
                            }

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

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

                            // Присваиваем описание, убираем все лишнее из текста
                            temp = "<h3>Description</h3>";
                            if (pageSource.Contains(temp))
                            {
                                description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                description = description.Substring(description.IndexOf("<div class=\"col-md-12\">") + 23);
                                description = description.Remove(description.IndexOf("</div>"));

                                description = description.Replace("</p>", " "); // здесь меняем на пробел
                                description = description.Replace("</P>", " "); // здесь меняем на пробел

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

                                int  startIndex = 0;
                                int  lastIndex  = 0;
                                bool done       = false;

                                while (done != true)
                                {
                                    char[] tempDescription = description.ToCharArray();

                                    for (int j = 0; j < description.Length; j++)
                                    {
                                        if (tempDescription[j] == '<')
                                        {
                                            startIndex = j;
                                            break;
                                        }
                                    }
                                    for (int k = startIndex; k < description.Length; k++)
                                    {
                                        if (tempDescription[k] == '>')
                                        {
                                            lastIndex = k - startIndex + 1;
                                            break;
                                        }
                                    }
                                    description = description.Remove(startIndex, lastIndex);
                                    if (!description.Contains('<') && !description.Contains('>'))
                                    {
                                        description = AlphabetCheck.Check(description);
                                        done        = true;
                                    }
                                }
                                //==================================================================================================
                            }
                        }
                        AddBookToList();
                        ClearBookList();
                    }
                    else
                    {
                        AddBookToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Errors.CustomError(ex);
            }
            WorkWithFile.SaveFile(book);

            PB.Close();
        }
Ejemplo n.º 11
0
        public Gardners(string[] isbns)
        {
            string loginPage     = "https://www.gardners.com/Account/LogOn";
            string isbnUrl       = "https://www.gardners.com/Product/";
            string accountNumber = "Номер аккаунта";
            string username      = "******";
            string password      = "******";

            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 });
            //==================================================================================================

            var cookieContainer = GetCookie(loginPage, accountNumber, username, password);

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

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

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

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту Gardners. Обработано {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;

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

                    // Проверка, не слетел ли наш логин
                    if (pageSource.Contains("class=\"unauthenticated\">"))
                    {
                        MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
                        break;
                    }
                    //==================================================================================================

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

                        // Проверяем, есть ли замена
                        temp = "<span class=\"replacedByLink\">";
                        if (pageSource.Contains(temp))
                        {
                            isbn2 = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            isbn2 = isbn2.Substring(isbn2.IndexOf(">") + 1);
                            isbn2 = isbn2.Remove(isbn2.IndexOf("<"));
                        }

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

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

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

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("<a href"))
                                {
                                    temp    = rows[j].Substring(rows[j].IndexOf("\">") + 2);
                                    temp    = temp.Remove(temp.IndexOf("<"));
                                    author += temp + ", ";
                                }
                            }
                            author = author.Remove(author.LastIndexOf(","));
                            author = AlphabetCheck.Check(author);
                        }

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

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

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

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

                        // Присваиваем скидку
                        temp = "<p class=\"hideCustomer\"><span>";
                        if (pageSource.Contains(temp))
                        {
                            discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            discount = discount.Remove(discount.IndexOf(" "));
                        }

                        // Присваиваем доступность
                        temp = "<div class=\"availability\"";
                        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("class=\"icon-text"))
                                {
                                    temp          = rows[j].Substring(rows[j].IndexOf("icon-text"));
                                    temp          = temp.Substring(temp.IndexOf(">") + 1);
                                    temp          = temp.Remove(temp.IndexOf("<"));
                                    availability += temp + ", ";
                                }
                            }
                            availability = availability.Remove(availability.LastIndexOf(","));
                        }

                        // Присваиваем читательскую группу (Readership)
                        temp = "<span>Readership:</span>";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            temp = temp.Remove(temp.IndexOf("</ul>"));

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

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("<li>"))
                                {
                                    temp        = rows[j].Substring(rows[j].IndexOf(">") + 1);
                                    temp        = temp.Remove(temp.IndexOf("<"));
                                    readership += temp + ", ";
                                }
                            }
                            readership = readership.Remove(readership.LastIndexOf(","));
                            readership = AlphabetCheck.Check(readership);
                        }

                        // Присваиваем издание
                        temp = "<span class=\"edition\">";
                        if (pageSource.Contains(temp))
                        {
                            edition = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            edition = edition.Remove(edition.IndexOf("<"));
                        }

                        // Присваиваем вес
                        temp = "<span>Weight:</span>";
                        if (pageSource.Contains(temp))
                        {
                            weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            weight = weight.Replace("<span>", "");
                            weight = weight.Remove(weight.IndexOf("g"));
                            weight = ((float.Parse(weight)) / 1000).ToString();
                        }

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

                            string[] dim = dimensions.Split('x');
                            try
                            {
                                length = dim[0];
                                width  = dim[1];
                                height = dim[2];
                            }
                            catch { }
                        }

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

                        // Присваиваем классификацию
                        temp = "<span>Classifications:</span>";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            temp = temp.Remove(temp.IndexOf("</ul>"));

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

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("<a href"))
                                {
                                    temp            = rows[j].Substring(rows[j].IndexOf("\">") + 2);
                                    temp            = temp.Remove(temp.IndexOf("<"));
                                    classification += temp + ", ";
                                }
                            }
                            classification = classification.Remove(classification.LastIndexOf(","));
                            classification = AlphabetCheck.Check(classification);
                        }

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

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

                        // Присваиваем серию
                        temp = "<span>Series:</span>";
                        if (pageSource.Contains(temp))
                        {
                            series = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            series = series.Replace("<span>", "");
                            series = series.Substring(series.IndexOf(">") + 1);
                            series = series.Remove(series.IndexOf("<"));
                        }

                        // Присваиваем описание
                        temp = "<div class=\"productDescription\">";
                        if (pageSource.Contains(temp))
                        {
                            description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            description = description.Remove(description.IndexOf("</div>"));
                            description = description.Replace("<br>", " ");

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

                            int  startIndex = 0;
                            int  lastIndex  = 0;
                            bool done       = false;

                            while (done != true)
                            {
                                char[] tempDescription = description.ToCharArray();

                                for (int j = 0; j < description.Length; j++)
                                {
                                    if (tempDescription[j] == '<')
                                    {
                                        startIndex = j;
                                        break;
                                    }
                                }
                                for (int k = startIndex; k < description.Length; k++)
                                {
                                    if (tempDescription[k] == '>')
                                    {
                                        lastIndex = k - startIndex + 1;
                                        break;
                                    }
                                }
                                description = description.Remove(startIndex, lastIndex);
                                if (!description.Contains('<') && !description.Contains('>'))
                                {
                                    description = AlphabetCheck.Check(description);
                                    done        = true;
                                }
                            }
                            //==================================================================================================
                        }

                        // Присваиваем содержание
                        temp = "<span>Contents:</span>";
                        if (pageSource.Contains(temp))
                        {
                            contents = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            contents = contents.Replace("<span>", "");
                            contents = contents.Remove(contents.IndexOf("</span>"));
                            contents = AlphabetCheck.Check(contents);
                        }

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

            PB.Close();
        }
Ejemplo n.º 12
0
        public AuthorsComparer(string authorsForComare)
        {
            // Создаем массив с авторами для сравнения (пользовательский)
            authorsForComare = authorsForComare.Replace("\r", "");
            string[] authors = authorsForComare.Split('\n');

            // Создаем массив с авторами из файла (с этим массивом мы будем сравнивать новый массив авторов authors)
            string[] authorsSavedList = File.ReadAllLines("authors.txt");
            string[,] compareList = new string[authorsSavedList.Length, 3];

            // В ячейку compareList[i, 0] записываем исходные данные автора
            // В ячейку compareList[i, 1] записываем очищенные данные (без запятых, кавычек, пробелов и т.д)
            // В ячейку compareList[i, 2] записываем отсортированные данные
            for (int i = 0; i < authorsSavedList.Length; i++)
            {
                compareList[i, 0] = authorsSavedList[i];
                compareList[i, 1] = AlphabetCheck.Check(compareList[i, 0]);
                compareList[i, 1] = compareList[i, 1].Replace(" ", "");
                compareList[i, 1] = compareList[i, 1].Replace(",", "");
                compareList[i, 1] = compareList[i, 1].Replace("-", "");
                compareList[i, 1] = compareList[i, 1].Replace(".", "");
                compareList[i, 1] = compareList[i, 1].Replace("/", "");
                compareList[i, 1] = compareList[i, 1].Replace("\\", "");
                compareList[i, 1] = compareList[i, 1].Replace("'", "");
                compareList[i, 1] = compareList[i, 1].Replace("\"", "");
                compareList[i, 1] = compareList[i, 1].Replace("_", "");
                compareList[i, 1] = compareList[i, 1].ToLower();

                char[] temp = compareList[i, 1].ToCharArray();
                Array.Sort(temp);
                compareList[i, 2] = new string(temp);
            }
            //==================================================================================================

            List <AuthorsList> authorsList = new List <AuthorsList>();

            string tempAuthor;

            for (int i = 0; i < authors.Length; i++)
            {
                // Убираем все лишние символы, т.к. автор может быть написан как "Herbert Wells" так и "Wells, Herbert"
                tempAuthor = AlphabetCheck.Check(authors[i]);
                tempAuthor = tempAuthor.Replace(" ", "");
                tempAuthor = tempAuthor.Replace(",", "");
                tempAuthor = tempAuthor.Replace("-", "");
                tempAuthor = tempAuthor.Replace(".", "");
                tempAuthor = tempAuthor.Replace("/", "");
                tempAuthor = tempAuthor.Replace("\\", "");
                tempAuthor = tempAuthor.Replace("'", "");
                tempAuthor = tempAuthor.Replace("\"", "");
                tempAuthor = tempAuthor.Replace("_", "");
                tempAuthor = tempAuthor.ToLower();
                //==================================================================================================

                // В этой части разбиваем автора на символы и складываем хешсумму
                char[] temp = tempAuthor.ToCharArray();

                Array.Sort(temp);

                string sortedAuthor = "";

                for (int j = 0; j < compareList.GetUpperBound(0); j++)
                {
                    if (new string(temp) == compareList[j, 2])
                    {
                        sortedAuthor = compareList[j, 0];
                    }
                }
                //==================================================================================================

                authorsList.Add(new AuthorsList
                {
                    OriginAuthor     = authors[i],
                    SortedAuthorName = tempAuthor,
                    NameInBitrix     = sortedAuthor,
                });
            }

            DataGrid DG = new DataGrid();

            DG.Title = "Таблица сравнения";
            DG.dataGrid.ItemsSource = authorsList;
            DG.Show();
        }
Ejemplo n.º 13
0
        public Libri(string[] isbns)
        {
            string loginPage     = "https://mein.libri.de/en/Login.html";
            string isbnUrl       = "https://mein.libri.de/en/produkt/";
            string accountNumber = "Номер аккаунта";
            string username      = "******";
            string password      = "******";

            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 });
            //==================================================================================================

            cookieContainer = GetCookie(loginPage, accountNumber, username, password);

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

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

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

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту Libri. Обработано {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;

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

                    // Проверка, не слетел ли наш логин
                    if (pageSource.Contains("Please enter your login information."))
                    {
                        MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
                        break;
                    }
                    //==================================================================================================

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

                        // Блок проверки соответствия ISBN. Сравниваем тот ISBN который был в списке с тем что нашли.
                        // Если они не равны, тогда в столбце ISBN2 указываем что ISBN не совпадает.
                        temp = "Article no./EAN";
                        if (pageSource.Contains(temp))
                        {
                            string checkISBN = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            checkISBN = checkISBN.Substring(checkISBN.IndexOf("<td>") + 4);
                            checkISBN = checkISBN.Remove(checkISBN.IndexOf("<"));
                            checkISBN = AlphabetCheck.Check(checkISBN);

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

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

                        // Присваиваем автора
                        temp = "<td class=\"detail-label\"> Author </td>";
                        if (pageSource.Contains(temp))
                        {
                            author = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            author = author.Replace("<td>", "");
                            author = author.Remove(author.IndexOf("</td>"));
                            author = author.Replace("<br>", ";");
                            author = AlphabetCheck.Check(author);
                        }

                        // Присваиваем дату издания
                        temp = "<td class=\"detail-label\"> Release date </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            pubDate = AlphabetCheck.Check(pubDate);
                        }

                        // Присваиваем издательство
                        temp = "<td class=\"detail-label\"> Publisher </td> <td class=\"info-column\">";
                        if (pageSource.Contains(temp))
                        {
                            publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            publisher = publisher.Remove(publisher.IndexOf("<"));
                            publisher = AlphabetCheck.Check(publisher);
                        }

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

                        // Присваиваем скидку
                        temp = "<td class=\"detail-label\"> Discount group </td>";
                        if (pageSource.Contains(temp))
                        {
                            discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            discount = discount.Substring(discount.IndexOf("content=\"") + 9);
                            discount = discount.Remove(discount.IndexOf("\""));
                            discount = discount.Replace("<br>", "; ");
                            try
                            {
                                discount = discount.Remove(discount.LastIndexOf(";"));
                            }
                            catch { }
                        }

                        // Присваиваем доступность
                        temp = "<td class=\"detail-label\"> Availability Status Code </td>";
                        if (pageSource.Contains(temp))
                        {
                            availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            availability = availability.Substring(availability.IndexOf("content=\"") + 9);
                            availability = availability.Remove(availability.IndexOf("\""));
                        }

                        // Присваиваем читательскую группу (Readership)
                        temp = "<td class=\"detail-label\"> Age group </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            readership = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            readership = readership.Remove(readership.IndexOf("<"));
                        }

                        // Присваиваем вес
                        temp = "<td class=\"detail-label\"> Weight </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            weight = weight.Remove(weight.IndexOf("g"));
                            weight = ((float.Parse(weight)) / 1000).ToString();
                        }

                        // Присваиваем классификацию
                        temp = "<td class=\"detail-label\"> Product group </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            classification = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            classification = classification.Remove(classification.IndexOf("<"));
                        }

                        // Присваиваем обложку
                        temp = "<td class=\"detail-label\"> Book cover </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            bookCover = bookCover.Remove(bookCover.IndexOf("<"));
                        }

                        // Присваиваем страницы
                        temp = "<td class=\"detail-label\"> Pages </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pages = pages.Remove(pages.IndexOf("<"));
                        }

                        // Присваиваем серию
                        temp = "<td class=\"detail-label\"> Series </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            series = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            series = series.Remove(series.IndexOf("<"));
                        }

                        // Присваиваем описание
                        temp = "<div class=\"detail-content detail-description\">";
                        if (pageSource.Contains(temp))
                        {
                            description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            description = description.Remove(description.IndexOf("<"));
                        }

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

            PB.Close();
        }
Ejemplo n.º 14
0
        public Brill(string[] isbns)
        {
            string isbnUrl    = "https://brill.com/search?q1=";
            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 });
            //==================================================================================================
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

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

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

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

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту Brill. Обработано {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;

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

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

                        // Присваиваем наименование
                        temp = "<div class=\"typography-body text-headline color-primary\">";
                        if (pageSource.Contains(temp))
                        {
                            title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            title = title.Substring(title.IndexOf(">") + 1);
                            title = title.Remove(title.IndexOf("<"));
                            //title = AlphabetCheck.Check(title);
                        }

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

                            string[] rows = Regex.Split(temp, "</span>");

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

                        // Присваиваем описание
                        temp = "<div id=\"ABSTRACT_OR_EXCERPT";
                        if (pageSource.Contains(temp))
                        {
                            try
                            {
                                description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                description = description.Substring(description.IndexOf(">") + 1);
                                description = description.Remove(description.IndexOf("</div>"));

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

                                int  startIndex = 0;
                                int  lastIndex  = 0;
                                bool done       = false;

                                while (done != true)
                                {
                                    char[] tempDescription = description.ToCharArray();

                                    for (int j = 0; j < description.Length; j++)
                                    {
                                        if (tempDescription[j] == '<')
                                        {
                                            startIndex = j;
                                            break;
                                        }
                                    }
                                    for (int k = startIndex; k < description.Length; k++)
                                    {
                                        if (tempDescription[k] == '>')
                                        {
                                            lastIndex = k - startIndex + 1;
                                            break;
                                        }
                                    }
                                    description = description.Remove(startIndex, lastIndex);
                                    if (!description.Contains('<') && !description.Contains('>'))
                                    {
                                        //description = AlphabetCheck.Check(description);
                                        done = true;
                                    }
                                }
                            }
                            catch
                            {
                                description = string.Empty;
                            }
                        }

                        // Присваиваем ссылку на картинку
                        temp = "<div class=\"cover cover-image configurable-index-card-cover-image\">";
                        if (pageSource.Contains(temp))
                        {
                            imageUrl = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            imageUrl = imageUrl.Substring(imageUrl.IndexOf(">") + 1);
                            imageUrl = imageUrl.Substring(imageUrl.IndexOf("src=\"") + 5);
                            imageUrl = "https://brill.com" + imageUrl.Remove(imageUrl.IndexOf(".") + 4);
                        }

                        temp = "<div class=\"content-box-body null\">";
                        if (pageSource.Contains(temp))
                        {
                            string[] body        = Regex.Split(pageSource, temp);
                            string[] meta        = null;
                            string   mainContent = null;
                            for (int j = 0; j < body.Length; j++)
                            {
                                if (body[j].Contains("<div class=\"text-metadata-format\">"))
                                {
                                    body[j] = body[j].Replace("-", "");
                                    meta    = Regex.Split(body[j], "<div class=\"textmetadataformat\">");
                                    break;
                                }
                            }

                            for (int j = 0; j < meta.Length; j++)
                            {
                                if (meta[j].Contains(isbn))
                                {
                                    mainContent = meta[j];
                                }
                            }

                            try
                            {
                                bookCover = mainContent.Remove(mainContent.IndexOf("<"));
                            }
                            catch { }
                            try
                            {
                                temp         = "<dd class=\"availability inline cList__item cList__item  secondary textmetadatavalue\">";
                                availability = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
                                availability = availability.Remove(availability.IndexOf("<"));
                            }
                            catch { }
                            try
                            {
                                temp    = "<dd class=\"pubdate inline cList__item cList__item  secondary textmetadatavalue\">";
                                pubDate = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
                                pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            }
                            catch { }
                            try
                            {
                                temp  = "</abbr>";
                                price = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
                                price = price.Remove(price.IndexOf("<"));
                                price = price.Replace("€", "");
                                price = price.Replace(".", ",");
                            }
                            catch { }
                        }

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

            PB.Close();
        }