Beispiel #1
0
        /// <summary>
        /// Общий метод для разных потоков на Get запрос с функцией дозированных запросов раз в  <paramref name="delay"/> мс и временем ожидания <paramref name="waitingTime"/>, в случае неудачного запроса
        /// </summary>
        /// <param name="request">Объект HttpRequest вызывающего потока</param>
        /// <param name="url">URL строка для  Get  запроса</param>
        /// <param name="delay">Время задержки между запросами в мс</param>
        /// <param name="waitingTime">Время ожидания не ошибочного ответа от сервера</param>
        /// <param name="setter">делегат передающий  сигналу задержки состояние true, означающий недавнее выполнение http get запроса</param>
        /// <param name="getter">делегат возвращающий текущее состояние сигнала разрешения задержки</param>
        /// <returns></returns>
        internal static string GetDosingRequests(HttpRequest request, string url, RequestParams rParams, int delay, int waitingTime, Action<bool> setter, FirstDelegate getter)
        {
            string resultPage = "";

            Stopwatch waitingWatch = new Stopwatch();
            waitingWatch.Start();
            while (String.IsNullOrEmpty(resultPage))
            {

                if (getter())
                {
                    //этой конструкцией выстраиваю потоки в очередь
                    lock (LockGetRequestObj)
                    {
                        Thread.Sleep(delay);
                    }
                }
                try
                {
                    setter(true);
                    resultPage = request.Get(url, rParams).ToString();
                    Console.WriteLine("request");
                }
                catch (Exception ex)
                {
                    if (waitingWatch.ElapsedMilliseconds > waitingTime && waitingTime != -1)
                        throw new Exception("Время ожидания вышло. Причина: \r\n" + ex.Message);
                    Thread.Sleep(5000);
                }
            }
            waitingWatch.Reset();
            return resultPage;
        }
Beispiel #2
0
        /// <summary>
        /// Считает время ожидания ответа на запрос к http серверу
        /// </summary>
        /// <param name="address">Url адрес</param>
        /// <param name="maxRequestTime">Максимальное время ожидания ответа. -1 для бесконечного времени ожидания.</param>
        /// <returns>Время запроса в мс</returns>

        internal static int GetRequestTime(string address, RequestParams requestParams, int maxRequestTime, out Exception outEx)
        {
            int result = -1;
            Exception innerEx = null;
            using (var request = new HttpRequest())
            {
                request.UserAgent = HttpHelper.ChromeUserAgent();
                EventWaitHandle wh = new AutoResetEvent(false);
                var requestThread = new Thread(() =>
                {
                    var watch = new Stopwatch();
                    watch.Start();
                    try
                    {
                        string resultPage = request.Get(address, requestParams).ToString();
                    }
                    catch (Exception ex) { innerEx = ex; }
                    result = Convert.ToInt32(watch.ElapsedMilliseconds);
                    watch.Reset();
                    wh.Set();
                });
                requestThread.Start();
                var stoptimer = new System.Threading.Timer((Object state) =>
                {
                    requestThread.Abort();
                    wh.Set();
                }, null, maxRequestTime, Timeout.Infinite);
                wh.WaitOne();

                stoptimer.Dispose();
            }
            outEx = innerEx;
            return result;
        }
Beispiel #3
0
 public string last_posts(int limit, int html)
 {
    string response = "";
    RequestParams req = new RequestParams();
    req["limit"] = limit.ToString();
    req["html"] = html.ToString();
    response = Post(req,"http://annimon.com/json/forum/last_posts");           
    return response; 
 }
 /// <summary>
 /// </summary>
 /// <param name="id"></param>
 /// <param name="appAuxLogFolder">It's where this class puts "*.succ.timestamp" files.
 /// That's needed for logging purposes. It could be null  (no flag files then), or e.g. a value of 
 /// Path.Combine( HttpRuntime.AppDomainAppPath , "logs" ).
 /// </param>
 /// <param name="consequentErrorsCounter">
 /// A counter to check if request error should be reported as error or as warning. If the number of 
 /// consequent request errors is not reached parameter's Threshold value, it logged as Warning. Otherwise
 /// it's logged as Error. Can be null, in this case always logged as Error. Note that: 
 /// - a successful request sets this counter to zero.
 /// - ResponseHasNoData or BadTrackerId are ignored and not counted as neither fail nor success.
 /// </param>
 public SpotLocationRequest(
     RequestParams requestParams,
     string appAuxLogFolder,
     ConsequentErrorsCounter consequentErrorsCounter
     )
     : base(requestParams)
 {
     this.appAuxLogFolder = appAuxLogFolder;
       this.consequentErrorsCounter = consequentErrorsCounter;
 }
Beispiel #5
0
 public WebRequest(Socket socket)
 {
     _socket = socket;
     _stream = new StreamReader(new NetworkStream(_socket));
     _requestParams = new RequestParams();
     _mimeTypeList = new List<string>()
     {
         ".html", ".htm", ".txt", ".mpeg", ".mpg", ".mpe", ".avi", ".png", "jpeg", ".jpg", ".jpe", ".gif",".bmp", ".wav",
         ".mp3", ".mp2", "aif", ".aiff", ".tiff", ".tif"
     };
 }
Beispiel #6
0
 public string unread(string token, int start, int limit, int html)
 {
     string response = "";
     RequestParams req = new RequestParams();
     req["token"] = token;
     req["start"] = start.ToString();
     req["limit"] = limit.ToString();
     req["html"] = html.ToString();
     response = Post(req,"http://annimon.com/json/forum/unread");
     return response;              
 }  
Beispiel #7
0
 public string get_posts(int topic, int start, int limit, int html)
 {
     string response = "";
     RequestParams req = new RequestParams();
     req["topic"] = topic.ToString();
     req["start"] = start.ToString();
     req["limit"] = limit.ToString();
     req["html"] = html.ToString();
     response = Post(req,"http://annimon.com/json/forum/get_posts");
     return response;              
 }
Beispiel #8
0
 public string get_topics(int section,int start, int limit)
 {
     string response = "";
     RequestParams req = new RequestParams();
     req["section"] = section.ToString();
     req["start"] = start.ToString();
     req["limit"] = limit.ToString();
     response = Post(req,"http://annimon.com/json/forum/get_topics");
     return response;
     
 }
Beispiel #9
0
        private void searchButton_Click(object sender, EventArgs e)
        {
            songBox.Items.Clear();
            if (searchInput.TextLength != 0)
            {
                using (var rq = new HttpRequest())
                {
                    rq.UserAgent = HttpHelper.FirefoxUserAgent();

                    if (ultimate_guitarCheck.Checked)
                    {
                        try
                        {
                            //www.ultimate-guitar.com/search.php?search_type=title&value=

                            var urlParams = new RequestParams();

                            urlParams["search_type"] = "title";
                            urlParams["value"] = searchInput.Text;

                            string content = rq.Get("http://www.ultimate-guitar.com/search.php", urlParams).ToString();

                            string[] songNames;
                            string[] urls;

                            songNames = content.Substrings("class=\"song\">", "</a>", 0);
                            urls = content.Substrings("<a href=\"" + ultimateAdress, "\" class=\"song\">", 0);

                            for (int i = 0; i < songNames.Length; i++)
                            {
                                    songNames[i] = songNames[i].Replace("<b>", "");
                                    songNames[i] = songNames[i].Replace("</b>", "");
                                    songNames[i] = songNames[i].Insert(0, i + ". ");

                                    urls[i] = urls[i].Insert(0, ultimateAdress);

                                    songs.Add(songNames[i], urls[i]);

                                    songBox.Items.Add(songNames[i]);
                            }

                        }
                        catch
                        {
                            MessageBox.Show("Что-то пошло не так");
                        }
                    }
                }
            }

            showTabButton.Enabled = true;
        }
Beispiel #10
0
 string Post(RequestParams req, string url)
 {
  string content = "";
     using (var request = new HttpRequest())
     {
         try{
                 content = request.Post(url, req).ToString();
             }
         catch(HttpException e)
             {
                 MessageBox.Show(e.Message);
             }         
       }
     return content;                
 }
Beispiel #11
0
 public static void GetFile(Uri uri, RequestParams request, string file)
 {
     DoRequest((client) => { client.DownloadFile(uri, file); }, request);
 }
Beispiel #12
0
 public static Task <Image> GetImageAsync(string uri, RequestParams request)
 {
     return(GetImageAsync(new Uri(uri), request));
 }
Beispiel #13
0
        /// <summary>
        /// Проверка обновлений программы
        /// </summary>
        /// <param name="progVer">Текущая версия основного ПО</param>
        /// <param name="sldVer">Текущая версия библиотек</param>
        private void CheckUpdateProgram(string progVer, string sldVer)
        {
            int ver0, ver1, rev0, rev1;

            string[] vers = progVer.Split('.');

            RequestSettings reqSettings = new RequestSettings();
            reqSettings.Site = "http://it-planets.ru/mbstudio/download_info.php";
            RequestParams reqParams = new RequestParams();
            reqParams.Add("type_info", "ver_po,ver_sld");
            reqSettings.PostData = reqParams.ToString();
            SiteConnector connector = new SiteConnector(reqSettings);

            string newversion_info = string.Empty;
            try
            {
                 connector.DownLoad("GET", Encoding.UTF8);

                if (vers.Count() == 4)
                {
                    if (int.TryParse(vers[0], out ver0))
                    {

                    }
                }
            }
            catch(System.Net.WebException ex)
            {

            }
            catch(Exception ex)
            {

            }
        }
Beispiel #14
0
        /// <summary>
        /// Добавляет временный параметр запроса.
        /// </summary>
        /// <param name="name">Имя параметра.</param>
        /// <param name="value">Значение параметра, или значение <see langword="null"/>.</param>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="name"/> равно <see langword="null"/>.</exception>
        /// <exception cref="System.ArgumentException">Значение параметра <paramref name="name"/> является пустой строкой.</exception>
        /// <remarks>Данный параметр будет стёрт после первого запроса.</remarks>
        public HttpRequest AddParam(string name, object value = null)
        {
            #region Проверка параметров

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (name.Length == 0)
            {
                throw ExceptionHelper.EmptyString("name");
            }

            #endregion

            if (_addedParams == null)
            {
                _addedParams = new RequestParams();
            }

            _addedParams[name] = value;

            return this;
        }
Beispiel #15
0
        /// <summary>
        /// Post image data on server
        /// </summary>
        /// <param name="image">Image data</param>
        /// <param name="type">Image extension type</param>
        /// <param name="param">Recognize params</param>
        public void PostImage(byte[] image, ImgType type, RecognizeParams param = null)
        {
            if (image == null || image.Length == 0)
                throw new ArgumentException("Bad image data");

            List<KeyValuePair<string, string>> postParams = new List<KeyValuePair<string, string>>();
            postParams.Add(new KeyValuePair<string, string>("method", "post"));
            postParams.Add(new KeyValuePair<string, string>("key", ACCOUNT_ID));

            if (param!=null)
            {
                foreach (var keyValue in param.Params)
                {
                    postParams.Add(keyValue);
                }
            }

            byte[] fbData = BuldFormbasedData(postParams, StreamEncoding.GetString(image), type);

            string contentType = "multipart/form-data; boundary=" + _boundary;
            RequestParams reqParams = new RequestParams(null, null, contentType, null, true, "POST", StreamEncoding, false);
            DownloaderObj obj = new DownloaderObj(_postUri, EndPostImage, true, null, CookieOptions.Empty, 4, null, null, false, 1000, null, reqParams);
            obj.PostData = fbData;
            Downloader.Queue(obj);
        }
Beispiel #16
0
        public static JSONDataArray GetJsonArray(Uri uri, RequestParams request)
        {
            string response = GetString(uri, request);

            return(response.IsNotNullOrWhiteSpace() ? response.JSONToDataObject() as JSONDataArray : null);
        }
Beispiel #17
0
        private void conv_btn(object sender, RoutedEventArgs e)
        {
            int     amount           = 0;
            Boolean numerical_amount = true;

            try
            {
                amount = int.Parse(amount_txt.Text);
            }
            catch
            {
                numerical_amount = false;
            }

            HttpRequest  req = new HttpRequest();
            HttpResponse resp;

            req.Cookies = new CookieDictionary();

            var urlParams = new RequestParams();

            urlParams["amount"] = amount;

            bool flag = false;

            if (comboFrom.SelectedItem == "ILS-Israeli Shekel")
            {
                urlParams["from"] = "ILS";

                if (comboTo.SelectedItem == "ILS-Israeli Shekel")
                {
                    flag = true;
                }
                if (comboTo.SelectedItem == "EUR-Euro")
                {
                    urlParams["to"] = "EUR";
                }
                if (comboTo.SelectedItem == "USD-US Dollar")
                {
                    urlParams["to"] = "USD";
                }
                if (comboTo.SelectedItem == "GBP-British Pound")
                {
                    urlParams["to"] = "GBP";
                }
                if (comboTo.SelectedItem == "JPY-Japanise Yen")
                {
                    urlParams["to"] = "JPY";
                }
            }

            if (comboFrom.SelectedItem == "EUR-Euro")
            {
                urlParams["from"] = "EUR";

                if (comboTo.SelectedItem == "EUR-Euro")
                {
                    flag = true;
                }
                if (comboTo.SelectedItem == "ILS-Israeli Shekel")
                {
                    urlParams["to"] = "ILS";
                }
                if (comboTo.SelectedItem == "USD-US Dollar")
                {
                    urlParams["to"] = "USD";
                }
                if (comboTo.SelectedItem == "GBP-British Pound")
                {
                    urlParams["to"] = "GBP";
                }
                if (comboTo.SelectedItem == "JPY-Japanise Yen")
                {
                    urlParams["to"] = "JPY";
                }
            }

            if (comboFrom.SelectedItem == "USD-US Dollar")
            {
                urlParams["from"] = "USD";

                if (comboTo.SelectedItem == "USD-US Dollar")
                {
                    flag = true;
                }
                if (comboTo.SelectedItem == "ILS-Israeli Shekel")
                {
                    urlParams["to"] = "ILS";
                }
                if (comboTo.SelectedItem == "EUR-Euro")
                {
                    urlParams["to"] = "EUR";
                }
                if (comboTo.SelectedItem == "GBP-British Pound")
                {
                    urlParams["to"] = "GBP";
                }
                if (comboTo.SelectedItem == "JPY-Japanise Yen")
                {
                    urlParams["to"] = "JPY";
                }
            }

            if (comboFrom.SelectedItem == "GBP-British Pound")
            {
                urlParams["from"] = "GBP";

                if (comboTo.SelectedItem == "GBP-British Pound")
                {
                    flag = true;
                }
                if (comboTo.SelectedItem == "ILS-Israeli Shekel")
                {
                    urlParams["to"] = "ILS";
                }
                if (comboTo.SelectedItem == "EUR-Euro")
                {
                    urlParams["to"] = "EUR";
                }
                if (comboTo.SelectedItem == "US-US Dollar")
                {
                    urlParams["to"] = "USD";
                }
                if (comboTo.SelectedItem == "JPY-Japanise Yen")
                {
                    urlParams["to"] = "JPY";
                }
            }

            if (comboFrom.SelectedItem == "JPY-Japanise Yen")
            {
                urlParams["from"] = "JPY";

                if (comboTo.SelectedItem == "JPY-Japanise Yen")
                {
                    flag = true;
                }
                if (comboTo.SelectedItem == "ILS-Israeli Shekel")
                {
                    urlParams["to"] = "ILS";
                }
                if (comboTo.SelectedItem == "EUR-Euro")
                {
                    urlParams["to"] = "EUR";
                }
                if (comboTo.SelectedItem == "US-US Dollar")
                {
                    urlParams["to"] = "USD";
                }
                if (comboTo.SelectedItem == "GBP-British Pound")
                {
                    urlParams["to"] = "GBP";
                }
            }

            if (!numerical_amount)
            {
                display_txt.Text = "Please insert a proper amount!";
            }

            else if (!flag)
            {
                urlParams["exchange"] = "-";
                resp = req.Get("http://localhost/ProjectG", urlParams);
                string json = resp.ToString();

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

                display_txt.Text = "Converted amount: " + result;
            }

            else
            {
                display_txt.Text = "Converted amount: " + amount;
            }
        }
Beispiel #18
0
 public string mark_readed(string token, int number)
 {
     string response = "";
     RequestParams req = new RequestParams();
     req["token"] = token;
     req["start"] = number.ToString();
     response = Post(req,"http://annimon.com/json/forum/mark_readed");
     return response;              
 }  
Beispiel #19
0
 public static XDocument GetXML(RequestParams prms)
 {
     string response = GetString(prms);
     return response.IsNotNullOrWhiteSpace() ? XDocument.Parse(response) : null;
 }
Beispiel #20
0
 public static Task GetFileAsync(Uri uri, RequestParams request, string file)
 {
     return(DoRequest((client) => client.DownloadFileTaskAsync(uri, file), request));
 }
Beispiel #21
0
 public static Task <JSONDynamicObject> GetJsonAsDynamicAsync(string uri, RequestParams request)
 {
     return(GetJsonAsDynamicAsync(new Uri(uri), request));
 }
Beispiel #22
0
        private void ExcecuteMethod <T>(CallDelegate <RequestParams, OutputModel <T>, bool> method, RequestParams @params, out OutputModel <T> outputModel)
        {
            outputModel = null;

            for (int i = 0; i < 2; i++)
            {
                if (method(@params, out outputModel))
                {
                    break;
                }
                else
                {
                    if (outputModel.Response.Status == Status.InvalidSession)
                    {
                        // Login and retrieve session token
                        if (!Login(out var response))
                        {
                            throw new Exception($"Invalid session and couldn't refresh. {response.Message}");
                        }
                    }
                    else
                    {
                        throw new Exception("Unknown error.");
                    }
                }
            }
        }
Beispiel #23
0
 public static JSONDataMap GetValueMap(string uri, RequestParams request)
 {
     return(GetValueMap(new Uri(uri), request));
 }
        public override void FromLC(ref string script, ref int lineNumber)
        {
            /*
             *   TYPE:STANDARD
             *   "name=hello&value=hi"
             *   "application/x-www-form-urlencoded"
             *
             *   TYPE:RAW
             *   BASE64_DATA
             *   "application/octet-stream"
             *
             *   TYPE:BASICAUTH
             *   "myUser"
             *   "myPass"
             *
             *   TYPE:MULTIPART
             *   "myBoundary"
             *   CONTENT:STRING "name" "content" "content-type"
             *   CONTENT:RAW "name" BASE64_DATA "content-type"
             *   CONTENT:FILE "name" "fileName" "content-type"
             *
             */

            // First parse the options that are common to every BlockInstance
            base.FromLC(ref script, ref lineNumber);

            using var reader = new StringReader(script);
            string line, lineCopy;

            while ((line = reader.ReadLine()) != null)
            {
                line     = line.Trim();
                lineCopy = line;
                lineNumber++;

                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                if (line.StartsWith("TYPE:"))
                {
                    try
                    {
                        var reqParams = Regex.Match(line, "TYPE:([A-Z]+)").Groups[1].Value;

                        switch (reqParams)
                        {
                        case "STANDARD":
                            var standardReqParams = new StandardRequestParams();

                            // Read one line to parse the content
                            line     = reader.ReadLine().Trim();
                            lineCopy = line;
                            lineNumber++;
                            LoliCodeParser.ParseSettingValue(ref line, standardReqParams.Content, new StringParameter());

                            // Read another line to parse the content-type
                            line     = reader.ReadLine().Trim();
                            lineCopy = line;
                            lineNumber++;
                            LoliCodeParser.ParseSettingValue(ref line, standardReqParams.ContentType, new StringParameter());

                            RequestParams = standardReqParams;
                            break;

                        case "RAW":
                            var rawReqParams = new RawRequestParams();

                            // Read one line to parse the content
                            line     = reader.ReadLine().Trim();
                            lineCopy = line;
                            lineNumber++;
                            LoliCodeParser.ParseSettingValue(ref line, rawReqParams.Content, new ByteArrayParameter());


                            // Read another line to parse the content-type
                            line     = reader.ReadLine().Trim();
                            lineCopy = line;
                            lineNumber++;
                            LoliCodeParser.ParseSettingValue(ref line, rawReqParams.ContentType, new StringParameter());

                            RequestParams = rawReqParams;
                            break;

                        case "BASICAUTH":
                            var basicAuthReqParams = new BasicAuthRequestParams();

                            // Read one line to parse the username
                            line     = reader.ReadLine().Trim();
                            lineCopy = line;
                            lineNumber++;
                            LoliCodeParser.ParseSettingValue(ref line, basicAuthReqParams.Username, new StringParameter());

                            // Read another line to parse the password
                            line     = reader.ReadLine().Trim();
                            lineCopy = line;
                            lineNumber++;
                            LoliCodeParser.ParseSettingValue(ref line, basicAuthReqParams.Password, new StringParameter());

                            RequestParams = basicAuthReqParams;
                            break;

                        case "MULTIPART":
                            var multipartReqParams = new MultipartRequestParams();

                            // Read one line to parse the boundary
                            line     = reader.ReadLine().Trim();
                            lineCopy = line;
                            lineNumber++;
                            LoliCodeParser.ParseSettingValue(ref line, multipartReqParams.Boundary, new StringParameter());

                            RequestParams = multipartReqParams;
                            break;

                        default:
                            throw new LoliCodeParsingException(lineNumber, $"Invalid type: {reqParams}");
                        }
                    }
                    catch (NullReferenceException)
                    {
                        throw new LoliCodeParsingException(lineNumber, "Missing options for the selected content");
                    }
                    catch
                    {
                        throw new LoliCodeParsingException(lineNumber, $"Could not parse the setting: {lineCopy.TruncatePretty(50)}");
                    }
                }

                else if (line.StartsWith("CONTENT:"))
                {
                    try
                    {
                        var multipart = (MultipartRequestParams)RequestParams;
                        var token     = LineParser.ParseToken(ref line);
                        var tokenType = Regex.Match(token, "CONTENT:([A-Z]+)").Groups[1].Value;

                        switch (tokenType)
                        {
                        case "STRING":
                            var stringContent = new StringHttpContentSettingsGroup();
                            LoliCodeParser.ParseSettingValue(ref line, stringContent.Name, new StringParameter());
                            LoliCodeParser.ParseSettingValue(ref line, stringContent.Data, new StringParameter());
                            LoliCodeParser.ParseSettingValue(ref line, stringContent.ContentType, new StringParameter());
                            multipart.Contents.Add(stringContent);
                            break;

                        case "RAW":
                            var rawContent = new RawHttpContentSettingsGroup();
                            LoliCodeParser.ParseSettingValue(ref line, rawContent.Name, new StringParameter());
                            LoliCodeParser.ParseSettingValue(ref line, rawContent.Data, new ByteArrayParameter());
                            LoliCodeParser.ParseSettingValue(ref line, rawContent.ContentType, new StringParameter());
                            multipart.Contents.Add(rawContent);
                            break;

                        case "FILE":
                            var fileContent = new FileHttpContentSettingsGroup();
                            LoliCodeParser.ParseSettingValue(ref line, fileContent.Name, new StringParameter());
                            LoliCodeParser.ParseSettingValue(ref line, fileContent.FileName, new StringParameter());
                            LoliCodeParser.ParseSettingValue(ref line, fileContent.ContentType, new StringParameter());
                            multipart.Contents.Add(fileContent);
                            break;
                        }
                    }
                    catch
                    {
                        throw new LoliCodeParsingException(lineNumber, $"Could not parse the multipart content: {lineCopy.TruncatePretty(50)}");
                    }
                }

                else
                {
                    try
                    {
                        LoliCodeParser.ParseSetting(ref line, Settings, Descriptor);
                    }
                    catch
                    {
                        throw new LoliCodeParsingException(lineNumber, $"Could not parse the setting: {lineCopy.TruncatePretty(50)}");
                    }
                }
            }
        }
Beispiel #25
0
        public static string GetString(RequestParams request)
        {
            if (request.Method != HTTPRequestMethod.GET && request.Method != HTTPRequestMethod.POST && request.Method != HTTPRequestMethod.PUT &&
                request.Method != HTTPRequestMethod.DELETE)
            {
                throw new NFXException(StringConsts.ARGUMENT_ERROR + typeof(WebClient).Name + ".GetString(method=GET|POST)");
            }

            NameValueCollection queryParams;

            if (request.QueryParameters != null)
            {
                queryParams = new NameValueCollection(request.QueryParameters.Count);
                request.QueryParameters.ForEach(kvp => queryParams.Add(kvp.Key, kvp.Value));
            }
            else
            {
                queryParams = new NameValueCollection();
            }

            NameValueCollection bodyParams;

            if (request.BodyParameters != null)
            {
                bodyParams = new NameValueCollection(request.BodyParameters.Count);
                request.BodyParameters.ForEach(kvp => bodyParams.Add(kvp.Key, kvp.Value));
            }
            else
            {
                bodyParams = new NameValueCollection();
            }

            WebHeaderCollection headerParams = prepareRequestHeaders(request);

            string responseStr;

            using (var client = new WebClientTimeouted(request.Caller))
            {
                if (request.HasCredentials)
                {
                    client.Credentials = new NetworkCredential(request.UName, request.UPwd);
                }

                client.Headers     = headerParams;
                client.QueryString = queryParams;
                if (request.Method == HTTPRequestMethod.GET)
                {
                    responseStr = Uri.UnescapeDataString(client.DownloadString(request.Uri));
                }
                else if (request.Method == HTTPRequestMethod.PUT || request.Method == HTTPRequestMethod.DELETE)
                {
                    responseStr = Uri.UnescapeDataString(client.UploadString(request.Uri, request.Method.ToString(), request.Body ?? string.Empty));
                }
                else
                {
                    var body = request.Body ??
                               (request.BodyParameters != null ?
                                string.Join("&", request.BodyParameters.Select(p => p.Key + "=" + p.Value)) :
                                string.Empty);
                    responseStr = Uri.UnescapeDataString(client.UploadString(request.Uri, body));
                }
            }

            return(responseStr);
        }
Beispiel #26
0
        public static JSONDynamicObject GetJsonAsDynamic(RequestParams prms)
        {
            string responseStr = GetString(prms);

            return(responseStr.IsNotNullOrWhiteSpace() ? responseStr.JSONToDynamic() : null);
        }
Beispiel #27
0
        private void ClearRequestData()
        {
            _content = null;

            _temporaryUrlParams = null;
            _temporaryParams = null;
            _temporaryMultipartContent = null;
            _temporaryHeaders = null;
        }
Beispiel #28
0
        public static JSONDataMap GetJson(RequestParams prms)
        {
            string responseStr = GetString(prms);

            return(responseStr.IsNullOrWhiteSpace() ? null : responseStr.JSONToDataObject() as JSONDataMap);
        }
Beispiel #29
0
        /// <summary>
        /// Отправляет GET-запрос HTTP-серверу.
        /// </summary>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="urlParams">Параметры URL-адреса, или значение <see langword="null"/>.</param>
        /// <returns>Объект, предназначенный для загрузки ответа от HTTP-сервера.</returns>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public HttpResponse Get(Uri address, RequestParams urlParams = null)
        {
            if (urlParams != null)
            {
                _addedUrlParams = urlParams;
            }

            return Raw(HttpMethod.GET, address);
        }
        public override LocationRequest CreateRequest( RequestParams requestParams )
        {
            string testXml = TestSource.Singleton.GetFeed( requestParams.Id );

              return new TestLocationRequest( requestParams, testXml );
        }
Beispiel #31
0
 public static Image GetImage(string uri, RequestParams request)
 {
     return(GetImage(new Uri(uri), request));
 }
 public void SetRequestParam(string name, string value)
 {
     RequestParams.Add(name, value);
 }
Beispiel #33
0
 public static void GetFile(string uri, RequestParams request, string file)
 {
     GetFile(new Uri(uri), request, file);
 }
 public CertificationBLL(HttpContext httpContext, RequestParams requestParams)
     : base(httpContext, requestParams)
 {
 }
Beispiel #35
0
 public static Task GetFileAsync(string uri, RequestParams request, string file)
 {
     return(GetFileAsync(new Uri(uri), request, file));
 }
        /// <summary>
        /// Execute a Web Request
        /// </summary>
        /// <param name="requestParam">Request parameters</param>
        /// <returns>Class</returns>
        protected virtual T Execute <T>(RequestParams requestParam) where T : class
        {
            try
            {
                client.BaseUrl = new Uri(requestParam.baseUrl);
                var request = new RestRequest(requestParam.resource.CleanPathUrl(requestParam.baseUrl), requestParam.method);

                #region parameters

                if (requestParam.param != null)
                {
                    foreach (Parameter p in requestParam.param)
                    {
                        request.AddParameter(p);
                    }
                }

                #endregion adding parameters

                #region authentication methods

                request.AddParameter("MerchantId", Configuration.MerchantId, ParameterType.HttpHeader);
                request.AddParameter("MerchantKey", Configuration.MerchantKey, ParameterType.HttpHeader);
                request.AddParameter("RequestId", Guid.NewGuid(), ParameterType.HttpHeader);

                #endregion authentication

                #region header request params

                request.AddHeader("Accept", "application/json");
                request.AddHeader("Content-Type", "application/json");
                request.RequestFormat = DataFormat.Json;

                #endregion

                if (requestParam.body != null)
                {
                    request.AddParameter("application/json",
                                         JsonConvert.SerializeObject(requestParam.body, Formatting.Indented, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    }),
                                         ParameterType.RequestBody);
                }

                var response = client.Execute(request);

                if ((response.StatusCode != HttpStatusCode.Created) &&
                    (response.StatusCode != HttpStatusCode.OK))
                {
                    throw new ResponseException(new ErrorResponse(response.Content, response.StatusCode));
                }

                return(JsonConvert.DeserializeObject <T>(response.Content));
            }
            catch (ResponseException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #37
0
        public static JSONDynamicObject GetJsonAsDynamic(Uri uri, RequestParams request)
        {
            string response = GetString(uri, request);

            return(response.IsNotNullOrWhiteSpace() ? response.JSONToDynamic() : null);
        }
Beispiel #38
0
        private static void Main()
        {
            Console.Write(@"Enter your mail: ");
            //var login = Console.ReadLine();
            fasdf
            var request = new HttpRequest()
            {
                UserAgent = Http.ChromeUserAgent(),
                Cookies   = new CookieDictionary()
            };
            var response =
                request.Get(
                    "vk.com").ToString();
            var rp = new RequestParams
            {
                ["act"]         = "login",
                ["role"]        = "al_frame",
                ["ip_h"]        = response.Substring("ip_h\" value=\"", "\""),
                ["lg_h"]        = response.Substring("lg_h\" value=\"", "\""),
                ["_origin"]     = "https://vk.com",
                ["captcha_sid"] = "",
                ["captcha_key"] = "",
                ["email"]       = login,
                ["pass"]        = password,
                ["expire"]      = "0"
            };

            Console.Title = "Ksuwa Cheker";
            Console.SetOut(new PrefixedWriter());
            bool isLoggined;

            do
            {
                isLoggined = MainWork.TryToLogin(request, rp, login, password);
            }while (isLoggined == false);
            Console.WriteLine("end");
            var searchedPerson = new SearchedPerson();
            var wrongValue     = true;

            {
                while (wrongValue)
                {
                    try
                    {
                        Console.Write(@"Enter person id: vk.com/");
                        searchedPerson.PersonId = Console.ReadLine();
                        if (string.IsNullOrEmpty(searchedPerson.PersonId))
                        {
                            throw new ArgumentNullException(nameof(searchedPerson.PersonId));
                        }
                        searchedPerson.PersonName = MainWork.ChekingPersonName(request, searchedPerson.PersonId);
                        Console.WriteLine(@"Person found: {0}", searchedPerson.PersonName);
                        searchedPerson.Online = MainWork.ChekingOnline(request, searchedPerson.PersonId);
                        if (searchedPerson.Online)
                        {
                            Console.WriteLine("{0} is online!", searchedPerson.PersonName);
                            Console.Write("Do you wanna get notified when person come offline? Y/N: ");
                            if (Console.ReadLine() == "Y")
                            {
                                NotifyThenOffline(searchedPerson.PersonId, request, true, searchedPerson.PersonName);
                            }
                            else
                            {
                                Environment.Exit(0);
                            }
                        }
                        else
                        {
                            Console.WriteLine("{0} is offline!", searchedPerson.PersonName);
                            Console.WriteLine("{0}", MainWork.GettingLastOnline(request, searchedPerson.PersonId));
                            Console.Write("Do you wanna get notified when person come online? Y/N: ");
                            if (Console.ReadLine() == "Y")
                            {
                                NotifyThenOffline(searchedPerson.PersonId, request, false, searchedPerson.PersonName);
                            }
                            else
                            {
                                Environment.Exit(0);
                            }
                        }
                        wrongValue = false;
                    }
                    catch (Exception exception)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(exception.Message);
                        Console.ResetColor();
                    }
                }
            }


            Console.ReadKey();
        }
Beispiel #39
0
 public static JSONDataArray GetJsonArray(string uri, RequestParams request)
 {
     return(GetJsonArray(new Uri(uri), request));
 }
Beispiel #40
0
      public static string GetString(Uri uri, 
        IWebClientCaller caller,
        HTTPRequestMethod method = HTTPRequestMethod.GET,
        IDictionary<string, string> queryParameters = null,
        IDictionary<string, string> bodyParameters = null,
        string body = null,
        IDictionary<string, string> headers = null)
      {
        RequestParams request = new RequestParams()
        {
          Uri = uri,
          Caller = caller,
          Method = method,
          QueryParameters = queryParameters,
          BodyParameters = bodyParameters,
          Body = body,
          Headers = headers
        };

        return GetString(request);
      }
Beispiel #41
0
 public static Task <JSONDataArray> GetJsonArrayAsync(string uri, RequestParams request)
 {
     return(GetJsonArrayAsync(new Uri(uri), request));
 }
Beispiel #42
0
 public static JSONDynamicObject GetJsonAsDynamic(RequestParams prms)
 {
   string responseStr = GetString(prms);
   return responseStr.IsNotNullOrWhiteSpace() ? responseStr.JSONToDynamic() : null;
 }
Beispiel #43
0
    /// <summary>
    /// Main API request method. Will return a Http Statuc code and the body response in string format for parsing // casting. 
    /// </summary>
    /// <param name="url"></param>
    /// <param name="requestObject"></param>
    /// <param name="method"></param>
    /// <returns></returns>
    public Response ApiRequest(string url, RequestParams requestObject = null, string method = "GET")
    {
        // Return Object
        Response returnValue = new Response();
        try
        {
            // Create a request using a URL that can receive a post.
            WebRequest request = WebRequest.Create(url);
            // Set the Method property of the request to POST.
            request.Method = method.ToUpper();

            // Variable building
            var timeNonce = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            var message = timeNonce + ApiId + ApiKey;
            var signature = GetSignature(message);
            // Set headers for request
            request.Headers = new WebHeaderCollection();
            request.Headers.Add("Access-Key", ApiKey);
            request.Headers.Add("Access-Nonce", timeNonce.ToString());
            request.Headers.Add("Access-Signature", signature);
            // Create POST data and convert it to a byte array.
            string postData = parseRequestObject(requestObject);
            byte[] byteArray = encoding.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Set Reponse status code
            returnValue.Status = ((HttpWebResponse)response).StatusCode;
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Set the return Content
            returnValue.ResponseBody += responseFromServer;
            // Clean up the streams.
            reader.Close();
            response.Close();

            // Return to sender
            return returnValue;
        }
        catch (WebException ex)
        {
            // If something went wrong we will suppress the Exception but return a header response to the caller.
            returnValue.Status = ((HttpWebResponse)ex.Response).StatusCode;
            returnValue.ResponseBody = String.Format("{0} : {1}", ex.Response.Headers["status"], ex.Message);
        }
        // Return
        return returnValue;
    }
Beispiel #44
0
        private static WebHeaderCollection prepareRequestHeaders(RequestParams request)
        {
          var result = new WebHeaderCollection();       
          if (request.Headers != null)
            request.Headers.ForEach(kvp => result.Add(kvp.Key, kvp.Value));
          
          if (request.ContentType.IsNotNullOrWhiteSpace())
              result.Add(HttpRequestHeader.ContentType, request.ContentType);
          if (request.AcceptType.IsNotNullOrWhiteSpace())
              result.Add(HttpRequestHeader.Accept, request.AcceptType);

          return result;
        }
Beispiel #45
0
 public static string GetString(string uri, RequestParams request)
 {
     return(GetString(new Uri(uri), request));
 }
Beispiel #46
0
 public string auth(string login,string password) 
 {
     string response = "";
     string md5_password = "";
     RequestParams req = new RequestParams();               
     md5_password = GetMD5(password);               
     req["ligin"] = login;
     req["md5_password"] = md5_password;
     response = Post(req,"http://annimon.com/json/user/auth");
     return response;                  
 }         
Beispiel #47
0
      public static string GetString(RequestParams request)
      {
        if (request.Method != HTTPRequestMethod.GET && request.Method != HTTPRequestMethod.POST && request.Method != HTTPRequestMethod.PUT
           && request.Method != HTTPRequestMethod.DELETE)
          throw new NFXException(StringConsts.ARGUMENT_ERROR + typeof(WebClient).Name + ".GetString(method=GET|POST)");

        NameValueCollection queryParams;
        if (request.QueryParameters != null)
        {
          queryParams = new NameValueCollection(request.QueryParameters.Count);
          request.QueryParameters.ForEach(kvp => queryParams.Add(kvp.Key, kvp.Value));
        }
        else
        {
          queryParams = new NameValueCollection();
        }

        NameValueCollection bodyParams;
        if (request.BodyParameters != null)
        {
          bodyParams = new NameValueCollection(request.BodyParameters.Count);
          request.BodyParameters.ForEach(kvp => bodyParams.Add(kvp.Key, kvp.Value));
        }
        else
        {
          bodyParams = new NameValueCollection();
        }

        WebHeaderCollection headerParams = prepareRequestHeaders(request);

        string responseStr;
        using (var client = new WebClientTimeouted(request.Caller))
        {
          if (request.HasCredentials)
            client.Credentials = new NetworkCredential(request.UName, request.UPwd);

          client.Headers = headerParams;
          client.QueryString = queryParams;
          if (request.Method == HTTPRequestMethod.GET)
          {
            responseStr = Uri.UnescapeDataString(client.DownloadString(request.Uri));
          }
          else if (request.Method == HTTPRequestMethod.PUT || request.Method == HTTPRequestMethod.DELETE)
          {
            responseStr = Uri.UnescapeDataString(client.UploadString(request.Uri, request.Method.ToString(), request.Body ?? string.Empty));
          }
          else
          {
            var body = request.Body ?? 
                       (request.BodyParameters != null ?
                        string.Join("&", request.BodyParameters.Select(p => p.Key + "=" + p.Value)) : 
                        string.Empty);
            responseStr = Uri.UnescapeDataString(client.UploadString(request.Uri, body));
          }
        }

        return responseStr;
      }
Beispiel #48
0
 public static Task <string> GetStringAsync(string uri, RequestParams request)
 {
     return(GetStringAsync(new Uri(uri), request));
 }
Beispiel #49
0
 public static JSONDataMap GetJson(RequestParams prms)
 {
   string responseStr = GetString(prms);
   return responseStr.IsNullOrWhiteSpace() ? null : responseStr.JSONToDataObject() as JSONDataMap;
 }
Beispiel #50
0
 public static byte[] GetData(string uri, RequestParams request, out string contentType)
 {
     return(GetData(new Uri(uri), request, out contentType));
 }
 public TestLocationRequest( RequestParams requestParams, string testXml )
     : base(requestParams)
 {
     this.spotFeedRequest = new SpotFeedRequest( requestParams.Id, testXml, -1 );
 }
Beispiel #52
0
 public static byte[] GetData(Uri uri, RequestParams request)
 {
     string contentType; return(GetData(uri, request, out contentType));
 }
Beispiel #53
0
        /// <summary>
        /// Возвращает List с id квартир. Для перехода по страницам (каждая квартира имеет свою страницу). 
        /// </summary>
        /// <returns>коллекция ID квартир</returns>
        private static List<string> GetAllIdApartment(int numberApartments)
        {
            var listIdApartment = new List<string>();

            try
            {
                var reqParams = new RequestParams();

                //парсим и вытаскиваем все ID квартир (одна страница 20 квартир)
                for (int i = 0; i <= numberApartments; i += 20)
                {
                    using (var request = new HttpRequest())
                    {
                        reqParams["SEARCH_BEGINPOS"] = i.ToString();

                        //получпем страницу с квартирами
                        string contentPage = request.Post("www.volga-info.ru/togliatti/search/kvartiryi/x", reqParams).ToString();

                        string[] apartmentId;

                        //парсим страницу и записываем данные в массив
                        apartmentId = contentPage.Substrings("/togliatti/object/kvartiryi/", "/\">", 0).Distinct().ToArray();

                        foreach (var item in apartmentId)
                        {
                            listIdApartment.Add(item);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex);
            }

            return listIdApartment.Distinct().ToList();
        }
Beispiel #54
0
 public static Task <byte[]> GetDataAsync(string uri, RequestParams request)
 {
     return(GetDataAsync(new Uri(uri), request));
 }
Beispiel #55
0
        /// <summary>
        /// Отправляет GET-запрос HTTP-серверу.
        /// </summary>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="urlParams">Параметры URL-адреса, или значение <see langword="null"/>.</param>
        /// <returns>Объект, предназначенный для загрузки ответа от HTTP-сервера.</returns>
        /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="address"/> равно <see langword="null"/>.</exception>
        /// <exception cref="System.ArgumentException">Значение параметра <paramref name="address"/> является пустой строкой.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public HttpResponse Get(string address, RequestParams urlParams = null)
        {
            if (urlParams != null)
            {
                _temporaryUrlParams = urlParams;
            }

            return Raw(HttpMethod.GET, address);
        }
Beispiel #56
0
 public static Task <byte[]> GetDataAsync(Uri uri, RequestParams request)
 {
     return(DoRequest((client) => client.DownloadDataTaskAsync(uri), request));
 }
Beispiel #57
0
        private void ClearRequestData()
        {
            _content = null;

            _addedUrlParams = null;
            _addedParams = null;
            _addedMultipartContent = null;
            _addedHeaders = null;
        }
Beispiel #58
0
 public static Task <Tuple <byte[], string> > GetDataAsyncWithContentType(string uri, RequestParams request)
 {
     return(GetDataAsyncWithContentType(new Uri(uri), request));
 }
Beispiel #59
0
        /// <summary>
        /// Отправляет POST-запрос HTTP-серверу.
        /// </summary>
        /// <param name="address">Адрес интернет-ресурса.</param>
        /// <param name="reqParams">Параметры запроса, отправляемые HTTP-серверу.</param>
        /// <param name="dontEscape">Указывает, нужно ли кодировать параметры запроса.</param>
        /// <returns>Объект, предназначенный для загрузки ответа от HTTP-сервера.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// Значение параметра <paramref name="address"/> равно <see langword="null"/>.
        /// -или-
        /// Значение параметра <paramref name="reqParams"/> равно <see langword="null"/>.
        /// </exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public HttpResponse Post(Uri address, RequestParams reqParams, bool dontEscape = false)
        {
            #region Проверка параметров

            if (reqParams == null)
            {
                throw new ArgumentNullException("reqParams");
            }

            #endregion

            return Raw(HttpMethod.POST, address, new FormUrlEncodedContent(reqParams, dontEscape, CharacterSet));
        }
Beispiel #60
0
 public static Task <Tuple <byte[], string> > GetDataAsyncWithContentType(Uri uri, RequestParams request)
 {
     return(DoRequest((client) =>
                      client.DownloadDataTaskAsync(uri)
                      .ContinueWith((antecedent) => Tuple.Create(antecedent.Result, client.ResponseHeaders[HttpResponseHeader.ContentType])), request));
 }