コード例 #1
44
        private void GetEmail(Int64 index)
        {
            using (var request = new HttpRequest())
            {
                request.CharacterSet = Encoding.UTF8;
                string url = "https://otvet.mail.ru/question/" + index.ToString();

                var line = request.Get(url).ToString();

                if (!String.IsNullOrEmpty(line))
                    ParseEmail(line);
            }
        }
コード例 #2
36
ファイル: Vk.cs プロジェクト: Undermove/SimplePhotoPost
        private string vkMethod (string methodName, string parameters)
        {
            using (var req = new xNet.HttpRequest())
            {
                var response = req.Get(String.Format("https://api.vk.com/method/{0}?{1}&access_token={2}", methodName, parameters, this.accessToken)).ToString();
                

                /*var json = JObject.Parse(response);
                //var jCheck = json["error"]["error_code"] as JValue;
                if (json == null)
                {
                    throw new Exception("Ошибка в формате отправки. Проверьте правильно ли вы ввели ID группы и ID альбома.");
                }*/

                return response;
            }
        }
コード例 #3
0
ファイル: translating.cs プロジェクト: DSVAR/Yandex-Api
        static public void translate()
        {
            if (detectedLanguage.decte == true)
            {
                while (true)
                {
                    var post = new xNet.HttpRequest();

                    try {
                        getgive = post.Post("https://translate.yandex.net/api/v1.5/tr.json/translate?" +
                                            "key=trnsl.1.1.20191207T155655Z.98fc42dcc71b1955.5a64a70d4dcb416d72248a2f5ac02b7eda46213c" +
                                            "&text=" + detectedLanguage.lo + "&lang=" + detectedLanguage.lang + "-" + RK.theSecond).ToString();
                    }
                    catch
                    {
                        MessageBox.Show("Проверьте подключение к сети");
                    }
                    var json = JObject.Parse(getgive);

                    JToken translate = json["text"][0];
                    rich.Invoke((MethodInvoker)(() => rich.Text = translate.ToString()));

                    detectedLanguage.decte = false;
                    break;
                }
            }
            else
            {
            }
        }
コード例 #4
0
        public string  RegaCall(string B24_URL, string LeadID, string Comment, string actok, string USER_PHONE_INNER, string PHONE_NUMBER)
        {
            // string operb24 = GetIdUserB24(B24_URL, actok, USER_PHONE_INNER);
            var data = new
            {
                fields = new
                {
                    OWNER_TYPE_ID  = 1,
                    OWNER_ID       = LeadID,
                    TYPE_ID        = 2,
                    COMMUNICATIONS = new[]
                    {
                        new{ VALUE = PHONE_NUMBER }
                    },
                    SUBJECT        = "Новое дело",
                    COMPLETED      = "N",
                    RESPONSIBLE_ID = "1",
                    DESCRIPTION    = Comment
                }
            };
            string contentText = JsonConvert.SerializeObject(data).ToString();

            string content;

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                content = request.Post("https://" + B24_URL + "/rest/crm.activity.add?auth=" + actok, contentText, "application/json").ToString();
            }

            return("ok");
        }
コード例 #5
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int         k    = 1;
            HttpRequest http = new HttpRequest();

            http.ConnectTimeout = 3500;
            string html = http.Get("https://couponscorpion.com/category/100-off-coupons/page/" + k + "/").ToString();
            Regex  reg  = new Regex(@"<div class=""news-community category_udemy-coupon-code-2021 category_udemy .*?</div>.*?<a href=""(?<Link>.*?)"" target=""_blank"">", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline);

            foreach (Match item in reg.Matches(html))
            {
                foreach (Capture i in item.Groups["Link"].Captures)
                {
                    HttpRequest http2 = new xNet.HttpRequest();
                    http2.ConnectTimeout = 1500;
                    string html_get_udemy = http2.Get(i.ToString()).ToString();

                    Regex reg_udemy = new Regex(@"var sf_offer_url = '(?<Link>.*?)';", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline);
                    foreach (Match item_udemy in reg_udemy.Matches(html_get_udemy))
                    {
                        foreach (Capture i_udemy in item_udemy.Groups["Link"].Captures)
                        {
                            xNetStandart.HttpRequest http3 = new xNetStandart.HttpRequest();
                            http3.ConnectTimeout = 4000;
                            System.Uri html_res = http3.Get("https://couponscorpion.com/scripts/udemy/out.php?go=" + i_udemy.ToString()).Address;
                        }
                    }
                }
            }
            //HttpRequest http = new HttpRequest();
            //http.ConnectTimeout = 3500;
            //string html = http.Get("https://couponscorpion.com/teaching-academics/master-work-time-for-gmat-gre-cat-competitive-exam/").ToString();
        }
コード例 #6
0
        //получаем ид оператора битрикс24
        public string GetIdUserB24(string B24_URL, string actok, string USER_PHONE_INNER)
        {
            string operb24 = "1";

            if (USER_PHONE_INNER != "0")
            {
                var data7 = new
                {
                    filter = new
                    {
                        UF_PHONE_INNER = USER_PHONE_INNER
                    }
                };
                string contentText7 = JsonConvert.SerializeObject(data7).ToString();

                string content7;
                using (xNet.HttpRequest request7 = new xNet.HttpRequest())
                {
                    content7 = request7.Post("https://" + B24_URL + "/rest/user.get.json?auth=" + actok, contentText7, "application/json").ToString();
                }
                var     converter7 = new ExpandoObjectConverter();
                dynamic otvetst7   = JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(content7, converter7);
                try { operb24 = otvetst7.result[0].ID.ToString(); }
                catch { operb24 = "1"; }
            }
            return(operb24);
        }
コード例 #7
0
        public int Transfer(string B24_URL, string actok, string CALL_GUID, string NUMBER_HIDE, string NUMBER_SHOW)
        {
            string hideuser = GetIdUserB24(B24_URL, actok, NUMBER_HIDE);

            System.Threading.Thread.Sleep(100);
            string showuser = GetIdUserB24(B24_URL, actok, NUMBER_SHOW);

            System.Threading.Thread.Sleep(100);

            var data = new
            {
                CALL_ID = CALL_GUID,
                USER_ID = hideuser
            };
            string content = JsonConvert.SerializeObject(data).ToString();

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                string cont = request.Post("https://" + B24_URL + "/rest/telephony.externalcall.hide.json?auth=" + actok, content, "application/json").ToString();
            }
            System.Threading.Thread.Sleep(100);
            var data2 = new
            {
                CALL_ID = CALL_GUID,
                USER_ID = showuser
            };
            string content2 = JsonConvert.SerializeObject(data2).ToString();

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                string cont = request.Post("https://" + B24_URL + "/rest/telephony.externalcall.show.json?auth=" + actok, content2, "application/json").ToString();
            }

            return(1);
        }
コード例 #8
0
        // определяем пользователя битрикс24
        public List <string> GetIdUsersB24(string B24_URL, string actok, string[] USER_PHONE_INNER)
        {
            List <string> operb24 = new List <string>();

            var data7 = new
            {
                filter = new
                {
                    UF_PHONE_INNER = USER_PHONE_INNER
                }
            };
            string contentText7 = JsonConvert.SerializeObject(data7).ToString();

            string content7;

            using (xNet.HttpRequest request7 = new xNet.HttpRequest())
            {
                content7 = request7.Post("https://" + B24_URL + "/rest/user.get.json?auth=" + actok, contentText7, "application/json").ToString();
            }
            var     converter7 = new ExpandoObjectConverter();
            dynamic otvetst7   = JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(content7, converter7);

            foreach (var item in  otvetst7.result)
            {
                operb24.Add(item.ID);
            }
            return(operb24);
        }
コード例 #9
0
ファイル: speller.cs プロジェクト: DSVAR/Yandex-Api
        static public void spool()
        {
            test = text.Text;

            var post = new xNet.HttpRequest();

            //  var por = new xNet.HttpResponse();
            try {
                get = post.Get("https://speller.yandex.net/services/spellservice.json/checkText?text=" + test).ToString();
                var    mar   = JArray.Parse(get);
                JToken spell = mar[0]["s"];
                kol = spell.Count();

                for (int j = 0; j < kol; j++)
                {
                    if (j != kol)
                    {
                        brut += spell[j] + ", ";
                    }
                    else
                    {
                        brut += spell[j] + ". ";
                    }
                }



                message.Invoke((MethodInvoker)(() => message.Text = brut));
                brut = null;
            }
            catch
            {
                MessageBox.Show("Проверьте подключение к сети");
            }
        }
コード例 #10
0
        public List <Custumer> GetCostumers(string telef)
        {
            List <Custumer> listuser = new List <Custumer>();
            string          token    = CreatLidAlfa();
            var             data     = new
            {
                page  = 0,
                phone = telef
            };
            string contentText = JsonConvert.SerializeObject(data).ToString();

            using (xNet.HttpRequest reqtok = new xNet.HttpRequest())
            {
                reqtok.AddHeader("X-ALFACRM-TOKEN", token);
                string  content   = reqtok.Post("https://legionsport.s20.online/v2api/1/customer/index", contentText, "application/json").ToString();
                var     converter = new ExpandoObjectConverter();
                dynamic obj       = JsonConvert.DeserializeObject <ExpandoObject>(content, converter);

                foreach (var item in obj.items)
                {
                    Custumer user = new Custumer();
                    user.Id       = item.id;
                    user.BierzDay = item.dob;
                    user.FullName = item.name;
                    user.Object   = item.custom_obekt;
                    user.Gruop    = item.custom_gruppa;
                    user.Telef1   = item.phone[0];
                    user.Telef2   = item.phone[1];
                    listuser.Add(user);
                }
            }
            return(listuser);
        }
コード例 #11
0
        public ActionResult Index(string code = "", string referer = "", string client_id = "", string from_widget = "")
        {
            string pach = System.Web.Hosting.HostingEnvironment.MapPath("/logamo.txt");

            System.IO.StreamWriter myfile = new System.IO.StreamWriter(pach, true);
            try
            {
                myfile.WriteLine(DateTime.Now.ToString() + "--Install--code:" + code + "--referer:" + referer + "--client_id:" + client_id + "--\n\n");
            }
            catch
            {
                myfile.WriteLine(DateTime.Now.ToString() + "Ошибка логирования--\n\n");
            }
            myfile.Close();
            myfile.Dispose();

            if (!string.IsNullOrEmpty(code))
            {
                var data = new
                {
                    client_id     = amoFunction.ClienID,
                    client_secret = amoFunction.ClientSecret,
                    grant_type    = "authorization_code",
                    code          = code,
                    redirect_uri  = amoFunction.RedirectUrl
                };
                string contentText = JsonConvert.SerializeObject(data).ToString();
                string content;
                using (xNet.HttpRequest request = new xNet.HttpRequest())
                {
                    content = request.Post("https://" + referer + "/oauth2/access_token", contentText, "application/json").ToString();
                }
                var     converter = new ExpandoObjectConverter();
                dynamic obj       = JsonConvert.DeserializeObject <ExpandoObject>(content, converter);

                amoCompan co = _db.amoCompans.Where(p => p.PortalName == referer).FirstOrDefault();
                if (co == null)
                {
                    amoCompan comp = new amoCompan();
                    comp.AcesTok    = obj.access_token;
                    comp.DTRefTok   = DateTime.Now.AddSeconds(86400);
                    comp.DTSetApp   = DateTime.Now;
                    comp.PortalName = referer;
                    comp.RefTok     = obj.refresh_token;
                    _db.amoCompans.Add(comp);
                    _db.SaveChanges();
                }
                else
                {
                    co.AcesTok          = obj.access_token;
                    co.DTRefTok         = DateTime.Now.AddSeconds(86400);
                    co.RefTok           = obj.refresh_token;
                    _db.Entry(co).State = System.Data.Entity.EntityState.Modified;
                    _db.SaveChanges();
                }
            }

            //  Response.Headers.Add("Access-Control-Allow-Origin", "https://service-axatel.ru");
            return(View());
        }
コード例 #12
0
        //public ActionResult Test()
        //{
        //    // string text = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath("/text.txt"));
        //    var data = new
        //    {
        //        AMO_URL = "xecoli8508.amocrm.ru",
        //        PHONE_NUMBER = "80261691950",
        //        AXATEL_GUID = "ceb9906c-0a24-4d7b-a8f4-f6e8f381c355"


        //    };
        //    string contentText2 = JsonConvert.SerializeObject(data).ToString();
        //    string content;
        //    using (xNet.HttpRequest request = new xNet.HttpRequest())
        //    {
        //        content = request.Post("http://localhost:8098/amo/method/reg", contentText2, "application/json").ToString();
        //    }
        //    var converter = new ExpandoObjectConverter();
        //    dynamic obj4 = JsonConvert.DeserializeObject<ExpandoObject>(content, converter);

        //    return Content("9");

        //}
        public ActionResult Test()
        {
            // string text = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath("/text.txt"));
            var data = new
            {
                AMO_URL          = "xecoli8508.amocrm.ru",
                PHONE_NUMBER     = "80291554499",
                AXATEL_GUID      = "ceb9906c-0a24-4d7b-a8f4-f6e8f381c355",
                CALL_FINISH_DATE = "2020-03-20 17:34:09",
                DURATION         = 65,
                VI_STATUS        = 6,
                TYPE             = "inbound",
                USER_PHONE_INNER = "300",
                URL = "/callrecords/domains/axata.a1.axatel.by/data/20200520/mtezmjywnjk0ma53d5.mp3"
            };
            string contentText2 = JsonConvert.SerializeObject(data).ToString();
            string content;

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                content = request.Post("http://localhost:62415/method/amo/finish", contentText2, "application/json").ToString();
            }
            var     converter = new ExpandoObjectConverter();
            dynamic obj4      = JsonConvert.DeserializeObject <ExpandoObject>(content, converter);

            return(Content("9"));
        }
コード例 #13
0
        private async Task MessageReceivedAsync(SocketMessage message)
        {
            if (message.Author.Id == _client.CurrentUser.Id)
            {
                return;
            }

            if (message.Channel is SocketDMChannel)
            {
                if (message.Content.Split(' ').Length == 2)
                {
                    settings = JsonConvert.DeserializeObject <SettingsJSON>(File.ReadAllText("settings.json"));
                    using (var request = new xNet.HttpRequest())
                    {
                        try
                        {
                            string[] data = message.Content.Split(' ');
                            request.UserAgent = Http.ChromeUserAgent();
                            request.Cookies   = new CookieDictionary();
                            request.AddHeader("XF-Api-Key", settings.xfToken);
                            var         response      = request.Post(settings.xfUri + "/api/auth", "login="******"&password="******"application/x-www-form-urlencoded").ToString();
                            XenforoJSON response_data = JsonConvert.DeserializeObject <XenforoJSON>(response);

                            if (response.Contains("success") && response_data != null && response_data.success != null && response_data.User != null)
                            {
                                int max_group = response_data.User.user_group_id;
                                foreach (int group in (int[])response_data.User.secondary_group_ids)
                                {
                                    int place = Array.IndexOf(settings.groupsHierarchy, group);
                                    max_group = max_group > place ? max_group : place;
                                }
                                var        user = message.Author as SocketGuildUser;
                                SocketRole role = user.Guild.GetRole(settings.groups[max_group].dsRoleId);
                                // TODO: можете также работать с данными полученного класса, например, для выдачи роли стаффа или добавления в какую-нибудь рассылку
                                await user.AddRoleAsync(role);

                                await message.Author.SendMessageAsync("Успешно");
                            }
                            else
                            {
                                await message.Author.SendMessageAsync("Неверный логин и/или пароль");
                            }
                        }
                        catch (Exception ex)
                        {
                            await message.Author.SendMessageAsync("Во время авторизации возникла ошибка: " + ex.Message);
                        }
                    }
                }
            }
            else
            if (message.Content == "!auth")
            {
                await message.Author.SendMessageAsync("Для авторизации в системе и получения соответствущей вам роли, отправьте в текущий диалог свой логин и пароль от форума MYPASTE.COM в формате log{пробел}pass");
            }
        }
コード例 #14
0
        // ложим трубку
        public int FinishCall(string CALL_Guid, string B24_URL, string INNER_PHONE, string DURATION, string VI_STATUS, string FAILED_REASON, string VOTE, string CALL_FINISH_DATE, string actok, string PROCES_STATUS)
        {
            string operb24 = GetIdUserB24(B24_URL, actok, INNER_PHONE);
            object data;

            if (VI_STATUS == "304")
            {
                data = new
                {
                    CALL_ID = CALL_Guid,
                    USER_ID = operb24,

                    STATUS_CODE   = VI_STATUS,
                    FAILED_REASON = FAILED_REASON,
                    VOTE          = VOTE
                };
            }
            else
            {
                data = new
                {
                    CALL_ID       = CALL_Guid,
                    USER_ID       = operb24,
                    DURATION      = DURATION,
                    STATUS_CODE   = VI_STATUS,
                    FAILED_REASON = FAILED_REASON,
                    VOTE          = VOTE,
                    RECORD_URL    = "https://service-axatel.ru:8099/content/zapisvobrabotke.mp3"
                };
            }

            string contentText = JsonConvert.SerializeObject(data).ToString();
            string content     = "";

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                content = request.Post("https://" + B24_URL + "/rest/telephony.externalcall.finish.json?auth=" + actok, contentText, "application/json").ToString();
            }
            string pach = System.Web.Hosting.HostingEnvironment.MapPath("/logb24.txt");

            System.IO.StreamWriter myfile = new System.IO.StreamWriter(pach, true);
            try
            {
                myfile.WriteLine(DateTime.Now.ToString() + "--FinishCallB24--Content: " + content + "--\n\n");
            }
            catch
            {
                myfile.WriteLine(DateTime.Now.ToString() + "--FinishCallB24--Ошибка логирования!--\n\n");
            }
            myfile.Close();
            myfile.Dispose();
            return(1);
        }
コード例 #15
0
        public string GetUserMobNumb(string B24_URL, string actok, string USER_ID)
        {
            string usernumb = "";
            string content  = "";

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                content = request.Get("https://" + B24_URL + "/rest/user.get.json?id=" + USER_ID + "&auth=" + actok).ToString();
            }
            var     converter = new ExpandoObjectConverter();
            dynamic obj       = JsonConvert.DeserializeObject <ExpandoObject>(content, converter);

            return(usernumb = obj.result[0].PERSONAL_MOBILE.ToString());
        }
コード例 #16
0
        public string Zvonok(string call_id, string direction, string remote_number)
        {
            RequestParams reqpar = new RequestParams();

            reqpar["event"]         = "alert";
            reqpar["call_id"]       = call_id;
            reqpar["direction"]     = direction;
            reqpar["remote_number"] = remote_number;
            using (xNet.HttpRequest reqtok = new xNet.HttpRequest())
            {
                string content = reqtok.Post("https://legionsport.s20.online/api/1/sip/process?token=c4ca4238a0b923820dcc509a6f75849b", reqpar).ToString();
            }
            return("ok");
        }
コード例 #17
0
        public string Active(string call_id, string direction, string remote_number)
        {
            RequestParams reqpar2 = new RequestParams();

            reqpar2["event"]         = "active";
            reqpar2["call_id"]       = call_id;
            reqpar2["direction"]     = direction;
            reqpar2["remote_number"] = remote_number;
            using (xNet.HttpRequest request2 = new xNet.HttpRequest())
            {
                xNet.HttpResponse content2 = request2.Post("https://legionsport.s20.online/api/1/sip/process?token=c4ca4238a0b923820dcc509a6f75849b", reqpar2);
            }
            return("ok");
        }
コード例 #18
0
        // Постит фотгафии в ответ возвращая массив айдишников последних добавленных фотографий
        public string[] photoPost(string groupId, string albumId, string[] photos)
        {
            // Получаем ответ от сервера в формате JSON group_id - должен быть положительным, то есть минус не нужен!!!
            string response = vkMethod("photos.getUploadServer", String.Format("group_id={0}&album_id={1}", groupId, albumId));


            // Получаем ссылку на сервер, которую можно использовать для загрузки фотки путем обработки JSON запроса
            var json = JObject.Parse(response);
            // Отлавливаем ошибку в случае если пользователь что-то не так ввел и отправил это на сервер

            /*var jCheck = json["error"]["error_code"] as JValue;
             * if (jCheck == null)
             * {
             *  throw new Exception("Ошибка в формате отправки. Проверьте правильно ли вы ввели ID группы и ID альбома.");
             * }*/
            var strUrl = json["response"]["upload_url"] as JValue;



            Uri upploadUrl = new Uri(strUrl.ToString());

            // составляем POST запрос при помощи которого отправляем фотографии на сервер
            string[] photoWallArray = photos;
            using (var req = new xNet.HttpRequest())
            {
                if (photos.Length != 0)
                {
                    for (int photoNumber = 0; photoNumber < photos.Length; photoNumber++)
                    {
                        req.AddFile("file1", photos[photoNumber]);
                        string getUpload = req.Post(upploadUrl).ToString();

                        json = JObject.Parse(getUpload);
                        var server     = json["server"] as JValue;
                        var photosList = json["photos_list"] as JValue;
                        var hash       = json["hash"] as JValue;

                        response = vkMethod("photos.save", String.Format("group_id={0}&album_id={1}&server={2}&photos_list={3}&hash={4}&", groupId, albumId, server, photosList, hash));

                        json = JObject.Parse(response);
                        var photoId = (string)json["response"][0]["pid"];

                        photoWallArray[photoNumber] = photoId;
                    }
                }
            }
            return(photoWallArray);
        }
コード例 #19
0
        public ActionResult ClickToCall(int userid, string tel)
        {
            string pach = System.Web.Hosting.HostingEnvironment.MapPath("/logamo.txt");

            System.IO.StreamWriter myfile = new System.IO.StreamWriter(pach, true);
            try
            {
                myfile.WriteLine(DateTime.Now.ToString() + "--ClickToCall--userid:" + userid + "--tel:" + tel + "--\n\n");
            }
            catch
            {
                myfile.WriteLine(DateTime.Now.ToString() + "Ошибка логирования--\n\n");
            }
            myfile.Close();
            myfile.Dispose();
            amoOperator oper = _db.amoOperators.Where(i => i.AmoId == userid).FirstOrDefault();

            if (oper == null)
            {
                return(Content("оператор не найден"));
            }
            amoCompan co       = _db.amoCompans.Where(i => i.Id == oper.PortalId).FirstOrDefault();
            string    guid     = Guid.NewGuid().ToString();
            var       datasend = new
            {
                entity  = "callmanager",
                action  = "init_call",
                options = new
                {
                    USER_PHONE_INNER = oper.InerNumb,
                    PHONE_NUMBER     = tel,
                    AMO_URL          = co.PortalName,
                    AXATEL_GUID      = co.AxatelGuid,
                    CALL_GUID        = guid,
                    TYPE             = "INTERCOM"
                }
            };

            string contentText = JsonConvert.SerializeObject(datasend).ToString();
            string content;

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                content = request.Post("http://" + co.BackIp + "/api/token/v1/" + co.BackToken, contentText, "application/json").ToString();
            }
            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            return(Json(new { result = "ok" }, JsonRequestBehavior.AllowGet));
        }
コード例 #20
0
        public int HideCard(string B24_URL, string actok, string[] USER_PHONE_INNER, string CALL_GUID)
        {
            string[] usersids = GetIdUsersB24(B24_URL, actok, USER_PHONE_INNER).ToArray();
            var      data     = new
            {
                CALL_ID = CALL_GUID,
                USER_ID = usersids
            };
            string content = JsonConvert.SerializeObject(data).ToString();

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                string cont = request.Post("https://" + B24_URL + "/rest/telephony.externalcall.hide.json?auth=" + actok, content, "application/json").ToString();
            }
            return(1);
        }
コード例 #21
0
 public static bool CheckMachine()
 {
     #region Khai báo request
     xNet.HttpRequest request = new xNet.HttpRequest();
     request.KeepAlive = true;
     request.Cookies   = new CookieDictionary();
     request.AddHeader(HttpHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
     request.AddHeader(HttpHeader.AcceptLanguage, "en-US,en;q=0.5");
     request.UserAgent = Http.ChromeUserAgent();
     #endregion
     string ck = request.Get(fLogin.domain + "CheckMachine/?RequestKey=" + md5(md5(GetHDDSerialNumber()) + "handsome") + "&MachineSerial=" + md5(GetHDDSerialNumber()) + "&SoftIndex=" + fLogin.softIndex).ToString();
     if (ck == "true")
     {
         return(true);
     }
     return(false);
 }
コード例 #22
0
        private string vkMethod(string methodName, string parameters)
        {
            using (var req = new xNet.HttpRequest())
            {
                var response = req.Get(String.Format("https://api.vk.com/method/{0}?{1}&access_token={2}", methodName, parameters, this.accessToken)).ToString();


                /*var json = JObject.Parse(response);
                 * //var jCheck = json["error"]["error_code"] as JValue;
                 * if (json == null)
                 * {
                 *  throw new Exception("Ошибка в формате отправки. Проверьте правильно ли вы ввели ID группы и ID альбома.");
                 * }*/

                return(response);
            }
        }
コード例 #23
0
        //Закрытый метод для получения и записи Токенов авторизации
        private void RefSetToken(string portal)
        {
            amoCompan conm = _db.amoCompans.Where(i => i.PortalName == portal).FirstOrDefault();

            // если токен свежий то выходим
            if (conm.DTRefTok.AddSeconds(-10) > DateTime.Now)
            {
                return;
            }

            xNet.HttpResponse resp2 = null;
            var data = new
            {
                client_id     = amoFunction.ClienID,
                client_secret = amoFunction.ClientSecret,
                grant_type    = "refresh_token",
                refresh_token = conm.RefTok,
                redirect_uri  = amoFunction.RedirectUrl
            };
            string contentText = JsonConvert.SerializeObject(data).ToString();

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                resp2 = request.Post("https://" + portal + "/oauth2/access_token", contentText, "application/json");

                //Если в ответ получаем статус-код отличный от 200, то это ошибка, вызываем исключение
                if (resp2.StatusCode != HttpStatusCode.OK)
                {
                    throw new FormatException("ErrorLogonBitrixOAuth");
                }
                else
                {
                    string  stringLogonBitrixOAuth = resp2.ToString();
                    var     converter           = new ExpandoObjectConverter();
                    dynamic objLogonBitrixOAuth = JsonConvert.DeserializeObject <ExpandoObject>(stringLogonBitrixOAuth, converter);
                    //Записывем Токены авторизации в поля нашего класса из динамического объекта
                    conm.AcesTok          = objLogonBitrixOAuth.access_token;
                    conm.RefTok           = objLogonBitrixOAuth.refresh_token;
                    conm.DTRefTok         = DateTime.Now.AddSeconds(objLogonBitrixOAuth.expires_in); //Добавляем к текущей дате количество секунд действия токена, обычно это плюс один час
                    _db.Entry(conm).State = System.Data.Entity.EntityState.Modified;
                    _db.SaveChanges();
                }
            }
        }
コード例 #24
0
        public string Close(string call_id, string direction, string remote_number, string USER_PHONE_INNER, string DURATION, string VI_STATUS, string finish_reason, string RECORD_URL)
        {
            RequestParams reqpar3 = new RequestParams();

            reqpar3["event"]         = "release";
            reqpar3["call_id"]       = call_id;
            reqpar3["direction"]     = direction;
            reqpar3["local_number"]  = USER_PHONE_INNER;
            reqpar3["duration"]      = DURATION;
            reqpar3["is_success"]    = VI_STATUS;
            reqpar3["remote_number"] = remote_number;
            reqpar3["finish_reason"] = finish_reason;
            reqpar3["record_url"]    = RECORD_URL;
            using (xNet.HttpRequest request3 = new xNet.HttpRequest())
            {
                xNet.HttpResponse content3 = request3.Post("https://legionsport.s20.online/api/1/sip/process?token=c4ca4238a0b923820dcc509a6f75849b", reqpar3);
            }
            return("ok");
        }
コード例 #25
0
ファイル: AuthController.cs プロジェクト: klusha/VK
 public RedirectResult GetToken(string code)
 {
     List<String> userInfo = new List<String>();
     JSONMaster master = new JSONMaster();
     using (var request = new xNet.HttpRequest())
     {
         String uri = string.Format(
                 "https://oauth.vk.com/access_token?client_id={0}&client_secret={1}&redirect_uri={2}&code={3}",
                 AppID,
                 client_secret,
                 redirect_uri,
                 code);
         String data = request.Get(uri).ToString();
         userInfo.AddRange(master.GetAccessToken(data));
     }
     String url = string.Format("http://localhost:61745/UserData/CreateUser?user_id={0}&token={1}",
                     userInfo.ElementAt(1),
                     userInfo.ElementAt(0));
     return Redirect(url);
 }
コード例 #26
0
        private void button14_Click(object sender, EventArgs e)
        {
            xNet.HttpRequest  req = new xNet.HttpRequest();
            xNet.HttpResponse resp;
            req.Cookies = new CookieDictionary();

            var urlParams = new RequestParams();

            calculate = HttpUtility.UrlEncode(textBox1.Text);

            urlParams["calc"] = calculate;
            resp = req.Get("http://localhost/site.local/www/index_calc.php", urlParams);
            string json = resp.ToString();

            JObject data   = JObject.Parse(json);
            string  result = (string)data["result"];

            textBox1.Text = result;
            label1.Text   = "";
        }
コード例 #27
0
ファイル: Spam.cs プロジェクト: Merzix/SpamDelivery
        /// <summary>
        /// Отсылает сообщение пользователю
        /// </summary>
        /// <param name="pupilId">Id пользователя на сайте</param>
        private static void SendSpam(int pupilId)
        {
            string url = $"http://www.videosharp.info/{pupilId}/messages";

            using (var request = new HttpRequest())
            {

                #region Настройка параметров Post запроса
                request.ConnectTimeout = TimeOutProxy;
                request.Reconnect = false;
                request.Proxy = HttpProxyClient.Parse(Proxy);
                //request.UserAgent = Http.IEUserAgent();
                request.Cookies = MyCookies;

                request.AddParam("answer", Message)
                    .AddParam("def_pupil_id", pupilId)
                    .AddParam("forum_fid", $"pupil={pupilId}");
                #endregion
                var content = "Empty";

                try
                {
                    content = request.Post(url).ToString(); //Пытаемся отправить Post запрос
                }
                catch
                {
                    LogResult(pupilId, ERROR);
                }

                #region Проверка и вывод на консоль результата отправки сообщения
                if (content.Contains("error"))
                    LogResult(pupilId, FAIL);

                else if (content.Contains("submit"))
                    LogResult(pupilId, SUCCESS);

                else
                    LogResult(pupilId, UNKNOWN);
                #endregion
            }
        }
コード例 #28
0
        // прикрепление записи
        public int Record(string CALL_Guid, string B24_URL, string FILE_CONTENT, string URL, string Ip, string AcesTok)
        {
            if (URL.IndexOf("http") == -1)
            {
                URL = "http://" + Ip + URL;
            }

            var data2 = new
            {
                CALL_ID    = CALL_Guid,
                FILENAME   = CALL_Guid + ".mp3",
                RECORD_URL = URL
            };
            string contentText2 = JsonConvert.SerializeObject(data2).ToString();

            using (xNet.HttpRequest request2 = new xNet.HttpRequest())
            {
                string content = request2.Post("https://" + B24_URL + "/rest/telephony.externalCall.attachRecord.json?auth=" + AcesTok, contentText2, "application/json").ToString();
            }

            return(1);
        }
コード例 #29
0
        // получаем токен для альфа СРМ
        public string CreatLidAlfa()
        {
            var data = new
            {
                email   = "*****@*****.**",
                api_key = "acf112e1-2de8-11e9-9333-0cc47a6ca50e"
            };
            string contentText = JsonConvert.SerializeObject(data).ToString();

            string tokenkey = "";

            using (xNet.HttpRequest reqtok = new xNet.HttpRequest())
            {
                string  content   = reqtok.Post("https://legionsport.s20.online/v2api/auth/login", contentText, "application/json").ToString();
                var     converter = new ExpandoObjectConverter();
                dynamic obj       = JsonConvert.DeserializeObject <ExpandoObject>(content, converter);

                tokenkey = obj.token;
            }

            return(tokenkey);
        }
コード例 #30
0
        public string RegLead(string B24_URL, string PHONE_NUMBER, string NameLead, string actok, string USER_PHONE_INNER)
        {
            string operb24 = GetIdUserB24(B24_URL, actok, USER_PHONE_INNER);
            var    data    = new
            {
                fields = new
                {
                    TITLE          = NameLead,
                    NAME           = "Имя лида " + PHONE_NUMBER,
                    SECOND_NAME    = "",
                    LAST_NAME      = "",
                    STATUS_ID      = "NEW",
                    OPENED         = "Y",
                    ASSIGNED_BY_ID = operb24,
                    CURRENCY_ID    = "BYN",

                    PHONE = new[]
                    {
                        new { VALUE = PHONE_NUMBER, VALUE_TYPE = "WORK" }
                    }
                },
                @params = new
                {
                    REGISTER_SONET_EVENT = "Y"
                }
            };
            string contentText = JsonConvert.SerializeObject(data).ToString();

            string content;

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                content = request.Post("https://" + B24_URL + "/rest/crm.lead.add?auth=" + actok, contentText, "application/json").ToString();
            }
            var     converter2 = new ExpandoObjectConverter();
            dynamic idlead     = JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(content, converter2);

            return(idlead.result.ToString());
        }
コード例 #31
0
ファイル: detectedLanguage.cs プロジェクト: DSVAR/Yandex-Api
        static public void deteck()
        {
            lang = null;
            //   label.Invoke((MethodInvoker) (()=>label.Text = "halalujah"));


            string floop = null;

            lo = text1.Text;

            var Post = new xNet.HttpRequest();

            for (int i = 0; i <= 1; i++)
            {
                try
                {
                    floop = Post.Post("https://translate.yandex.net/api/v1.5/tr.json/detect?" +
                                      "key=trnsl.1.1.20191207T155655Z.98fc42dcc71b1955.5a64a70d4dcb416d72248a2f5ac02b7eda46213c" +
                                      "&text=" + lo).ToString();
                }
                catch
                {
                    MessageBox.Show("Проверьте подключение к сети");
                }


                var json = JObject.Parse(floop);


                JToken dec = json["lang"];
                lang = dec.ToString();

                decte = true;

                //        text2.Invoke((MethodInvoker)(() => text2.Text = lang ));
            }
        }
コード例 #32
0
ファイル: Vk.cs プロジェクト: Undermove/SimplePhotoPost
        // Постит фотгафии в ответ возвращая массив айдишников последних добавленных фотографий
        public string[] photoPost(string groupId, string albumId, string[] photos)
        {
            // Получаем ответ от сервера в формате JSON group_id - должен быть положительным, то есть минус не нужен!!!
            string response = vkMethod("photos.getUploadServer", String.Format("group_id={0}&album_id={1}", groupId, albumId));


            // Получаем ссылку на сервер, которую можно использовать для загрузки фотки путем обработки JSON запроса
            var json = JObject.Parse(response);
            // Отлавливаем ошибку в случае если пользователь что-то не так ввел и отправил это на сервер
            /*var jCheck = json["error"]["error_code"] as JValue;
            if (jCheck == null)
            {
                throw new Exception("Ошибка в формате отправки. Проверьте правильно ли вы ввели ID группы и ID альбома.");
            }*/
            var strUrl = json["response"]["upload_url"] as JValue;

        


            Uri upploadUrl = new Uri(strUrl.ToString());

            // составляем POST запрос при помощи которого отправляем фотографии на сервер
            string[] photoWallArray = photos;
            using (var req = new xNet.HttpRequest())
            {
                if (photos.Length != 0)
                {
                    for (int photoNumber = 0; photoNumber < photos.Length; photoNumber++)
                    {
                        req.AddFile("file1", photos[photoNumber]);
                        string getUpload = req.Post(upploadUrl).ToString();

                        json = JObject.Parse(getUpload);
                        var server = json["server"] as JValue;
                        var photosList = json["photos_list"] as JValue;
                        var hash = json["hash"] as JValue;

                        response = vkMethod("photos.save", String.Format("group_id={0}&album_id={1}&server={2}&photos_list={3}&hash={4}&", groupId, albumId, server, photosList, hash));

                        json = JObject.Parse(response);
                        var photoId = (string)json["response"][0]["pid"];

                        photoWallArray[photoNumber] = photoId;
                    }
                }
            }
            return photoWallArray;
        }
コード例 #33
0
ファイル: HttpResponse.cs プロジェクト: krotya/xNet
        internal HttpResponse(HttpRequest request)
        {
            _request = request;

            ContentLength = -1;
            ContentType = string.Empty;
        }
コード例 #34
0
        /// <summary>
        /// Установка прокси HttpRequest объекту
        /// </summary>
        public void SetProxy(ref HttpRequest request,string line)
        {
            CallProxyMsg("Установка типа прокси");
            try {
                switch (proxy.ProxyType)
                {
                    case 0:
                        {
                            request.Proxy = request.Proxy = HttpProxyClient.Parse(line);
                            break;
                        }
                    case 1:
                        {
                            request.Proxy = request.Proxy = Socks4ProxyClient.Parse(line);
                            break;
                        }
                    case 2:
                        {
                            request.Proxy = request.Proxy = Socks5ProxyClient.Parse(line);
                            break;
                        }

                    default:
                        throw new Exception("Ошибка прокси.Не могу установить тип прокси.");
                }

                if (proxy.ProxyUseAuth)
                {
                    request.Proxy.Password = proxy.ProxyPassword;
                    request.Proxy.Username = proxy.ProxyLogin;
                }

                CallProxyMsg($"Установлен тип прокси {ProxyTypeGetString}");
            }
            catch
            {
                throw new Exception("Ошибка прокси.Не могу установить тип прокси.");
            }
        }
コード例 #35
0
ファイル: Form1.cs プロジェクト: DimaMudrakov/GitHubProject
        private string GetSourcePage()
        {
            string sourcePage = "";

            using (HttpRequest request = new HttpRequest())
            {
                request.CharacterSet = Encoding.UTF8;
                sourcePage = request.Get("http://www.ua-football.com/foreign/england").ToString();
            }
            return sourcePage;
        }
コード例 #36
0
ファイル: Form1.cs プロジェクト: vadimvv/Parser
        int GetCountPages()
        {
            string link = "http://sfs.gov.ua/baneryi/podatkovi-konsultatsii/konsultatsii-dlya-yuridichnih-osib/";
            string last_link = "";
            int countPages = 0;
            string pattern = "konsultatsii-dlya-yuridichnih-osib.page\\d*\">\\d*<.a><.div>";

            Regex newReg = new Regex(pattern);
            try
            {
                using (var Request = new HttpRequest())
                {
                    try
                    {
                        sitecode = Request.Get(link).ToString();
                    }
                    catch
                    {
                        error = "Немає доступу до сайту";
                        gonext = false;
                        return 0;
                    }
                    MatchCollection matches = newReg.Matches(sitecode);
                    last_link = matches[matches.Count - 1].Value;
                    countPages = Convert.ToInt32(last_link.Substring("konsultatsii-dlya-yuridichnih-osib/page", "\">"));
                }
            }
            catch
            {
                error = "Помилка! Не може порахувати к-сть всіх сторінок";
            }
            return countPages;
        }
コード例 #37
0
        private void btnSignup_Click(object sender, EventArgs e)
        {
            if (txtHoTen.Text == "" || txbSignupLink.Text == "" || txbSignupUser.Text == "" || txbSignupPass.Text == "" || txbSignupEmail.Text == "" || txbSignupPhone.Text == "")
            {
                MessageBox.Show("Vui lòng nhập đầy đủ thông tin", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //email
            int email = 1;

            try
            {
                MailAddress m = new MailAddress(txbSignupEmail.Text);
                email = 1;
            }
            catch (FormatException)
            {
                email = 0;
            }
            if (email == 0)
            {
                MessageBox.Show("Định dạng Email không đúng, vui lòng nhập lại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txbSignupEmail.Focus();
                return;
            }
            //link fb
            if (!txbSignupLink.Text.Contains("facebook"))
            {
                MessageBox.Show("Link facebook không đúng, vui lòng nhập lại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txbSignupLink.Focus();
                return;
            }


            //max ki tu
            if (txtHoTen.Text.Length > 250)
            {
                MessageBox.Show("Họ tên không được nhập quá 250 ký tự");
                txtHoTen.Focus();
                return;
            }

            if (txbSignupUser.Text.Length >= 251)
            {
                MessageBox.Show("Tài khoản không được nhập quá 250 ký tự");
                txbSignupUser.Focus();
                return;
            }

            if (txbSignupPass.Text.Length >= 251)
            {
                MessageBox.Show("Mật khẩu không được nhập quá 250 ký tự");
                txbSignupPass.Focus();
                return;
            }

            if (txbSignupEmail.Text.Length >= 251)
            {
                MessageBox.Show("Email không được nhập quá 250 ký tự");
                txbSignupEmail.Focus();
                return;
            }

            if (txbSignupPhone.Text.Length >= 251)
            {
                MessageBox.Show("Số điện thoại không được nhập quá 250 ký tự");
                txbSignupPhone.Focus();
                return;
            }

            if (txbSignupLink.Text.Length >= 251)
            {
                MessageBox.Show("Link facebook không được nhập quá 250 ký tự");
                txbSignupLink.Focus();
                return;
            }

            //min ky tu
            if (txbSignupUser.Text.Length < 6)
            {
                MessageBox.Show("Tài khoản phải có từ 6 ký tự trở lên!");
                txbSignupUser.Focus();
                return;
            }
            if (txbSignupPass.Text.Length < 6)
            {
                MessageBox.Show("Mật khẩu phải có từ 6 ký tự trở lên!");
                txbSignupPass.Focus();
                return;
            }

            if (txbSignupPhone.Text.Length < 10)
            {
                MessageBox.Show("Số điện thoại không đúng");
                txbSignupPhone.Focus();
                return;
            }


            //ko có dấu
            if (txbSignupUser.Text != convertToUnSign3(txbSignupUser.Text))
            {
                MessageBox.Show("Tài khoản không được có dấu tiếng tiệt!");
                txbSignupUser.Focus();
                return;
            }
            if (txbSignupPass.Text != convertToUnSign3(txbSignupPass.Text))
            {
                MessageBox.Show("Mật khẩu không được có dấu tiếng tiệt!");
                txbSignupPass.Focus();
                return;
            }
            if (txbSignupEmail.Text != convertToUnSign3(txbSignupEmail.Text))
            {
                MessageBox.Show("Email không được có dấu tiếng tiệt!");
                txbSignupEmail.Focus();
                return;
            }


            #region Khai báo request
            xNet.HttpRequest request = new xNet.HttpRequest();
            request.KeepAlive = true;
            request.Cookies   = new CookieDictionary();
            request.AddHeader(HttpHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            request.AddHeader(HttpHeader.AcceptLanguage, "en-US,en;q=0.5");
            request.UserAgent = Http.ChromeUserAgent();
            #endregion
            string checkIsHave = request.Get(domain + "CheckAccount?RequestKey=" + md5(md5(GetHDDSerialNumber()) + "handsome") + "&MachineSerial=" + md5(GetHDDSerialNumber()) + "&UserName="******"\"", "") == "Error")
            {
                MessageBox.Show("Truy cập không hợp lệ!");
                return;
            }

            if (checkIsHave.Replace("\"", "") == "false")
            {
                string check = request.Post(domain + "Register/?MachineSerial=" + md5(GetHDDSerialNumber()) + "&CustomerName=" + txtHoTen.Text + "&LinkFacebook=" + txbSignupLink.Text + "&UserName="******"&PassWord="******"&Email=" + txbSignupEmail.Text + "&Phone=" + txbSignupPhone.Text).ToString();
                if (check.Replace("\"", "") == "true")
                {
                    MessageBox.Show("Đăng kí tài khoản thành công!");
                    txbUserName.Text  = txbSignupUser.Text;
                    txbPass.Text      = txbSignupPass.Text;
                    pnlLogin.Visible  = true;
                    pnlSignup.Visible = false;
                }
                else
                {
                    MessageBox.Show("Đã có lỗi xảy ra, vui lòng thử lại sau");
                }
            }
            else
            {
                MessageBox.Show("Tên đăng nhập đã tồn tại");
                txbSignupUser.Focus();
            }
        }
コード例 #38
0
        public void InitializationRequest(string cookie = "", string userAgent = "", string proxy = "", int typeProxy = 0)
        {
            if (userAgent == "")
            {
                userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36";
            }
            this.request = new xNet.HttpRequest()
            {
                KeepAlive         = true,
                AllowAutoRedirect = true,
                Cookies           = new CookieDictionary(false),
                UserAgent         = userAgent
            };
            request.SslProtocols = SslProtocols.Tls12;
            this.request.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            this.request.AddHeader("Accept-Language", "en-US,en;q=0.9");
            if (cookie != "")
            {
                this.AddCookie(cookie);
            }
            if (proxy != "")
            {
                switch (proxy.Split(new char[] { ':' }).Count <string>())
                {
                case 1:
                {
                    this.request.Proxy = Socks5ProxyClient.Parse(string.Concat("127.0.0.1:", proxy));
                    break;
                }

                case 2:
                {
                    if (typeProxy != 0)
                    {
                        this.request.Proxy = Socks5ProxyClient.Parse(proxy);
                    }
                    else
                    {
                        this.request.Proxy = HttpProxyClient.Parse(proxy);
                    }
                    break;
                }

                case 3:
                {
                    break;
                }

                case 4:
                {
                    this.request.Proxy = new HttpProxyClient(proxy.Split(new char[] { ':' })[0], Convert.ToInt32(proxy.Split(new char[] { ':' })[1]), proxy.Split(new char[] { ':' })[2], proxy.Split(new char[] { ':' })[3]);
                    break;
                }

                default:
                {
                    goto case 3;
                }
                }
            }
        }
コード例 #39
0
ファイル: Form1.cs プロジェクト: vadimvv/Parser
        Task<string> GetTextAsync()
        {
            string Source = "";
            string Stattia = "";
            string link = "";
            string result = "";
            return Task.Run(() =>
            {
                if (gonext)
                {
                    for (int i = 0; i < AllLinks.Count; i++)
                    {
                        try
                        {
                            link = "http://sfs.gov.ua" + AllLinks[i];
                            using (var Request = new HttpRequest())
                            {
                                try
                                {
                                    Source = Request.Get(link).ToString();
                                }
                                catch
                                {
                                    error = "Немає доступу до " + link;
                                    gonext = false;
                                    return error;
                                }
                                n++;
                                Stattia += "" + n +
                                           Source.Substring("itemtype=\"http://schema.org/Article\">",
                                               "<div class=\"bottom bottom_mod\">") + Environment.NewLine +
                                           Environment.NewLine;
                            }
                        }
                        catch
                        {
                            error = "Помилка! Не може знайти текста на сторінці" + link;
                        }
                    }
                }
                return Stattia;
            });

        }
コード例 #40
0
        // регистрация звонка
        public Ansver RegisterCall(string B24_URL, string PHONE_NUMBER, string CALL_START_DATE, string TYPE, string CRM_CREATE, string PROCES_STATUS, string actok, string USER_PHONE_INNER = "0", string LINE_NUMBER = "")
        {
            string operb24 = GetIdUserB24(B24_URL, actok, USER_PHONE_INNER);

            Ansver ans = new Ansver();
            //var data5 = new
            //{
            //    filter = new
            //    {
            //        PHONE = PHONE_NUMBER

            //    },
            //    select = new[] { "ID", "NAME", "LAST_NAME", "SECOND_NAME", "PHONE" } //
            //};
            //string contentText = JsonConvert.SerializeObject(data5).ToString();

            //string content5;
            //using (xNet.HttpRequest request5 = new xNet.HttpRequest())
            //{
            //    content5 = request5.Post("https://" + B24_URL + "/rest/crm.contact.list?auth=" + actok, contentText, "application/json").ToString();
            //}
            //var converter2 = new ExpandoObjectConverter();
            //dynamic contakt = JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(content5, converter2);

            //string contid;
            //try
            //{
            //    contid = contakt.result[0].ID; //ид контакта. если контакт есть то берем первый попавшийся

            //}
            //catch { contid = "0"; }

            //if (contid == "0") // ели контакта нет то добовляем
            //{
            //    var data3 = new
            //    {

            //        fields = new
            //        {
            //            NAME = PHONE_NUMBER,
            //            LAST_NAME = "Контакт",
            //            OPENED = "Y",
            //            ASSIGNED_BY_ID = operb24,
            //            TYPE_ID = "CLIENT",
            //            PHONE = new[]
            //            {
            //                new { VALUE = PHONE_NUMBER , VALUE_TYPE = "WORK" }
            //            }
            //        },
            //        @params = new
            //        {
            //            REGISTER_SONET_EVENT = "Y"
            //        }

            //    };
            //    string contentText3 = JsonConvert.SerializeObject(data3).ToString();
            //    string content3;
            //    using (xNet.HttpRequest request3 = new xNet.HttpRequest())
            //    {
            //        content3 = request3.Post("https://" + B24_URL + "/rest/crm.contact.add?auth=" + actok, contentText3, "application/json").ToString();
            //    }
            //}
            //System.Threading.Thread.Sleep(100);

            // if (dt != null) { date = dt; }

            var data = new
            {
                CALL_START_DATE = CALL_START_DATE,
                USER_ID         = operb24,
                PHONE_NUMBER    = PHONE_NUMBER,
                TYPE            = TYPE,
                SHOW            = 0,
                CRM_CREATE      = CRM_CREATE,
                LINE_NUMBER     = LINE_NUMBER,
            };
            string contentText2 = JsonConvert.SerializeObject(data).ToString();
            string content;

            using (xNet.HttpRequest request = new xNet.HttpRequest())
            {
                content = request.Post("https://" + B24_URL + "/rest/telephony.externalcall.register.json?auth=" + actok, contentText2, "application/json").ToString();
            }
            var converter = new ExpandoObjectConverter();

            System.Threading.Thread.Sleep(100);
            dynamic       obj      = JsonConvert.DeserializeObject <ExpandoObject>(content, converter);
            List <object> resentry = obj.result.CRM_CREATED_ENTITIES;

            if (resentry.Count == 0)
            {
                ans.CREATED_ENTITY = "0";
            }
            else
            {
                ans.CREATED_ENTITY = "1";
            }
            if (string.IsNullOrEmpty(obj.result.CALL_ID))
            {
                return(null);
            }
            ans.CALL_GUID = obj.result.CALL_ID.ToString();

            string idotv = "";

            if (obj.result.CRM_ENTITY_TYPE.ToString() == "CONTACT")
            {
                ans.SIP_INFO = obj.result.CRM_ENTITY_TYPE;
                string idcont   = obj.result.CRM_ENTITY_ID.ToString();
                string content2 = "";
                using (xNet.HttpRequest request = new xNet.HttpRequest())
                {
                    content2 = request.Get("https://" + B24_URL + "/rest/crm.contact.get.json?id=" + idcont + "&auth=" + actok).ToString();
                }
                dynamic obj2 = JsonConvert.DeserializeObject <ExpandoObject>(content2, converter);
                idotv = obj2.result.ASSIGNED_BY_ID;
            }
            else if (obj.result.CRM_ENTITY_TYPE.ToString() == "LEAD")
            {
                ans.SIP_INFO = obj.result.CRM_ENTITY_TYPE;
                string idlead   = obj.result.CRM_ENTITY_ID.ToString();
                string content2 = "";
                using (xNet.HttpRequest request = new xNet.HttpRequest())
                {
                    content2 = request.Get("https://" + B24_URL + "/rest/crm.lead.get.json?id=" + idlead + "&auth=" + actok).ToString();
                }
                dynamic obj2 = JsonConvert.DeserializeObject <ExpandoObject>(content2, converter);
                idotv = obj2.result.ASSIGNED_BY_ID;
            }
            else if (obj.result.CRM_ENTITY_TYPE.ToString() == "COMPANY")
            {
                ans.SIP_INFO = obj.result.CRM_ENTITY_TYPE;
                string idcoo    = obj.result.CRM_ENTITY_ID.ToString();
                string content2 = "";
                using (xNet.HttpRequest request = new xNet.HttpRequest())
                {
                    content2 = request.Get("https://" + B24_URL + "/rest/crm.company.get.json?id=" + idcoo + "&auth=" + actok).ToString();
                }
                dynamic obj2 = JsonConvert.DeserializeObject <ExpandoObject>(content2, converter);
                idotv = obj2.result.ASSIGNED_BY_ID;
            }
            try
            {
                System.Threading.Thread.Sleep(100);
                string content6 = "";
                using (xNet.HttpRequest request = new xNet.HttpRequest())
                {
                    content6 = request.Get("https://" + B24_URL + "/rest/user.get.json?id=" + idotv + "&auth=" + actok).ToString();
                }
                dynamic obj6 = JsonConvert.DeserializeObject <ExpandoObject>(content6, converter);
                ans.CRM_OWNER_NUMBER = obj6.result[0].UF_PHONE_INNER.ToString();
            }
            catch
            {
                ans.SIP_INFO         = "BITRIX_USER_NUMBER";
                ans.CRM_OWNER_NUMBER = "";
            }
            return(ans);
        }
コード例 #41
0
ファイル: Form1.cs プロジェクト: vadimvv/Parser
 List<string> GetAllLinksFromCurrentPage(string link)
 {
     if (gonext)
     {
         string pattern = @".baneryi.podatkovi-konsultatsii.konsultatsii-dlya-yuridichnih-osib.\d*.html";
         Regex newReg = new Regex(pattern);
         try
         {
             using (var Request = new HttpRequest())
             {
                 try
                 {
                     sitecode = Request.Get(link).ToString();
                 }
                 catch
                 {
                     error = "Немає доступу до " + link;
                     gonext = false;
                 }
                 MatchCollection matches = newReg.Matches(sitecode);
                 foreach (Match mat in matches)
                 {
                     AllLinks.Add(mat.Value);
                 }
             }
         }
         catch
         {
             error += "\nПомилка! Не може знайти ссилкі на даній сторінці";
             gonext = false;
         }
     }
     return AllLinks;
 }
コード例 #42
0
        /// <summary>
        /// Регистрация 
        /// </summary>
        public void Registration()
        {
            CallUnitMsg("Registration start");
            var client = new HttpRequest();

            begin:;
            try
            {
                client.ClearAllHeaders();
                client.UserAgent = UnitUserAgent;
                client.CharacterSet = Encoding.UTF8;
                client.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                client.AddHeader("Accept-Language", "ru - RU,ru; q = 0.8,en - US; q = 0.5,en; q = 0.3");
                client.Cookies = UnitCookies;


                if (UnitProxy.ProxyUse && !UnitProxy.ProxyIsEmtpy)
                {
                    if(UnitProxyLine == null)
                    {
                        UnitProxyLine = UnitProxy.GetProxyLine();
                    }

                    UnitProxy.SetProxy(ref client, UnitProxyLine);
                }

                byte[] stream = client.Get("https://fotostrana.ru/signup/login/").ToBytes();

                GetToken(stream);

                client.CharacterSet = Encoding.Default;
                client.AddHeader("Accept-Language", "ru - RU,ru; q = 0.8,en - US; q = 0.5,en; q = 0.3");
                client.AddHeader("Accept", @"application/json, text/javascript, */*; q = 0.01");
                client.AllowAutoRedirect = true;
                client.AddHeader("X-Simple-Token:", UnitToken);
                client.AddHeader("X-Requested-With", "XMLHttpRequest");
                client.Referer = "https://fotostrana.ru/signup/login/";
                client.UserAgent = UnitUserAgent;
                client.Cookies = UnitCookies;

                GetPassword();

                string data = $"csrftkn={UnitToken}&user_email={UnitEmail}& user_password={UnitPassword}&submitted=1& issetFields%5B%5D=csrftkn&issetFields%5B%5D=user_email&issetFields%5B%5D=user_password&issetFields%5B%5D=submitted&_fs2ajax=1";

                CallUnitMsg("Попытка авторизации");
                string s = client.Post("https://fotostrana.ru/signup/signup/auth/", data, "application/x-www-form-urlencoded;charset=UTF-8").ToString();
                AnalizResult(s);
            }
            catch (Exception ex)
            {
               
                if (ex.Message == "Не удалось соединиться с HTTP-сервером 'fotostrana.ru'.")
                {
                    try
                    {
                        UnitProxy.WriteProxyToFile(UnitProxyLine, 1);
                    }
                    catch (Exception x)
                    {
                        MessageBox.Show(x.Message);
                    }
                    UnitProxyLine = null;
                    goto begin;
                }
                CallUnitMsg(ex.Message);
            }

        }