示例#1
0
    void SendResultInfoAsJson(SendRequestResponse res)
    {
        string strJson = JsonConvert.SerializeObject(res);

        Response.ContentType = "application/json; charset=utf-8";
        Response.AppendHeader("Access-Control-Allow-Origin", "*");
        Response.Write(strJson);
        Response.End();
    }
示例#2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        SendRequestRequest  req;
        SendRequestResponse res = new SendRequestResponse();

        res.error = String.Empty;

        // 1. Deserialize the incoming Json.
        try
        {
            req = GetRequestInfo();
        }
        catch (Exception ex)
        {
            res.error = ex.Message.ToString();

            // Return the results as Json.
            SendResultInfoAsJson(res);
            return;
        }

        if (req.RequestType <= 0 || req.RequestType > 4)
        {
            res.error = "Invalid request type";
            SendResultInfoAsJson(res);
            return;
        }

        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        try
        {
            connection.Open();

            string     sql       = "INSERT INTO Request(StoreID,EmployeeID,RequestType,RequestStatus,RequestText,ScheduleID1,ScheduleID2) Values(@StoreID,@EmployeeID,@RequestType,0,@RequestText,@ScheduleID1,@ScheduleID2)";
            SqlCommand createReq = new SqlCommand(sql, connection);
            createReq.Parameters.Add("@StoreID", SqlDbType.Int);
            createReq.Parameters.Add("@EmployeeID", SqlDbType.Int);
            createReq.Parameters.Add("@RequestType", SqlDbType.Int);
            createReq.Parameters.Add("@RequestText", SqlDbType.NVarChar);
            createReq.Parameters.Add("@ScheduleID1", SqlDbType.Int);
            createReq.Parameters.Add("@ScheduleID2", SqlDbType.Int);
            createReq.Parameters["@StoreID"].Value     = req.StoreID;
            createReq.Parameters["@EmployeeID"].Value  = req.EmployeeID;
            createReq.Parameters["@RequestType"].Value = req.RequestType;
            createReq.Parameters["@RequestText"].Value = req.RequestText;
            createReq.Parameters["@ScheduleID1"].Value = req.ScheduleID1;
            createReq.Parameters["@ScheduleID2"].Value = req.ScheduleID2 == 0 ? req.ScheduleID1 : req.ScheduleID2;
            createReq.ExecuteNonQuery();

            string     getSql = "SELECT TOP 1 RequestID FROM Request WHERE StoreID = @StoreID AND EmployeeID = @EmployeeID AND RequestType = @RequestType AND RequestText = @RequestText AND ScheduleID1 = @ScheduleID1 AND ScheduleID2 = @ScheduleID2 ORDER BY RequestID desc";
            SqlCommand getReq = new SqlCommand(getSql, connection);
            getReq.Parameters.Add("@StoreID", SqlDbType.Int);
            getReq.Parameters.Add("@EmployeeID", SqlDbType.Int);
            getReq.Parameters.Add("@RequestType", SqlDbType.Int);
            getReq.Parameters.Add("@RequestText", SqlDbType.NVarChar);
            getReq.Parameters.Add("@ScheduleID1", SqlDbType.Int);
            getReq.Parameters.Add("@ScheduleID2", SqlDbType.Int);
            getReq.Parameters["@StoreID"].Value     = req.StoreID;
            getReq.Parameters["@EmployeeID"].Value  = req.EmployeeID;
            getReq.Parameters["@RequestType"].Value = req.RequestType;
            getReq.Parameters["@RequestText"].Value = req.RequestText;
            getReq.Parameters["@ScheduleID1"].Value = req.ScheduleID1;
            getReq.Parameters["@ScheduleID2"].Value = req.ScheduleID2 == 0 ? req.ScheduleID1 : req.ScheduleID2;

            SqlDataReader reader = getReq.ExecuteReader();
            if (reader.Read())
            {
                res.RequestID = Convert.ToInt32(reader["RequestID"]);
            }
            else
            {
                res.error = "Something went wrong";
            }
        }
        catch (Exception ex)
        {
            res.error = ex.Message.ToString();
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }

        // Return the results as Json.
        SendResultInfoAsJson(res);
    }
示例#3
0
        private async void ПолучитьСертификат_Click(object sender, RoutedEventArgs e)
        {
            ПолучитьСертификат.IsEnabled = false;
            using (new WaitCursor())
                try
                {
                    if (НазваниеУрока.SelectedIndex == -1)
                    {
                        MessageBox.Show("Список уроков не загружен.\nЗакройте программу и повторите попытку позднее.", "Уведомление", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                        return;
                    }
                    if (string.IsNullOrWhiteSpace(ИмяПользователя.Text) && НазваниеУрока.SelectedIndex < НовыйАлгоритм)
                    {
                        MessageBox.Show("Введите имя и повторите попытку.", "Уведомление", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                        return;
                    }
                    string error_text = string.Empty;
                    try
                    {
                        //Константы
                        const string MissingData              = "Запрошенная страница не содержит искомых данных.\nПроверьте обновление программы.";
                        const string GettingIdError           = "Ошибка получения нового идентификатора пользователя.\nПопробуйте повторить попытку позднее.";
                        const string SiteUnavailable          = "\"{0}\" недоступен.\nПроверьте подключение к интернет или попробуйте повторить попытку позднее.";
                        const string SiteTemporaryUnavailable = "\"{0}\" временно недоступен.\nПопробуйте повторить попытку позднее.";

                        string            user_id = string.Empty;
                        CookieContainer   cookies = new CookieContainer();
                        HttpClientHandler handler = new HttpClientHandler
                        {
                            CookieContainer        = cookies,
                            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                        };
                        HttpClient client = new HttpClient(handler);
                        client.DefaultRequestHeaders.Add(HttpRequestHeader.UserAgent.ToString(), UserAgent);
                        HttpResponseMessage response;

                        if (НазваниеУрока.SelectedIndex < НовыйАлгоритм)
                        {
                            //Получаем новый user_id
                            response = await client.PostAsync("https://form.datalesson.ru/api/v1/auth",
                                                              new StringContent(RandLoginRequest(), Encoding.UTF8, "application/json"));

                            if (!response.IsSuccessStatusCode)
                            {
                                throw new Exception(string.Format(SiteUnavailable, "form.datalesson.ru"));
                            }

                            //Обработка ответа
                            LoginResponse loginResponse = JsonConvert.DeserializeObject <LoginResponse>(await response.Content.ReadAsStringAsync());
                            if (loginResponse.data != null)
                            {
                                user_id = loginResponse.data.user_id;
                            }
                            else if (loginResponse.error != null)
                            {
                                throw new Exception($"{loginResponse.error.code}: {loginResponse.error.descrption}");
                            }
                            else
                            {
                                throw new Exception(GettingIdError);
                            }
                            if (new Regex(@"[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}", RegexOptions.IgnoreCase).IsMatch(user_id))
                            {
                                //Загрузка сертификата
                                response = await client.GetAsync("https://form.datalesson.ru/api/v1/certificates/student/" +
                                                                 $"{user_id}?challenge_type={Уроки[НазваниеУрока.SelectedIndex].Тренажер}&name={ИмяПользователя.Text}");

                                if (!response.IsSuccessStatusCode)
                                {
                                    throw new Exception("Ошибка получения сертификата. Повторите попытку позднее.");
                                }
                                else
                                {
                                    string FileName = $"{Уроки[НазваниеУрока.SelectedIndex].Название}.pdf";
                                    if (GetSaveFileName(ref FileName))
                                    {
                                        using (var ms = await response.Content.ReadAsStreamAsync())
                                            using (var fs = File.Create(FileName))
                                            {
                                                ms.Seek(0, SeekOrigin.Begin);
                                                ms.CopyTo(fs);
                                            }
                                        MessageBox.Show("Сертификат успешно сохранён.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                                    }
                                    else
                                    {
                                        MessageBox.Show("Сохранение сертификата отменено.", "Информация", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception(MissingData);
                            }
                        }
                        else
                        {
                            //Грузим главную страницу. Получаем куки, парсим данные
                            response = await client.GetAsync($"https://xn--h1adlhdnlo2c.xn--p1ai/?rnd={rand.Next()}");

                            if (!response.IsSuccessStatusCode)
                            {
                                throw new Exception(string.Format(SiteUnavailable, "урокцифры.рф"));
                            }

                            string buffer = await response.Content.ReadAsStringAsync();

                            //Переменные
                            string     _token  = string.Empty;
                            List <int> regions = new List <int>();

                            //Парсим токен
                            Match match = new Regex(@"name=_token\s+value=([A-z\d]{40})").Match(buffer);
                            if (match.Success)
                            {
                                _token = match.Groups[1].Value;

                                //Парсим регионы
                                int startIndex = buffer.IndexOf("<select name=id_region");
                                if (startIndex == -1)
                                {
                                    throw new Exception(MissingData);
                                }
                                int length = buffer.Substring(startIndex).IndexOf("</select>");
                                if (length == -1)
                                {
                                    throw new Exception(MissingData);
                                }
                                if (!ParseList(buffer.Substring(startIndex, length), ref regions))
                                {
                                    throw new Exception(MissingData);
                                }
                            }
                            else
                            {
                                throw new Exception(MissingData);
                            }

                            //Переменные
                            List <int> cities = new List <int>(), countries = new List <int>();
                            bool       not_from_russia = Convert.ToBoolean(rand.Next(2));
                            int        id_region = RandomListValue(regions), id_city = 0, id_country = 0;

                            if (not_from_russia) //Если не из рашки
                            //Парсим страны
                            {
                                response = await client.GetAsync($"https://xn--h1adlhdnlo2c.xn--p1ai/load-countries?rnd={rand.Next()}");
                            }
                            else //Из рашки
                                 //Парсим города
                            {
                                response = await client.GetAsync($"https://xn--h1adlhdnlo2c.xn--p1ai/load-region-cities?rnd={rand.Next()}" +
                                                                 $"&id={id_region}&id_city=undefined");
                            }
                            if (!response.IsSuccessStatusCode)
                            {
                                throw new Exception(string.Format(SiteTemporaryUnavailable, "урокцифры.рф"));
                            }
                            if (!ParseList(await response.Content.ReadAsStringAsync(), ref countries))
                            {
                                throw new Exception(MissingData);
                            }
                            if (not_from_russia) //Если не из рашки
                            {
                                id_country = RandomListValue(countries);
                            }
                            else
                            {
                                id_city = RandomListValue(cities);
                            }

                            //Переменные
                            string type   = new string[] { "pupil", "parent", "teacher" }[rand.Next(3)];
                            int    age_id = rand.Next(3); //тренажёр[1-4][5-7][8-11]

                            //Получаем новый user_id
                            response = await client.PostAsync("https://xn--h1adlhdnlo2c.xn--p1ai/trainer/send-request",
                                                              new StringContent(string.Join("&", new Dictionary <string, string>
                            {
                                { "type", type
                                  + (not_from_russia ? "&not_from_russia=on" : string.Empty) },
                                { "id_country", id_country.ToString() },
                                { "id_region", not_from_russia ? string.Empty : id_region.ToString() },
                                { "id_city", not_from_russia ? string.Empty : id_city.ToString() },
                                { "grade", type == "teacher" ? string.Empty : RandomGradeByAgeId(age_id).ToString() },
                                { "pass_type", "self" },
                                { "id_trainer", Уроки[НазваниеУрока.SelectedIndex].Тренажеры[age_id].ToString() },
                                { "id_lesson", Уроки[НазваниеУрока.SelectedIndex].Урок.ToString() },
                                { "_token", _token },
                                { "passType", "self" },
                            }.Select(x => x.Key + "=" + x.Value).ToArray()),
                                                                                Encoding.UTF8, "application/x-www-form-urlencoded"));

                            if (!response.IsSuccessStatusCode)
                            {
                                throw new Exception(GettingIdError);
                            }

                            //Обработка ответа
                            SendRequestResponse srr = JsonConvert.DeserializeObject <SendRequestResponse>(await response.Content.ReadAsStringAsync());
                            if (srr.status)
                            {
                                match = new Regex(@"[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}", RegexOptions.IgnoreCase).Match(srr.url);
                                if (match.Success)
                                {
                                    user_id = match.Value;

                                    MessageBox.Show("Страница выдачи сертификата будет открыта в браузере.", "Информация",
                                                    MessageBoxButton.OK, MessageBoxImage.Information);
                                    //Открытие страница выдачи сертификата в браузере
                                    Process.Start(Уроки[НазваниеУрока.SelectedIndex].Ссылка.Replace("{user_id}", user_id));
                                }
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        error_text = ex.Message;
                    }
                    catch (Exception ex)
                    {
                        error_text = ex.Message;
                    }
                    if (!string.IsNullOrEmpty(error_text))
                    {
                        MessageBox.Show($"Ошибка получения сертификата.\n{error_text}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                finally
                {
                    ПолучитьСертификат.IsEnabled = true;
                }
        }