Beispiel #2
0
 private static void ProcessResponse(IAsyncResult asyncResult, WebRequest request, HttpResponse resp, Action <HttpResponse> action)
 {
     lock (Http.pendingRequests)
     {
         if (Http.pendingRequests.Contains(resp))
         {
             Http.pendingRequests.Remove(resp);
         }
     }
     try
     {
         WebResponse webResponse = request.EndGetResponse(asyncResult);
         resp.IsConnected = true;
         WebResponse webResponse2 = webResponse;
         using (webResponse)
         {
             if (resp.Request.ResponseAsStream)
             {
                 resp.ResponseStream = webResponse.GetResponseStream();
             }
             else
             {
                 resp.RawResponse = webResponse.GetResponseStream().ReadToEnd();
             }
             if (webResponse2.Headers.AllKeys.Contains("Set-Cookie"))
             {
                 string text = webResponse2.Headers["Set-Cookie"];
                 int    num  = text.IndexOf(';');
                 if (num != -1)
                 {
                     foreach (KeyValuePair <string, string> current in HttpUtilityExtensions.ParseQueryString(text.Substring(0, num)))
                     {
                         resp.Cookies.Add(new Cookie(current.Key, current.Value));
                     }
                 }
             }
         }
     }
     catch (Exception ex2)
     {
         WebException ex = ex2 as WebException;
         if (ex != null)
         {
             HttpWebResponse httpWebResponse = ex.Response as HttpWebResponse;
             if (httpWebResponse != null)
             {
                 resp.HttpStatusCode = httpWebResponse.StatusCode;
             }
         }
         if (resp.ResponseStream != null)
         {
             resp.ResponseStream.Dispose();
             resp.ResponseStream = null;
         }
         resp.Exception = ex2;
         if (action != null)
         {
             action(resp);
         }
         return;
     }
     if (action != null)
     {
         action(resp);
     }
 }
Beispiel #3
0
        public void Initialize(string gameId, bool testMode)
        {
            if (debugMode)
            {
                Debug.Log("UnityAdsEditor: Initialize(" + gameId + ", " + testMode + ");");
            }

            var placeHolderGameObject = new GameObject("UnityAdsEditorPlaceHolderObject")
            {
                hideFlags = HideFlags.HideAndDontSave | HideFlags.HideInInspector
            };

            m_Placeholder           = placeHolderGameObject.AddComponent <Placeholder>();
            m_Placeholder.OnFinish += (object sender, FinishEventArgs e) =>
            {
                var handler = OnFinish;
                if (handler != null)
                {
                    handler(sender, new FinishEventArgs(e.placementId, e.showResult));
                }

                m_CallbackExecutor.Post(execute =>
                {
                    foreach (var listener in _listeners)
                    {
                        listener.OnUnityAdsDidFinish(e.placementId, e.showResult);
                    }
                });
            };

            string configurationUrl = string.Join("/", new string[] {
                s_BaseUrl,
                gameId,
                string.Join("&", new string[] {
                    "configuration?platform=editor",
                    "unityVersion=" + Uri.EscapeDataString(Application.unityVersion),
                    "sdkVersionName=" + Uri.EscapeDataString(version)
                })
            });
            WebRequest request = WebRequest.Create(configurationUrl);

            request.BeginGetResponse(result =>
            {
                WebResponse response = request.EndGetResponse(result);
                var reader           = new StreamReader(response.GetResponseStream());
                string responseBody  = reader.ReadToEnd();
                try
                {
                    m_Configuration = new Configuration(responseBody);
                    if (!m_Configuration.enabled)
                    {
                        Debug.LogWarning("gameId " + gameId + " is not enabled");
                    }

                    m_CallbackExecutor.Post(execute =>
                    {
                        foreach (var placement in m_Configuration.placements)
                        {
                            foreach (var listener in _listeners)
                            {
                                listener.OnUnityAdsReady(placement.Key);
                            }
                        }
                    });
                }
                catch (Exception exception)
                {
                    Debug.LogError("Failed to parse configuration for gameId: " + gameId);
                    Debug.Log(responseBody);
                    Debug.LogException(exception);
                    m_CallbackExecutor.Post(execute =>
                    {
                        foreach (var listener in _listeners)
                        {
                            listener.OnUnityAdsDidError("Failed to parse configuration for gameId: " + gameId);
                        }
                    });
                }
                reader.Close();
                response.Close();
            }, null);
        }
        private void HttpRequestReturn(IAsyncResult result)
        {
            RequestState state   = (RequestState)result.AsyncState;
            WebRequest   request = (WebRequest)state.Request;
            Stream       stream  = null;

            byte[] imageJ2000 = new byte[0];

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                if (response != null && response.StatusCode == HttpStatusCode.OK)
                {
                    stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        Bitmap image = new Bitmap(stream);
                        Size   newsize;

                        // TODO: make this a bit less hard coded
                        if ((image.Height < 64) && (image.Width < 64))
                        {
                            newsize = new Size(32, 32);
                        }
                        else if ((image.Height < 128) && (image.Width < 128))
                        {
                            newsize = new Size(64, 64);
                        }
                        else if ((image.Height < 256) && (image.Width < 256))
                        {
                            newsize = new Size(128, 128);
                        }
                        else if ((image.Height < 512 && image.Width < 512))
                        {
                            newsize = new Size(256, 256);
                        }
                        else if ((image.Height < 1024 && image.Width < 1024))
                        {
                            newsize = new Size(512, 512);
                        }
                        else
                        {
                            newsize = new Size(1024, 1024);
                        }

                        Bitmap resize = new Bitmap(image, newsize);

                        try
                        {
                            imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
                        }
                        catch (Exception)
                        {
                            m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Encode Failed.  Empty byte data returned!");
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned");
                    }
                }
            }
            catch (WebException)
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            m_log.DebugFormat("[LOADIMAGEURLMODULE] Returning {0} bytes of image data for request {1}",
                              imageJ2000.Length, state.RequestID);
            m_textureManager.ReturnData(state.RequestID, imageJ2000);
        }
Beispiel #5
0
        public void LoadRssFeed()
        {
            WebRequest request = WebRequest.Create(Url);

            request.BeginGetResponse((args) =>
            {
                // Download XML.
                Stream stream       = request.EndGetResponse(args).GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string xml          = reader.ReadToEnd();

                // Parse XML to extract data from RSS feed.
                XDocument doc    = XDocument.Parse(xml);
                XElement rss     = doc.Element(XName.Get("rss"));
                XElement channel = rss.Element(XName.Get("channel"));

                // Set Title property.
                Title = channel.Element(XName.Get("title")).Value;

                // Set Items property.
                List <RSSFeedItem> list =
                    channel.Elements(XName.Get("item")).Select((XElement element) =>
                {
                    return(new RSSFeedItem()
                    {
                        Title = element.Element(XName.Get("title")).Value,
                        Description = element.Element(XName.Get("description")).Value,
                        Link = element.Element(XName.Get("link")).Value,
                        PubDate = element.Element(XName.Get("pubDate")).Value,
                        Thumbnail = ""
                    });
                }).ToList();
                list.Add(new RSSFeedItem()
                {
                    Title       = "TopCách ly toàn xã hội từ 1/4 trên toàn quốc: Người dân cần tuân thủ những gì?",
                    Description = "Cách ly toàn xã hội từ 1/4 trên toàn quốc: Người dân cần tuân thủ những gì?",
                    Link        = "https://www.24h.com.vn/tin-tuc-trong-ngay/cach-ly-toan-xa-hoi-tu-1-4-tren-toan-quoc-nguoi-dan-can-tuan-thu-nhung-gi-c46a1136809.html",
                    PubDate     = "Wed, 01 Apr 2020 14:13:34 +0700",
                    Thumbnail   = "https://gamek.mediacdn.vn/2017/smile-emojis-icon-facebook-funny-emotion-women-s-premium-long-sleeve-t-shirt-1500882676711.jpg"
                });
                list.Add(new RSSFeedItem()
                {
                    Title       = "Top1Cách ly toàn xã hội từ 1/4 trên toàn quốc: Người dân cần tuân thủ những gì?",
                    Description = "Cách ly toàn xã hội từ 1/4 trên toàn quốc: Người dân cần tuân thủ những gì?",
                    Link        = "https://www.24h.com.vn/tin-tuc-trong-ngay/cach-ly-toan-xa-hoi-tu-1-4-tren-toan-quoc-nguoi-dan-can-tuan-thu-nhung-gi-c46a1136809.html",
                    PubDate     = "Wed, 01 Apr 2020 14:13:34 +0700",
                    Thumbnail   = "https://gamek.mediacdn.vn/2017/smile-emojis-icon-facebook-funny-emotion-women-s-premium-long-sleeve-t-shirt-1500882676711.jpg"
                });
                var lstItem = list.OrderByDescending(s => s.PubDateTime).ToList();
                try
                {
                    if (!string.IsNullOrEmpty(searchText))
                    {
                        Items = lstItem.Where(s => s.Title.ToLower().Contains(searchText.ToLower())).ToList().ToObservableCollection();
                    }
                    else
                    {
                        Items = lstItem.ToObservableCollection();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                // Set IsRefreshing to false to stop the 'wait' icon.
                IsRefreshing = false;
            }, null);
        }
Beispiel #6
0
        /// <summary>
        /// Gets the response.
        /// </summary>
        /// <param name="__result">The result.</param>
        protected override void getResponse(IAsyncResult __result)
        {
            if (__result == null)
            {
                status = webRequestEventType.error;
                return;
            }

            if (status == webRequestEventType.error)
            {
                return;
            }
            else
            {
            }

            try
            {
                result.response = new webResponse(httpRequest.EndGetResponse(__result));
            }
            catch (Exception ex)
            {
                // logSystem.log("Web Request error ["+getClientInfo()+"]: " + ex.Message, logType.Warning);
                status = webRequestEventType.error;
                // result.response = new webResponse();
                // result.response.
                //source = ex.Message;

                //throw;
            }

            if (status == webRequestEventType.error)
            {
                return;
            }
            else
            {
            }
            String       source = "";
            StreamReader reader = null;

            switch (action)
            {
            //case webRequestActionType.Text:

            //    break;
            default:
            case webRequestActionType.openUrl:
            case webRequestActionType.GetHeaders:
            case webRequestActionType.XML:
            case webRequestActionType.HTMLasXML:
                try
                {
                    reader = new StreamReader(result.response._response.GetResponseStream());
                }
                catch (Exception ex)
                {
                    //  this.note(ex);
                    callExecutionError(webRequestEventType.error, "Error in response Stream catch :: " + ex.Message);
                }

                try
                {
                    source = reader.ReadToEnd();
                }
                catch (Exception ex)
                {
                    //this.note(ex);
                    callExecutionError(webRequestEventType.error, "Error in stream reading :: " + ex.Message);
                    if (source == null)
                    {
                        source = "";
                    }
                    source += "<div> " + ex.Message + "</div>";
                    //throw;
                }
                break;
            }


            try
            {
                result.document.deploySource(source, action, result.request.htmlSettings);
                status = webRequestEventType.loaded;
            }
            catch (Exception ex)
            {
                //this.note(ex);
                callExecutionError(webRequestEventType.error, "Error in document sourceDeploying :: " + ex.Message);
                source += "<div> " + ex.Message + "</div>";
                //throw;
            }

            if (settings.doUseCache)
            {
                if (status == webRequestEventType.loaded)
                {
                    webCacheSystem.saveCache(url, source, result.response);
                }
            }
        }
Beispiel #7
0

        
Beispiel #8
0
        private static void tfrcallback(IAsyncResult ar)
        {
            try
            {
                string content = "";

                // check if cache exists and last write was today
                if (File.Exists(tfrcache) &&
                    new FileInfo(tfrcache).LastWriteTime.ToShortDateString() == DateTime.Now.ToShortDateString())
                {
                    content = File.ReadAllText(tfrcache);
                }
                else
                {
                    // Set the State of request to asynchronous.
                    WebRequest myWebRequest1 = (WebRequest)ar.AsyncState;

                    using (WebResponse response = myWebRequest1.EndGetResponse(ar))
                    {
                        var st = response.GetResponseStream();

                        StreamReader sr = new StreamReader(st);

                        content = sr.ReadToEnd();

                        File.WriteAllText(tfrcache, content);
                    }
                }

                XDocument xdoc = XDocument.Parse(content);

                tfritem currenttfr = new tfritem();

                for (int a = 1; a < 100; a++)
                {
                    var newtfrs = (from _item in xdoc.Element("TFRSET").Elements("TFR" + a)
                                   select new tfritem
                    {
                        ID = _item.Element("ID").Value,
                        NID = _item.Element("NID").Value,
                        VERIFIED = _item.Element("VERIFIED").Value,
                        NAME = _item.Element("NAME").Value,
                        COMMENT = _item.Element("COMMENT").Value,
                        ACCESS = _item.Element("ACCESS").Value,
                        APPEAR = _item.Element("APPEAR").Value,
                        TYPE = _item.Element("TYPE").Value,
                        MINALT = _item.Element("MINALT").Value,
                        MAXALT = _item.Element("MAXALT").Value,
                        SEGS = _item.Element("SEGS").Value,
                        BOUND = _item.Element("BOUND").Value,
                        SRC = _item.Element("SRC").Value,
                        CREATED = _item.Element("CREATED").Value,
                        MODIFIED = _item.Element("MODIFIED").Value,
                        DELETED = _item.Element("DELETED").Value,
                        ACTIVE = _item.Element("ACTIVE").Value,
                        EXPIRES = _item.Element("EXPIRES").Value,
                        SUBMITID = _item.Element("SUBMITID").Value,
                        SUBMITHOST = _item.Element("SUBMITHOST").Value,
                    }).ToList();

                    if (newtfrs == null || newtfrs.Count == 0)
                    {
                        break;
                    }

                    tfrs.AddRange(newtfrs);
                }

                if (GotTFRs != null)
                {
                    GotTFRs(tfrs, null);
                }
            }
            catch {  }
        }
Beispiel #9
0
 public override WebResponse EndGetResponse(IAsyncResult asyncResult)
 {
     return(webRequest.EndGetResponse(asyncResult));
 }
Beispiel #10
0
        private void RequestCallback(IAsyncResult asyncResult)
        {
            RequestState requestState = (RequestState)asyncResult.AsyncState;
            WebRequest   request      = requestState.request;

            WebResponse response = null;

            try
            {
                response = request.EndGetResponse(asyncResult);
            }
            catch (WebException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }

            Tile tile = requestState.tile;

            if (response == null)
            {
                lock (_requestQueue)
                {
                    _requestsOpen--;
                    _requestQueue.Remove(tile);
                }

                _serverError = true;

                return;
            }

            Stream       resp_stream = response.GetResponseStream();
            MemoryStream mem_stream  = WriteToMemStream(resp_stream);

            if (_callback != null)
            {
                _callback(tile, mem_stream);
            }

            tile.IsRequested = false;                           // redundant in ImageCacheDisk.Add()

            resp_stream.Close();
            mem_stream.Close();

            Tile next_tile = null;

            lock (_requestQueue)
            {
                _requestsOpen--;
                _requestQueue.Remove(tile);

                LinkedListNode <Tile> next_node = _requestQueue.First;

                while (next_node != null)
                {
                    if (!next_node.Value.IsRequested)
                    {
                        next_tile = next_node.Value;

                        next_tile.IsRequested = true;
                        _requestsOpen++;
                        break;
                    }

                    next_node = next_node.Next;
                }
            }

            if (next_tile != null)
            {
                DownloadTileAsync(next_tile);
            }
        }
        /// <summary>
        /// Perform an asynchronous REST request.
        /// </summary>
        /// <param name="verb"></param>
        /// <param name="requestUrl"></param>
        /// <param name="obj"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        ///
        /// <exception cref="System.Net.WebException">Thrown if we encounter a
        /// network issue while posting the request.  You'll want to make
        /// sure you deal with this as they're not uncommon</exception>
        //
        public static void MakeRequest <TRequest, TResponse>(string verb,
                                                             string requestUrl, TRequest obj, Action <TResponse> action)
        {
            Type type = typeof(TRequest);

            WebRequest    request      = WebRequest.Create(requestUrl);
            WebResponse   response     = null;
            TResponse     deserial     = default(TResponse);
            XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));

            request.Method = verb;

            if (verb == "POST")
            {
                request.ContentType = "text/xml";

                MemoryStream buffer = new MemoryStream();

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = Encoding.UTF8;

                using (XmlWriter writer = XmlWriter.Create(buffer, settings))
                {
                    XmlSerializer serializer = new XmlSerializer(type);
                    serializer.Serialize(writer, obj);
                    writer.Flush();
                }

                int length = (int)buffer.Length;
                request.ContentLength = length;

                request.BeginGetRequestStream(delegate(IAsyncResult res)
                {
                    Stream requestStream = request.EndGetRequestStream(res);

                    requestStream.Write(buffer.ToArray(), 0, length);

                    request.BeginGetResponse(delegate(IAsyncResult ar)
                    {
                        response = request.EndGetResponse(ar);

                        try
                        {
                            deserial = (TResponse)deserializer.Deserialize(
                                response.GetResponseStream());
                        }
                        catch (System.InvalidOperationException)
                        {
                        }

                        action(deserial);
                    }, null);
                }, null);

                return;
            }

            request.BeginGetResponse(delegate(IAsyncResult res2)
            {
                response = request.EndGetResponse(res2);

                try
                {
                    deserial = (TResponse)deserializer.Deserialize(
                        response.GetResponseStream());
                }
                catch (System.InvalidOperationException)
                {
                }

                action(deserial);
            }, null);
        }
Beispiel #12
0
 /// <summary>
 /// Ends the reading of the response string.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <returns></returns>
 public string EndReadResponseString(IAsyncResult result)
 {
     return(ReadStringInternal(() => WebRequest.EndGetResponse(result)));
 }
Beispiel #13
0
        private void SendCrashes(IsolatedStorageFile store, string[] filenames)
        {
            foreach (String filename in filenames)
            {
                try
                {
                    Stream fileStream = store.OpenFile(Path.Combine(CrashDirectoryName, filename), FileMode.Open);
                    string log        = "";
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        log = reader.ReadToEnd();
                    }
                    string body = "";
                    body += "raw=" + HttpUtility.UrlEncode(log);
                    body += "&sdk=" + SdkName;
                    body += "&sdk_version=" + SdkVersion;
                    fileStream.Close();

                    WebRequest request = WebRequestCreator.ClientHttp.Create(new Uri("https://rink.hockeyapp.net/api/2/apps/" + identifier + "/crashes"));
                    request.Method      = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Headers[HttpRequestHeader.UserAgent] = "Hockey/WP7";

                    request.BeginGetRequestStream(requestResult =>
                    {
                        try
                        {
                            Stream stream    = request.EndGetRequestStream(requestResult);
                            byte[] byteArray = Encoding.UTF8.GetBytes(body);
                            stream.Write(byteArray, 0, body.Length);
                            stream.Close();

                            request.BeginGetResponse(responseResult =>
                            {
                                Boolean deleteCrashes = true;
                                try
                                {
                                    request.EndGetResponse(responseResult);
                                }
                                catch (WebException e)
                                {
                                    if ((e.Status == WebExceptionStatus.ConnectFailure) ||
                                        (e.Status == WebExceptionStatus.ReceiveFailure) ||
                                        (e.Status == WebExceptionStatus.SendFailure) ||
                                        (e.Status == WebExceptionStatus.Timeout) ||
                                        (e.Status == WebExceptionStatus.UnknownError))
                                    {
                                        deleteCrashes = false;
                                    }
                                }
                                catch (Exception)
                                {
                                }
                                finally
                                {
                                    if (deleteCrashes)
                                    {
                                        DeleteCrashes(store, filenames);
                                    }
                                }
                            }, null);
                        }
                        catch (Exception)
                        {
                        }
                    }, null);
                }
                catch (Exception)
                {
                    store.DeleteFile(Path.Combine(CrashDirectoryName, filename));
                }
            }
        }
Beispiel #14
0
        public void EndProcessRequest(IAsyncResult result)
        {
            string      resultdata = String.Empty;
            Site        site       = (Site)result.AsyncState;
            XmlElement  ResultXML;
            XmlDocument outgoingcount;
            WebResponse response = null;


            try
            {
                response = _request.EndGetResponse(result);
            }
            catch
            {
                return;
            }

            string ResultCount          = string.Empty;
            string ResultDetailsURL     = string.Empty;
            string ResultPopulationType = string.Empty;
            string ResultPreviewURL     = string.Empty;
            string ResultText           = string.Empty;
            string sql = string.Empty;

            using (response)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                resultdata = reader.ReadToEnd();
                reader.Close();

                outgoingcount = new XmlDocument();

                if (resultdata != "ERROR")
                {
                    resultdata = this.CRLF(resultdata);
                    try
                    {
                        outgoingcount.LoadXml(resultdata);

                        ResultText           = resultdata;
                        ResultXML            = outgoingcount.DocumentElement;
                        ResultCount          = GetXMLText(ResultXML, "//count");
                        ResultDetailsURL     = GetXMLText(ResultXML, "//search-results-URL");
                        ResultPopulationType = GetXMLText(ResultXML, "//population-type");
                        ResultPreviewURL     = GetXMLText(ResultXML, "//preview-URL");
                    }
                    catch (Exception ex)
                    {
                        ex = ex;
                    }
                }
                else
                {
                    ResultText = resultdata;
                }

                DIRECT.Utilities.DataIO data = new DIRECT.Utilities.DataIO();
                data.UpdateLogOutgoing(site.FSID, 4, 200, ResultText.Substring(0, ResultText.Length > 3000 ? 3000 : ResultText.Length), ResultCount, ResultDetailsURL);


                //if (Conn.State == System.Data.ConnectionState.Open)
                //    Conn.Close();

                site.JavaScript = "<script language=\"javascript\" type=\"text/javascript\">parent.siteResult(" + site.SiteID + ",0," + ch(ResultCount) + "," + ch(ResultDetailsURL) + "," + ch(ResultPopulationType) + "," + ch(ResultPreviewURL) + ",'" + site.FSID + "');</script>" + Environment.NewLine;
                try
                {
                    site.Context.Response.Write(site.JavaScript);
                }
                catch (Exception ex)
                {
                    //do nothing
                }
                try
                {
                    site.Context.Response.Flush();
                }
                catch (Exception ex)
                { ex = ex; }
                site.IsDone = true;
                this.Site   = site;
                response.Close();
            }
        }
        public void UpdateMemberDetails()
        {
            WebRequest webRequest = WebRequest.Create("http://08309web.net.dcs.hull.ac.uk/borre/service.svc/member");

            webRequest.Method      = "POST";
            webRequest.ContentType = "application/json";

            webRequest.BeginGetRequestStream(a =>
            {
                Stream datastream;
                DataContractJsonSerializer ser;
                StreamWriter sw;

                try
                {
                    datastream = webRequest.EndGetRequestStream(a);

                    MemoryStream ms = new MemoryStream();

                    ser = new DataContractJsonSerializer(typeof(Member));
                    ser.WriteObject(ms, member);

                    string json = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);

                    sw = new StreamWriter(datastream);
                    sw.Write(json);
                    sw.Close();

                    ms.Close();

                    datastream.Close();
                }
                catch
                {
                }

                webRequest.BeginGetResponse(b =>
                {
                    try
                    {
                        bool result;

                        WebResponse response = webRequest.EndGetResponse(b);
                        datastream           = response.GetResponseStream();
                        ser    = new DataContractJsonSerializer(typeof(bool));
                        result = (bool)ser.ReadObject(datastream);

                        datastream.Close();
                        response.Close();

                        if (result)
                        {
                            Dispatcher.BeginInvoke(() => showresult());
                        }
                    }
                    catch
                    {
                    }
                }
                                            , null);
            }
                                             , null);
        }
Beispiel #16
0
        /// <summary>
        /// Returns a response to an Internet request as an asynchronous operation.
        /// </summary>
        /// <remarks>
        /// This operation will not block. The returned <see cref="Task{TResult}"/> object will
        /// complete after a response to an Internet request is available.
        /// </remarks>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new <see cref="Task"/>.</param>
        /// <returns>A <see cref="Task"/> object which represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="request"/> is <see langword="null"/>.</exception>
        /// <exception cref="WebException">
        /// If <see cref="WebRequest.Abort"/> was previously called.
        /// <para>-or-</para>
        /// <para>If the timeout period for the request expired.</para>
        /// <para>-or-</para>
        /// <para>If an error occurred while processing the request.</para>
        /// </exception>
        public static Task <WebResponse> GetResponseAsync(this WebRequest request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            bool timeout = false;
            TaskCompletionSource <WebResponse> completionSource = new TaskCompletionSource <WebResponse>();

            RegisteredWaitHandle timerRegisteredWaitHandle        = null;
            RegisteredWaitHandle cancellationRegisteredWaitHandle = null;
            AsyncCallback        completedCallback =
                result =>
            {
                try
                {
                    if (cancellationRegisteredWaitHandle != null)
                    {
                        cancellationRegisteredWaitHandle.Unregister(null);
                    }

                    if (timerRegisteredWaitHandle != null)
                    {
                        timerRegisteredWaitHandle.Unregister(null);
                    }

                    completionSource.TrySetResult(request.EndGetResponse(result));
                }
                catch (WebException ex)
                {
                    if (timeout)
                    {
                        completionSource.TrySetException(new WebException("No response was received during the time-out period for a request.", WebExceptionStatus.Timeout));
                    }
                    else if (cancellationToken.IsCancellationRequested)
                    {
                        completionSource.TrySetCanceled();
                    }
                    else
                    {
                        completionSource.TrySetException(ex);
                    }
                }
                catch (Exception ex)
                {
                    completionSource.TrySetException(ex);
                }
            };

            IAsyncResult asyncResult = request.BeginGetResponse(completedCallback, null);

            if (!asyncResult.IsCompleted)
            {
                if (request.Timeout != Timeout.Infinite)
                {
                    WaitOrTimerCallback timedOutCallback =
                        (object state, bool timedOut) =>
                    {
                        if (timedOut)
                        {
                            timeout = true;
                            request.Abort();
                        }
                    };

                    timerRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, timedOutCallback, null, request.Timeout, true);
                }

                if (cancellationToken.CanBeCanceled)
                {
                    WaitOrTimerCallback cancelledCallback =
                        (object state, bool timedOut) =>
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            request.Abort();
                        }
                    };

                    cancellationRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(cancellationToken.WaitHandle, cancelledCallback, null, Timeout.Infinite, true);
                }
            }

            return(completionSource.Task);
        }
Beispiel #17
0
        /// <summary>
        /// For the Request and Access Token stages, makes the request and parses out the OAuth tokens from
        /// the server.
        /// </summary>
        /// <param name="request">The request that needs to be signed with OAuth.</param>
        /// <returns>A <see cref="Tokens"/> object containing the Access Token and Access Secret provided by the OAuth server.</returns>
        /// <remarks>You typically call this when making a request to get the users access tokens and combine this with the <see cref="Tokens.MergeWith"/> function.</remarks>
        /// <example>
        ///     <code>
        ///     var request = WebRequest.Create("https://api.twitter.com/oauth/request_token") { Method = "POST" };
        ///     request.SignRequest(RequestTokens)
        ///         .WithCallback("oob")
        ///         .InHeader();
        ///
        ///     var accessTokens = request.GetOAuthTokens();
        ///     RequestTokens.MergeWith(accessTokens);
        ///     </code>
        /// In the above example, the <see cref="WebRequest"/> is created, and signed with a specific set of <see cref="Tokens"/>. A call to <see cref="GetOAuthTokens"/>
        /// is made and then merged with the original Request Tokens.
        /// </example>
        /// <exception cref="WebException">Thrown when the <paramref name="request"/> encounters an error.</exception>
        public static void GetOAuthTokensAsync(this WebRequest request, Action <Tokens, Exception> callback)
        {
            var newTokens = new Tokens();

            var output = string.Empty;

            WebResponse  response             = null;
            StreamReader responseStreamReader = null;
            Exception    thrownException      = null;

            request.BeginGetResponse((responseResult) =>
            {
                try
                {
                    try
                    {
                        response = request.EndGetResponse(responseResult);

                        responseStreamReader = new StreamReader(response.GetResponseStream());

                        output = responseStreamReader.ReadToEnd();

                        if (!String.IsNullOrEmpty(output))
                        {
                            var dataValues = UrlHelper.ParseQueryString(output);

                            if (!dataValues.ContainsKey("oauth_token") ||
                                !dataValues.ContainsKey("oauth_token_secret"))
                            {
                                var ex = new Exception("Response did not contain oauth_token and oauth_token_secret. Response is contained in Data of exception.");
                                ex.Data.Add("ResponseText", output);
                                ex.Data.Add("RequestUri", request.RequestUri);
                                ex.Data.Add("RequestMethod", request.Method);
                                ex.Data.Add("RequestHeaders", request.Headers);
                                ex.Data.Add("ResponseHeaders", response.Headers);
                                throw ex;
                            }
                            newTokens.AccessToken       = dataValues["oauth_token"];
                            newTokens.AccessTokenSecret = dataValues["oauth_token_secret"];
                        }
                    }
                    catch (Exception ex)
                    {
                        thrownException = ex;
                    }

                    if (thrownException != null)
                    {
                        callback(null, thrownException);
                    }
                    else
                    {
                        callback(newTokens, null);
                    }
                }
                finally
                {
                    try { if (responseStreamReader != null)
                          {
                              responseStreamReader.Dispose();
                          }
                    }
                    catch { }
                    try { if (response != null)
                          {
                              ((IDisposable)response).Dispose();
                          }
                    }
                    catch { }
                }
            }, null);
        }
Beispiel #18
0
        private void LEn1aOXgs([In] IAsyncResult obj0)
        {
            HistoricalDataRequest historicalDataRequest = (HistoricalDataRequest)obj0.AsyncState;
            WebRequest            webRequest            = (WebRequest)null;

            if (!this.EjDBtJJBo.TryGetValue(historicalDataRequest.RequestId, out webRequest))
            {
                return;
            }
            this.EjDBtJJBo.Remove(historicalDataRequest.RequestId);
            try
            {
                StreamReader  streamReader = new StreamReader(webRequest.EndGetResponse(obj0).GetResponseStream());
                List <string> list1        = new List <string>();
                string        str;
                while ((str = streamReader.ReadLine()) != null)
                {
                    list1.Add(str);
                }
                list1.RemoveAt(0);
                list1.Reverse();
                List <Daily> list2 = new List <Daily>();
                for (int index1 = 0; index1 < list1.Count; ++index1)
                {
                    string[] strArray = list1[index1].Split(new char[1]
                    {
                        ','
                    });
                    if (strArray.Length >= 7)
                    {
                        for (int index2 = 0; index2 < strArray.Length; ++index2)
                        {
                            strArray[index2] = strArray[index2].Trim(new char[1]
                            {
                                '"'
                            });
                            if (strArray[index2] == RbFKKlTxInQUoAZCSj.q6GyF96n8(274))
                            {
                                strArray[index2] = RbFKKlTxInQUoAZCSj.q6GyF96n8(284);
                            }
                        }
                        Daily daily1 = new Daily(DateTime.Parse(strArray[0], (IFormatProvider)CultureInfo.InvariantCulture), double.Parse(strArray[1], (IFormatProvider)CultureInfo.InvariantCulture), double.Parse(strArray[2], (IFormatProvider)CultureInfo.InvariantCulture), double.Parse(strArray[3], (IFormatProvider)CultureInfo.InvariantCulture), double.Parse(strArray[4], (IFormatProvider)CultureInfo.InvariantCulture), long.Parse(strArray[5], (IFormatProvider)CultureInfo.InvariantCulture));
                        if (this.YGOxAtD62)
                        {
                            double num1   = double.Parse(strArray[6], (IFormatProvider)CultureInfo.InvariantCulture);
                            double num2   = num1 / daily1.Close;
                            Daily  daily2 = daily1;
                            double num3   = daily2.Open * num2;
                            daily2.Open = num3;
                            Daily  daily3 = daily1;
                            double num4   = daily3.High * num2;
                            daily3.High = num4;
                            Daily  daily4 = daily1;
                            double num5   = daily4.Low * num2;
                            daily4.Low   = num5;
                            daily1.Close = num1;
                        }
                        list2.Add(daily1);
                    }
                }
                foreach (Daily daily in list2)
                {
                    if (this.FexSQYEw9.Contains((object)historicalDataRequest.RequestId))
                    {
                        this.FexSQYEw9.Remove((object)historicalDataRequest.RequestId);
                        this.J9LThvcYS(historicalDataRequest, list2.Count);
                        return;
                    }
                    else if (this.c6Jl2nfcs != null)
                    {
                        this.c6Jl2nfcs((object)this, new HistoricalBarEventArgs((Bar)daily, historicalDataRequest.RequestId, historicalDataRequest.Instrument, (IHistoricalDataProvider)this, list2.Count));
                    }
                }
                this.xmlocsjtF(historicalDataRequest, list2.Count);
            }
            catch (Exception ex)
            {
                if (this.FexSQYEw9.Contains((object)historicalDataRequest.RequestId))
                {
                    this.FexSQYEw9.Remove((object)historicalDataRequest.RequestId);
                    this.J9LThvcYS(historicalDataRequest, 0);
                }
                else
                {
                    this.iC2ZqQH0T(historicalDataRequest, ex.Message);
                }
            }
        }
        /// <summary>
        /// Called when a corresponding asynchronous load operation completes.
        /// </summary>
        /// <param name="result">The result of the asynchronous operation.</param>
        private static void AsyncLoadCallback(IAsyncResult result)
        {
            System.Text.Encoding encoding       = System.Text.Encoding.UTF8;
            XPathNavigator       navigator      = null;
            WebRequest           httpWebRequest = null;
            AtomEntryResource    entry          = null;
            Uri source = null;
            WebRequestOptions options = null;
            SyndicationResourceLoadSettings settings = null;

            if (result.IsCompleted)
            {
                object[] parameters = (object[])result.AsyncState;
                httpWebRequest = parameters[0] as WebRequest;
                entry          = parameters[1] as AtomEntryResource;
                source         = parameters[2] as Uri;
                settings       = parameters[3] as SyndicationResourceLoadSettings;
                options        = parameters[4] as WebRequestOptions;
                object userToken = parameters[5];

                if (entry != null)
                {
                    WebResponse httpWebResponse = (WebResponse)httpWebRequest.EndGetResponse(result);

                    using (Stream stream = httpWebResponse.GetResponseStream())
                    {
                        if (settings != null)
                        {
                            encoding = settings.CharacterEncoding;
                        }

                        using (StreamReader streamReader = new StreamReader(stream, encoding))
                        {
                            XmlReaderSettings readerSettings = new XmlReaderSettings();
                            readerSettings.IgnoreComments   = true;
                            readerSettings.IgnoreWhitespace = true;
                            readerSettings.DtdProcessing    = DtdProcessing.Ignore;

                            using (XmlReader reader = XmlReader.Create(streamReader, readerSettings))
                            {
                                if (encoding == System.Text.Encoding.UTF8)
                                {
                                    navigator = SyndicationEncodingUtility.CreateSafeNavigator(source, options, null);
                                }
                                else
                                {
                                    navigator = SyndicationEncodingUtility.CreateSafeNavigator(source, options, settings.CharacterEncoding);
                                }

                                SyndicationResourceAdapter adapter = new SyndicationResourceAdapter(navigator, settings);
                                adapter.Fill(entry, SyndicationContentFormat.Atom);

                                AtomPublishingEditedSyndicationExtension editedExtension = entry.FindExtension(AtomPublishingEditedSyndicationExtension.MatchByType) as AtomPublishingEditedSyndicationExtension;
                                if (editedExtension != null)
                                {
                                    entry.EditedOn = editedExtension.Context.EditedOn;
                                }

                                AtomPublishingControlSyndicationExtension controlExtension = entry.FindExtension(AtomPublishingControlSyndicationExtension.MatchByType) as AtomPublishingControlSyndicationExtension;
                                if (controlExtension != null)
                                {
                                    entry.IsDraft = controlExtension.Context.IsDraft;
                                }

                                entry.OnEntryLoaded(new SyndicationResourceLoadedEventArgs(navigator, source, options, userToken));
                            }
                        }
                    }

                    entry.LoadOperationInProgress = false;
                }
            }
        }
Beispiel #20
0
        private void SearchCallback(IAsyncResult result)
        {
            try {
                RequestState2 rs = (RequestState2)result.AsyncState;

                //Don't do anything if this isn't the last web request we made
                if (rs.webURL != lastURL)
                {
                    rs.Request.EndGetResponse(result);
                    //rs.Request.Abort();
                    return;
                }

                // Get the WebRequest from RequestState.
                WebRequest req = rs.Request;

                // Call EndGetResponse, which produces the WebResponse object
                //  that came from the request issued above.
                WebResponse resp = req.EndGetResponse(result);

                //  Start reading data from the response stream.
                Stream responseStream = resp.GetResponseStream();

                // Store the response stream in RequestState to read
                // the stream asynchronously.
                xmlReader = new XmlTextReader(responseStream);
                xmlDoc    = new XmlDocument();
                xmlDoc.Load(xmlReader);
                xmlReader.Close();
                resp.Close();
            } catch (WebException we) {
                MessageBox.Show(we.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            XmlNodeList memberNodes = xmlDoc.SelectNodes("//result");

            foreach (XmlNode node in memberNodes)
            {
                details.ProgramName  = GetNodeElement(node, "title");
                details.Year         = GetNodeElement(node, "year");
                details.Publisher    = GetNodeElement(node, "publisher");
                details.ProgramType  = GetNodeElement(node, "type");
                details.Language     = GetNodeElement(node, "language");
                details.Score        = GetNodeElement(node, "score");
                details.Authors      = GetNodeElement(node, "author");
                details.Controls     = GetNodeElement(node, "joysticks");
                details.Protection   = GetNodeElement(node, "protectionScheme");
                details.Availability = GetNodeElement(node, "availability");
                details.Publication  = GetNodeElement(node, "publication");
                details.MachineType  = GetNodeElement(node, "machineType");
                details.PicInlayURL  = GetNodeElement(node, "picInlay");
                details.PicLoadURL   = GetNodeElement(node, "picLoad");
                details.PicIngameURL = GetNodeElement(node, "picIngame");
            }

            if (string.IsNullOrEmpty(details.Protection))
            {
                details.Protection = "Various";
            }
            UpdateLabelInfo(authorLabel, details.Authors);
            UpdateLabelInfo(publicationLabel, details.Publication);
            UpdateLabelInfo(availabilityLabel, details.Availability);
            UpdateLabelInfo(protectionLabel, details.Protection);
            string controls = "";

            foreach (char c in details.Controls.ToCharArray())
            {
                if (c == 'K')
                {
                    controls += "Keyboard, ";
                }
                else if (c == '1')
                {
                    controls += "IF 2 Left, ";
                }
                else if (c == '2')
                {
                    controls += "IF 2 Right, ";
                }
                else if (c == 'C')
                {
                    controls += "Cursor, ";
                }
                else if (c == 'R')
                {
                    controls += "Redefinable, ";
                }
            }

            UpdateLabelInfo(controlsLabel, controls);
            UpdateLabelInfo(machineLabel, details.MachineType);

            XmlNodeList fileNodes = xmlDoc.SelectNodes("/result/downloads/file");

            foreach (XmlNode node in fileNodes)
            {
                String   full_link  = node.SelectSingleNode("link").InnerText;
                char     delimiter  = '/';
                string[] splitWords = full_link.Split(delimiter);
                String   type       = node.SelectSingleNode("type").InnerText;
                fileList.Add(full_link);
                UpdateCheckbox(checkedListBox1, " (" + type + ") " + splitWords[splitWords.Length - 1]);
            }

            XmlNodeList fileNodes2 = xmlDoc.SelectNodes("/result/otherDownloads/file");

            foreach (XmlNode node in fileNodes2)
            {
                String   full_link  = node.SelectSingleNode("link").InnerText;
                char     delimiter  = '/';
                string[] splitWords = full_link.Split(delimiter);
                String   type       = node.SelectSingleNode("type").InnerText;
                fileList.Add(full_link);
                UpdateCheckbox(checkedListBox1, " (" + type + ") " + splitWords[splitWords.Length - 1]);
            }

            toolStripStatusLabel1.Text = "Ready.";

            if (details.PicInlayURL != "")
            {
                try {
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(details.PicInlayURL);
                    webRequest.Method    = WebRequestMethods.Http.Get;
                    webRequest.UserAgent = "Zero Emulator";
                    // RequestState is a custom class to pass info to the callback
                    RequestState2 rs2 = new RequestState2();
                    rs2.Request = webRequest;

                    IAsyncResult result2 = webRequest.BeginGetResponse(new AsyncCallback(PictureLoadCallback), rs2);

                    ThreadPool.RegisterWaitForSingleObject(result2.AsyncWaitHandle,
                                                           new WaitOrTimerCallback(InfoseekTimeout),
                                                           rs2,
                                                           (30 * 1000), // 30 second timeout
                                                           true
                                                           );
                } catch (WebException we) {
                    MessageBox.Show(we.Message, "Connection Error", MessageBoxButtons.OK);
                }
            }

            if (details.PicLoadURL != "")
            {
                try {
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(details.PicLoadURL);
                    webRequest.Method    = WebRequestMethods.Http.Get;
                    webRequest.UserAgent = "Zero Emulator";
                    // RequestState is a custom class to pass info to the callback
                    RequestState2 rs2 = new RequestState2();
                    rs2.Request = webRequest;

                    IAsyncResult result2 = webRequest.BeginGetResponse(new AsyncCallback(PictureLoadCallback), rs2);

                    ThreadPool.RegisterWaitForSingleObject(result2.AsyncWaitHandle,
                                                           new WaitOrTimerCallback(InfoseekTimeout),
                                                           rs2,
                                                           (30 * 1000), // 30 second timeout
                                                           true
                                                           );
                } catch (WebException we) {
                    MessageBox.Show(we.Message, "Connection Error", MessageBoxButtons.OK);
                }
            }

            if (details.PicIngameURL != "")
            {
                try {
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(details.PicIngameURL);
                    webRequest.Method    = WebRequestMethods.Http.Get;
                    webRequest.UserAgent = "Zero Emulator";
                    // RequestState is a custom class to pass info to the callback
                    RequestState2 rs2 = new RequestState2();
                    rs2.Request = webRequest;

                    IAsyncResult result2 = webRequest.BeginGetResponse(new AsyncCallback(PictureLoadCallback), rs2);

                    ThreadPool.RegisterWaitForSingleObject(result2.AsyncWaitHandle,
                                                           new WaitOrTimerCallback(InfoseekTimeout),
                                                           rs2,
                                                           (30 * 1000), // 30 second timeout
                                                           true
                                                           );
                } catch (WebException we) {
                    MessageBox.Show(we.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// Perform an asynchronous REST request.
        /// </summary>
        /// <param name="verb">GET or POST</param>
        /// <param name="requestUrl"></param>
        /// <param name="obj"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        ///
        /// <exception cref="System.Net.WebException">Thrown if we encounter a
        /// network issue while posting the request.  You'll want to make
        /// sure you deal with this as they're not uncommon</exception>
        //
        public static void MakeRequest <TRequest, TResponse>(string verb,
                                                             string requestUrl, TRequest obj, Action <TResponse> action)
        {
            //            m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl);

            Type type = typeof(TRequest);

            WebRequest    request      = WebRequest.Create(requestUrl);
            WebResponse   response     = null;
            TResponse     deserial     = default(TResponse);
            XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));

            request.Method = verb;

            if (verb == "POST")
            {
                request.ContentType = "text/xml";

                MemoryStream buffer = new MemoryStream();

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = Encoding.UTF8;

                using (XmlWriter writer = XmlWriter.Create(buffer, settings))
                {
                    XmlSerializer serializer = new XmlSerializer(type);
                    serializer.Serialize(writer, obj);
                    writer.Flush();
                }

                int length = (int)buffer.Length;
                request.ContentLength = length;

                request.BeginGetRequestStream(delegate(IAsyncResult res)
                {
                    Stream requestStream = request.EndGetRequestStream(res);

                    requestStream.Write(buffer.ToArray(), 0, length);
                    requestStream.Close();

                    request.BeginGetResponse(delegate(IAsyncResult ar)
                    {
                        response          = request.EndGetResponse(ar);
                        Stream respStream = null;
                        try
                        {
                            respStream = response.GetResponseStream();
                            deserial   = (TResponse)deserializer.Deserialize(
                                respStream);
                        }
                        catch (System.InvalidOperationException)
                        {
                        }
                        finally
                        {
                            // Let's not close this
                            //buffer.Close();
                            respStream.Close();
                            response.Close();
                        }

                        action(deserial);
                    }, null);
                }, null);


                return;
            }

            request.BeginGetResponse(delegate(IAsyncResult res2)
            {
                try
                {
                    // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
                    // documented in MSDN
                    response = request.EndGetResponse(res2);

                    Stream respStream = null;
                    try
                    {
                        respStream = response.GetResponseStream();
                        deserial   = (TResponse)deserializer.Deserialize(respStream);
                    }
                    catch (System.InvalidOperationException)
                    {
                    }
                    finally
                    {
                        respStream.Close();
                        response.Close();
                    }
                }
                catch (WebException e)
                {
                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        if (e.Response is HttpWebResponse)
                        {
                            HttpWebResponse httpResponse = (HttpWebResponse)e.Response;

                            if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                            {
                                // We don't appear to be handling any other status codes, so log these feailures to that
                                // people don't spend unnecessary hours hunting phantom bugs.
                                m_log.DebugFormat(
                                    "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
                                    verb, requestUrl, httpResponse.StatusCode);
                            }
                        }
                    }
                    else
                    {
                        m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
                    }
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
                }

                //  m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());

                try
                {
                    action(deserial);
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat(
                        "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e);
                }
            }, null);
        }
Beispiel #22
0
        private void HttpRequestReturn(IAsyncResult result)
        {
            if (m_textureManager == null)
            {
                m_log.WarnFormat("[LOADIMAGEURLMODULE]: No texture manager. Can't function.");
                return;
            }

            RequestState state   = (RequestState)result.AsyncState;
            WebRequest   request = (WebRequest)state.Request;
            Stream       stream  = null;

            byte[] imageJ2000 = new byte[0];
            Size   newSize    = new Size(0, 0);

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                if (response != null && response.StatusCode == HttpStatusCode.OK)
                {
                    stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        try
                        {
                            Bitmap image = new Bitmap(stream);

                            // TODO: make this a bit less hard coded
                            if ((image.Height < 64) && (image.Width < 64))
                            {
                                newSize.Width  = 32;
                                newSize.Height = 32;
                            }
                            else if ((image.Height < 128) && (image.Width < 128))
                            {
                                newSize.Width  = 64;
                                newSize.Height = 64;
                            }
                            else if ((image.Height < 256) && (image.Width < 256))
                            {
                                newSize.Width  = 128;
                                newSize.Height = 128;
                            }
                            else if ((image.Height < 512 && image.Width < 512))
                            {
                                newSize.Width  = 256;
                                newSize.Height = 256;
                            }
                            else if ((image.Height < 1024 && image.Width < 1024))
                            {
                                newSize.Width  = 512;
                                newSize.Height = 512;
                            }
                            else
                            {
                                newSize.Width  = 1024;
                                newSize.Height = 1024;
                            }

                            using (Bitmap resize = new Bitmap(image, newSize))
                            {
                                imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
                            }
                        }
                        catch (Exception)
                        {
                            m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Conversion Failed.  Empty byte data returned!");
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned");
                    }
                }
            }
            catch (WebException)
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}",
                              imageJ2000.Length, state.RequestID);

            m_textureManager.ReturnData(
                state.RequestID,
                new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
                    request.RequestUri, null, imageJ2000, newSize, false));
        }
Beispiel #23
0
        // Starts at the starting URL and continues crawling links and updating database
        public void Crawl()
        {
            // Populate hash with urls from the database
            _seenURLS = _sc.GetVisited();

            Stopwatch      sw     = new Stopwatch();
            Queue <string> WebBFS = new Queue <string>();

            _logger.Initialize();
            WebBFS.Enqueue(_start);
            sw.Start();

            while (true)
            {
                // Exit after 30 minutes
                if (_runtime != -1 && sw.Elapsed.Minutes >= _runtime)
                {
                    Environment.Exit(0);
                }
                try
                {
                    string currentURL;

                    lock (WebBFS)
                    {
                        // Don't let queue grow indefinitely
                        currentURL = WebBFS.Dequeue();

                        if (WebBFS.Count >= ProducerBlock.high)
                        {
                            while (WebBFS.Count >= ProducerBlock.low)
                            {
                                WebBFS.Dequeue();
                            }
                        }
                    }

                    Console.WriteLine("Crawling " + currentURL);

                    WebRequest request = WebRequest.Create(currentURL);

                    IAsyncResult result = request.BeginGetResponse((IAsyncResult v) =>
                    {
                        try
                        {
                            WebResponse response = request.EndGetResponse(v);
                            Stream data          = response.GetResponseStream();
                            string html          = String.Empty;
                            Dictionary <string, bool> localSeen = new Dictionary <string, bool>();

                            using (StreamReader sr = new StreamReader(data))
                            {
                                html = sr.ReadToEnd();
                            }

                            html = Parser.SanitizeHtml(html);

                            IEnumerable <string> urls = Parser.GetURLS(html);

                            // Enqueue all the sites found from links
                            foreach (string s in urls)
                            {
                                string nextURL = s;

                                // If the link is relative add the current url
                                if (s.StartsWith("/"))
                                {
                                    nextURL = currentURL + s;
                                }
                                else if (!s.StartsWith("http"))
                                {
                                    nextURL = currentURL + "/" + s;
                                }
                                lock (WebBFS)
                                {
                                    // Don't allow a site to increase the page rank of a url more than once
                                    if (localSeen.ContainsKey(nextURL))
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        localSeen.Add(nextURL, true);
                                    }
                                    // Check if URL exists in our set
                                    if (_seenURLS.ContainsKey(nextURL))
                                    {
                                        _seenURLS[nextURL]++;
                                    }
                                    else
                                    {
                                        _seenURLS.Add(nextURL, 1);
                                        WebBFS.Enqueue(nextURL);
                                    }
                                }
                            }

                            // Parse content and write to SQL database
                            string content = Parser.GetContent(html);

                            Dictionary <string, int> keywords = Parser.GetKeywords(content);

                            // We are done with the large HTML string, have GC collect it
                            content = null;
                            html    = null;

                            // No keywords in the case of an HTML overflow
                            if (keywords.Count > 0)
                            {
                                _sc.BulkInsert(currentURL, keywords, _seenURLS[currentURL], localSeen);
                            }
                        }
                        catch (WebException we)
                        {
                            // Log failure
                            if (_logger._on)
                            {
                                _logger.Log(DateTime.Now + " " + we.Message + " " + "(" + currentURL + ")" + Environment.NewLine);
                            }
                        }
                        catch (Exception we)
                        {
                            if (_logger._on)
                            {
                                _logger.Log(DateTime.Now + " " + we.Message + " " + "(" + currentURL + ")" + Environment.NewLine);
                            }
                            return;
                        }
                    }, null);
                }
                catch (System.InvalidOperationException we)
                {
                    if (_logger._on)
                    {
                        _logger.Log(DateTime.Now + " " + we.Message + Environment.NewLine);
                    }
                    continue;
                }
                catch (Exception we)
                {
                    if (_logger._on)
                    {
                        _logger.Log(DateTime.Now + " " + we.Message + Environment.NewLine);
                    }
                    continue;
                }
            }
        }
 void Task1End(IAsyncResult result)
 {
     response = request.EndGetResponse(result).GetResponseStream();
 }
        //public ICommand EditCommand
        //{
        //    get
        //    {
        //        return _editCommand;
        //    }
        //}

        #endregion
        #region Load LoadRssFeed url rss
        public void LoadRssFeed()
        {
            if (!string.IsNullOrEmpty(Url))
            {
                WebRequest request = WebRequest.Create(Url);
                request.BeginGetResponse((args) =>
                {
                    try
                    {
                        // Download XML.
                        Stream stream       = request.EndGetResponse(args).GetResponseStream();
                        StreamReader reader = new StreamReader(stream);
                        string xml          = reader.ReadToEnd();
                        // Parse XML to extract data from RSS feed.
                        XDocument doc    = XDocument.Parse(xml);
                        XElement rss     = doc.Element(XName.Get("rss"));
                        XElement channel = rss.Element(XName.Get("channel"));
                        // Set Title property.
                        Title = channel.Element(XName.Get("title")).Value;
                        // Set Items property.
                        List <RSSFeedItem> list =
                            channel.Elements(XName.Get("item")).Select((XElement element) =>
                        {
                            var desciption = element.Element(XName.Get("description"));
                            //var image = desciption.Element(XName.Get("img")).Attribute("src").Value.ToString();
                            var result         = new RSSFeedItem();
                            result.Title       = element.Element(XName.Get("title")).Value;
                            result.Description = desciption.Value;
                            result.Link        = element.Element(XName.Get("link")).Value;
                            result.PubDate     = element.Element(XName.Get("pubDate")).Value;
                            #region get images form description
                            Regex regx = new Regex("http(s?)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?.(?:jpg|bmp|gif|png)", RegexOptions.IgnoreCase);
                            MatchCollection mactches = regx.Matches(desciption.ToString());
                            if (mactches.Count > 0)
                            {
                                foreach (var urlImage in mactches)
                                {
                                    result.Thumbnail = urlImage.ToString();
                                }
                            }
                            else
                            {
                                result.Thumbnail = "https://joebalestrino.com/wp-content/uploads/2019/02/Marketplace-Lending-News.jpg";
                            }
                            #endregion
                            return(result);
                        }).ToList();
                        var lstItem = list.OrderByDescending(s => s.PubDateTime).ToList();
                        try
                        {
                            if (!string.IsNullOrEmpty(searchText))
                            {
                                Items = lstItem.Where(s => s.Title.ToLower().Contains(searchText.ToLower())).ToList().ToObservableCollection();
                            }
                            else
                            {
                                Items = lstItem.ToObservableCollection();
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }

                        // Set IsRefreshing to false to stop the 'wait' icon.
                        IsRefreshing = false;
                    }
                    catch (Exception)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            Application.Current.MainPage.DisplayAlert("Server Error", "Not Connected", "OK");
                        });
                    }
                }, null);
            }
            else
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    Application.Current.MainPage.DisplayAlert("Error", "Please check url no empty", "OK");
                });
            }
        }
Beispiel #26
0
        /// <summary>
        /// Read asynchronous web response.
        /// Invoke the callback method to report completion.
        /// </summary>
        /// <param name="state">Async Web method state</param>
        private void EndAsyncResponse(IAsyncResult state)
        {
            AsyncWebMethodRequest  input         = state.AsyncState as AsyncWebMethodRequest;
            AsyncWebMethodResponse asyncResponse = new AsyncWebMethodResponse(input.State);

            try
            {
                WebRequest      request     = input.Request;
                HttpWebResponse webResponse = (HttpWebResponse)request.EndGetResponse(state);
                asyncResponse.StatusDescription = webResponse.StatusDescription;
                if (asyncResponse.StatusDescription == "OK")
                {
                    asyncResponse.Result = webResponse.GetResponseStream();
                    asyncResponse.Status = AsyncMethodState.Passed;
                }
                else
                {
                    asyncResponse.Status = AsyncMethodState.Passed;
                }
            }
            catch (WebException we)
            {
                HttpWebResponse response = (HttpWebResponse)we.Response;
                if (response == null)
                {
                    asyncResponse.StatusDescription = string.Format(CultureInfo.InvariantCulture,
                                                                    "{0}{1}",
                                                                    asyncResponse.StatusDescription,
                                                                    we.Message);
                    if (we.InnerException != null)
                    {
                        asyncResponse.StatusDescription = string.Format(CultureInfo.InvariantCulture,
                                                                        "{0}\n{1}",
                                                                        asyncResponse.StatusDescription,
                                                                        we.InnerException.Message);
                    }
                }
                else
                {
                    asyncResponse.StatusDescription = string.Format(CultureInfo.InvariantCulture,
                                                                    "{0}WebException: {1}",
                                                                    asyncResponse.StatusDescription,
                                                                    response.StatusDescription);
                }

                asyncResponse.Status = AsyncMethodState.Failed;
                asyncResponse.Error  = we;
            }
            catch (Exception ex)
            {
                asyncResponse.StatusDescription = ex.Message;
                if (ex.InnerException != null)
                {
                    asyncResponse.StatusDescription = string.Format(CultureInfo.InvariantCulture,
                                                                    "{0}\n{1}",
                                                                    asyncResponse.StatusDescription,
                                                                    ex.InnerException.Message);
                }

                asyncResponse.Status = AsyncMethodState.Failed;
                asyncResponse.Error  = ex;
            }

            input.Callback(asyncResponse);
        }
Beispiel #27
0
    public void runNetLoop()
    {
        ManualResetEvent http_response_sync = new ManualResetEvent(false);
        HttpWebResponse resp = null;

        int registeredHandle = 0;
        try
        {
            conn = HttpWebRequest.Create(url);//todomt (HttpConnection)Connector.open(url);
            //System.Net.ServicePointManager.Expect100Continue = false;

            if (method == 0) conn.Method = "GET";
            else conn.Method = "POST";

            if (updateTime != null && updateTime.Trim().Length > 0) {
                conn.Headers["IfModifiedSince"] = updateTime;
            }

            registeredHandle = CRunTime.registerObject(conn);

        }
        catch (Exception e)
        {
            quit = true;
            Logger.log(e.ToString());
            UIWorker.addUIEventLog("Async Net : Exception opening URL " + e);
        }

        int handle = registeredHandle;

        UIWorker.addUIEventValid(c_do_async_connect_cb, handle, cb_addr, context, 0, false, this);
        if (quit) return;

        while (!quit)
        {
            lock (conn)
            {
                if (!do_read)
                {
                    try
                    {
                        Monitor.Wait(conn);
                    }
                    catch (SynchronizationLockException e)
                    {
                    }
                    if (quit) return;
                    if (!do_read) continue;
                }
            }

            try
            {
                if (Stream == null)
                {
                    resp = null;
                    Exception exp = null;
                    try
                    {
                        http_response_sync.Reset();
                        conn.BeginGetResponse(delegate(IAsyncResult result)
                        {
                            try
                            {
                                Logger.log("downloading " + conn.RequestUri);
                                resp = (HttpWebResponse)conn.EndGetResponse(result);
                                http_response_sync.Set();
                            }
                            catch (Exception we)
                            {
                                resp = null;
                                exp = we;
                                http_response_sync.Set();
                            }
                        }, null);
                    }
                    catch (Exception ioe)
                    {
                        resp = null;
                        exp = ioe;
                        http_response_sync.Set();
                    }

                    http_response_sync.WaitOne();

                    if (resp != null)
                    {
                        Stream = resp.GetResponseStream();
                        int status = (int)resp.StatusCode;
                        long data_size = resp.ContentLength;
                        string lastModifiedStr = resp.Headers["Last-Modified"];
                        //Logger.log("Java header, s is " + lastModifiedStr);

                        /*
                         * We need to send c a complete header string, so we fake it by creating the
                         * res string. More header fields can be added later on besides the content length and last-modified
                         *
                         */
                        string res = "HTTP/1.1 " + status + " OK\r\nContent-Length: " + data_size + "\r\n";
                        if (lastModifiedStr != null)
                            res += "Last-Modified:" + lastModifiedStr + "\r\n\r\n";
                        else
                            res += "\r\n";

                        buffer = new byte[4096];
                        byte[] res_bytes = Syscalls.StringToAscii(res);
                        res_bytes.CopyTo(buffer, 0);
                        buffer_len = res_bytes.Length;
                        buffer_cur_ptr = 0;
                    }
                    else
                    {
                        UIWorker.addUIEventLog("Exception in async net read: " + exp);
                        eof = true;
                        quit = true;
                        ////buffer = new byte[4096];
                        //string res = "HTTP/1.1 404 Not Found\r\n";
                        ///*byte[] res_bytes*/buffer = Syscalls.StringToAscii(res);
                        ////res_bytes.CopyTo(buffer, 0);
                        //buffer_len = /*res_bytes.Length;*/buffer.Length;
                        //buffer_cur_ptr = 0;
                        //do_read = false;
                    }
                }
                else
                {
                    if (buffer_cur_ptr == buffer_len)
                    {
                        buffer_len = Stream.Read(buffer, 0, buffer.Length);
                        if (buffer_len == -1)
                        {
                            eof = true;
                            Stream.Dispose();
                            resp.Dispose();
                        }
                        buffer_cur_ptr = 0;
                    }
                }
            }
            catch (Exception e)
            {
                UIWorker.addUIEventLog("Exception in async net read: " + e);
                eof = true;
                quit = true;
            }
            lock (conn)
            {
                do_read = false;
            }

            // Call read CB
            if (is_valid) UIWorker.addUIEventValid(c_input_ready_cb, input_id, 0, 0, 0, false, this);

        }
    }
Beispiel #28
0
 protected virtual WebResponse GetWebResponse(WebRequest request,
                                              IAsyncResult result)
 {
     return(request.EndGetResponse(result));
 }
        /// <summary>
        /// Uploads a file by making an HTTP POST request to the specified MediaWiki API endpoint.
        /// </summary>
        /// <param name="wiki">The <see cref="Wiki"/> to contact.</param>
        /// <param name="query">A dictionary of key-value pairs that represent the request parameters.</param>
        /// <param name="file">The file to upload, as a byte array of binary data.</param>
        /// <param name="fileName">The name of the file to upload.</param>
        /// <param name="fileParamName">The name (key) of the POST parameter whose value is the file data.</param>
        /// <param name="onSuccess">A function that will be called when the request is successful.
        /// The function is passed the XML response as its only parameter.</param>
        /// <param name="onError">A function that will be called when the request fails.
        /// The function is passed the error message string as its only parameter.</param>
        public static void UploadFile(Wiki wiki, StringDictionary query, byte[] file, string fileName, //string fileMimeType,
                                      string fileParamName, MorebitsDotNetPostSuccess onSuccess, MorebitsDotNetError onError)
        {
            // thanks to http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx

            query.Add("format", "xml");

            WebRequest req = HttpWebRequest.Create(GetApiUri(wiki));

            ((HttpWebRequest)req).UserAgent = UserAgent;
            req.Method = "POST";

            LoginInfo session = LoginSessions[wiki];

            if (session.CookieJar == null)
            {
                session.CookieJar = new CookieContainer();
            }
            ((HttpWebRequest)req).CookieContainer = session.CookieJar;

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);

            req.ContentType = "multipart/form-data; boundary=" + boundary;

            req.BeginGetRequestStream(delegate(IAsyncResult innerResult)
            {
                Stream stream = req.EndGetRequestStream(innerResult);

                foreach (DictionaryEntry e in query)
                {
                    string item = String.Format(CultureInfo.InvariantCulture,
                                                "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n{2}\r\n",
                                                boundary, e.Key.ToString(), e.Value.ToString());
                    byte[] bytes = Encoding.UTF8.GetBytes(item);
                    stream.Write(bytes, 0, bytes.Length);
                }

                if (file != null)
                {
                    string header = String.Format(CultureInfo.InvariantCulture,
                                                  "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                                                  boundary, fileParamName, fileName, "text/plain; charset=UTF-8"); // last param was |fileMimeType|
                    byte[] headerbytes = Encoding.UTF8.GetBytes(header);
                    stream.Write(headerbytes, 0, headerbytes.Length);

                    stream.Write(file, 0, file.Length);

                    byte[] newline = Encoding.UTF8.GetBytes("\r\n");
                    stream.Write(newline, 0, newline.Length);
                }
                byte[] endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");
                stream.Write(endBytes, 0, endBytes.Length);
                stream.Close();
            }, null);

            IAsyncResult result = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult innerResult)
            {
                WebResponse resp = null;
                try
                {
                    resp = req.EndGetResponse(innerResult);
                }
                catch (WebException e)
                {
                    onError(Localization.GetString("MorebitsDotNet_NetRequestFailure") + "\n\n" + e.Message);
                    return;
                }

                XmlDocument doc = new XmlDocument();
                doc.Load(resp.GetResponseStream());

#if REQUEST_LOG
                // simple request logging; doesn't include request body, so it should be used in conjunction with a debug session
                System.IO.File.AppendAllText("RequestLog.txt", "====\r\n\r\n" + req.RequestUri + "\r\n\r\nREQUEST HEADERS:\r\n" + req.Headers + "\r\n\r\nRESPONSE HEADERS:\r\n" + resp.Headers);
#endif

                XmlNodeList list = doc.GetElementsByTagName("error");
                if (list.Count == 0)
                {
                    onSuccess(doc);
                }
                else
                {
                    onError(Localization.GetString("MorebitsDotNet_ApiError") + "\n\n" + list[0].Attributes["info"].Value);
                }
            }), null);

            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), req, UploadTimeout, true);
        }
Beispiel #30
0
            protected void RespCallback(IAsyncResult ar)
            {
                int           result;
                ResultHandler rh = (ResultHandler)ar.AsyncState;

                try
                {
                    mResponse = mRequest.EndGetResponse(ar);
                    mStream   = mResponse.GetResponseStream();
                    if (mResponse is HttpWebResponse)
                    {
                        result = (int)((HttpWebResponse)mResponse).StatusCode;
                    }
                    else
                    {
                        result = 1;
                    }
                }
                catch (WebException e)
                {
                    if (e.Response != null)
                    {
                        mResponse = e.Response;
                        mStream   = mResponse.GetResponseStream();
                    }
                    switch (e.Status)
                    {
                    case WebExceptionStatus.ProtocolError:
                        if (e.Response is HttpWebResponse)
                        {
                            result = (int)((HttpWebResponse)mResponse).StatusCode;
                        }
                        else
                        {
                            result = MoSync.Constants.CONNERR_GENERIC;
                        }
                        break;

                    case WebExceptionStatus.NameResolutionFailure:
                    case WebExceptionStatus.ProxyNameResolutionFailure:
                        result = MoSync.Constants.CONNERR_DNS;
                        break;

                    case WebExceptionStatus.ConnectionClosed:
                        result = MoSync.Constants.CONNERR_CLOSED;
                        break;

                    case WebExceptionStatus.RequestCanceled:
                        result = MoSync.Constants.CONNERR_CANCELED;
                        break;

                    case WebExceptionStatus.SecureChannelFailure:
                    case WebExceptionStatus.TrustFailure:
                        result = MoSync.Constants.CONNERR_SSL;
                        break;

                    case WebExceptionStatus.ServerProtocolViolation:
                        result = MoSync.Constants.CONNERR_PROTOCOL;
                        break;

                    default:
                        result = MoSync.Constants.CONNERR_GENERIC;
                        break;
                    }
                }
                rh(mHandle, MoSync.Constants.CONNOP_CONNECT, result);
            }
Beispiel #31
0
        public static void IoThread()
        {
            ThreadPool.SetMinThreads(12, 12);
            ThreadPool.SetMaxThreads(12, 12);

            ManualResetEvent waitHandle = new ManualResetEvent(false);

            Stopwatch watch = new Stopwatch();

            watch.Start();

            WebRequest request = HttpWebRequest.Create("http://www.hao123.com/");

            request.BeginGetResponse(ar =>
            {
                var response = request.EndGetResponse(ar);
                Console.WriteLine(watch.Elapsed + ": Response Get");
            }, null);

            WebRequest request1 = HttpWebRequest.Create("http://www.baidu.com/");

            request1.BeginGetResponse(ar =>
            {
                var response1 = request1.EndGetResponse(ar);
                Console.WriteLine(watch.Elapsed + ": Response Get1");
            }, null);


            WebRequest request2 = HttpWebRequest.Create("http://www.baidu.com/");

            request2.BeginGetResponse(ar =>
            {
                var response2 = request2.EndGetResponse(ar);
                Console.WriteLine(watch.Elapsed + ": Response Get2");
            }, null);

            //Thread.Sleep(1000);
            ////request1.Abort();
            //RequestCachePolicy policy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
            //WebRequest request3 = HttpWebRequest.Create("http://www.baidu.com/");
            //request3.CachePolicy = policy;
            //request3.BeginGetResponse(ar =>
            //{
            //    var response3 = request3.EndGetResponse(ar);
            //    Console.WriteLine(watch.Elapsed + ": Response Get3");

            //}, null);

            ////request3.
            ////Thread.Sleep(1000);
            ////request3.Abort();
            //WebRequest request4 = HttpWebRequest.Create("http://www.baidu.com/");
            //request4.BeginGetResponse(ar =>
            //{
            //    var response4 = request4.EndGetResponse(ar);
            //    Console.WriteLine(watch.Elapsed + ": Response Get4");

            //}, null);

            try
            {
                WebRequest request5 = WebRequest.Create("http://www.baidu.com/");
                //request5.Timeout = 5000;
                var response5 = request5.GetResponse();
            }
            catch (Exception e)
            {
                string a = "";
            }


            for (int i = 0; i < 10; i++)
            {
                ThreadPool.QueueUserWorkItem(index =>
                {
                    Console.WriteLine(String.Format("{0}: Task {1} started", watch.Elapsed, index));
                    waitHandle.WaitOne();
                }, i);
            }

            waitHandle.WaitOne();
        }