/// <summary>
        /// 获取远程接口数据-字符串(Utf8)
        /// </summary>
        /// <param name="target">目标接口</param>
        /// <returns>字符结果集</returns>
        public static string DownLoadRemoteUtf8Data(string target)
        {
            string responseData;

            try
            {
                HttpWebRequest Request = System.Net.WebRequest.Create(target) as HttpWebRequest;
                Request.Method = "Get";
                //设置超时时间
                Request.Timeout          = 10000;
                Request.ReadWriteTimeout = 10000;
                //设置缓存
                RequestCachePolicy policy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);
                Request.CachePolicy = policy;

                using (StreamReader responseReader = new StreamReader(Request.GetResponse().GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    responseData = responseReader.ReadToEnd();
                }
            }
            catch
            {
                responseData = string.Empty;
            }
            return(responseData);
        }
Esempio n. 2
0
        /// <summary>
        /// Helper Method to read contents of a web page, in this case it is
        /// used to read the XML from the web page
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static string readHtmlPage(string url)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    RequestCachePolicy policy;
                    if (url.Contains("GetSeries.php?seriesname"))
                    {
                        policy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);
                    }
                    else
                    {
                        policy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
                    }
                    wc.CachePolicy = policy;

                    return(wc.DownloadString(url));
                }
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Load just the header line
        /// </summary>
        /// <param name="URIDataFilename"></param>
        /// <param name="Headers"></param>
        public void LoadHeaderLine(string URIDataFilename, out string[] Headers)
        {
            string line = "[start of file]";

            using (System.Net.WebClient webClient = new System.Net.WebClient())
            {
                RequestCachePolicy policy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
                webClient.CachePolicy = policy;
                try
                {
                    using (System.IO.Stream stream = webClient.OpenRead(URIDataFilename))
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            line    = reader.ReadLine(); //read the header line
                            Headers = ParseCSVLine(line);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Headers = null;
                }
            }
        }
Esempio n. 4
0
        // Constructors

        static WebRequest()
        {
#if MONOTOUCH
            AddPrefix("http", typeof(HttpRequestCreator));
            AddPrefix("https", typeof(HttpRequestCreator));
            AddPrefix("file", typeof(FileWebRequestCreator));
            AddPrefix("ftp", typeof(FtpRequestCreator));
#else
        #if NET_2_0
            defaultCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
        #endif
#if NET_2_0 && CONFIGURATION_DEP
            object cfg = ConfigurationManager.GetSection("system.net/webRequestModules");
            WebRequestModulesSection s = cfg as WebRequestModulesSection;
            if (s != null)
            {
                foreach (WebRequestModuleElement el in
                         s.WebRequestModules)
                {
                    AddPrefix(el.Prefix, el.Type);
                }
                return;
            }
#endif
            ConfigurationSettings.GetConfig("system.net/webRequestModules");
#endif
        }
Esempio n. 5
0
 public static void CachePolicy_Roundtrips()
 {
     var wc = new WebClient();
     var c = new RequestCachePolicy(RequestCacheLevel.BypassCache);
     wc.CachePolicy = c;
     Assert.Same(c, wc.CachePolicy);
 }
Esempio n. 6
0
        private static void RegisterIoc()
        {
#if DEBUG
            var cachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);
#else
            var cachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);
#endif

            DependencyInjection.Register <AzureConfiguration>();
            DependencyInjection.Register <GitHubConfiguration>();
            DependencyInjection.Register <IRestClient>(() => new RestClient()
            {
                CachePolicy = cachePolicy
            });

            DependencyInjection.Register <IRepo <Activity>, ActivityRepo>();
            DependencyInjection.Register <IRepo <Album>, AlbumRepo>();
            DependencyInjection.Register <IRepo <Email>, EmailRepo>();
            DependencyInjection.Register <IRepo <Sponsor>, SponsorRepo>();

            DependencyInjection.RegisterSingleton <IAlertService, AlertService>();
            DependencyInjection.RegisterSingleton(() => GetNavigationService());
            DependencyInjection.Register <AboutViewModel>();
            DependencyInjection.Register <ActivityEditViewModel>();
            DependencyInjection.Register <ActivityListViewModel>();
            DependencyInjection.Register <AlbumListViewModel>();
            DependencyInjection.Register <ContactUsViewModel>();
            DependencyInjection.Register <MainMenuMasterViewModel>();
            DependencyInjection.Register <MotDeMDoyonViewModel>();
            DependencyInjection.Register <SocialViewModel>();
            DependencyInjection.Register <SponsorListViewModel>();

            DependencyInjection.Verify();
        }
        private async Task <Stream> GetNonFileStreamAsync(Uri uri, ICredentials credentials, IWebProxy proxy,
                                                          RequestCachePolicy cachePolicy)
        {
            WebRequest req = WebRequest.Create(uri);

            if (credentials != null)
            {
                req.Credentials = credentials;
            }
            if (proxy != null)
            {
                req.Proxy = proxy;
            }
            if (cachePolicy != null)
            {
                req.CachePolicy = cachePolicy;
            }

            using (WebResponse resp = await req.GetResponseAsync().ConfigureAwait(false))
                using (Stream respStream = resp.GetResponseStream())
                {
                    var result = new MemoryStream();
                    await respStream.CopyToAsync(result).ConfigureAwait(false);

                    result.Position = 0;
                    return(result);
                }
        }
Esempio n. 8
0
        // Constructors

        static WebRequest()
        {
#if NET_2_1
            IWebRequestCreate http = new HttpRequestCreator();
            RegisterPrefix("http", http);
            RegisterPrefix("https", http);
        #if MOBILE
            RegisterPrefix("file", new FileWebRequestCreator());
            RegisterPrefix("ftp", new FtpRequestCreator());
        #endif
#else
            defaultCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
        #if CONFIGURATION_DEP
            object cfg = ConfigurationManager.GetSection("system.net/webRequestModules");
            WebRequestModulesSection s = cfg as WebRequestModulesSection;
            if (s != null)
            {
                foreach (WebRequestModuleElement el in
                         s.WebRequestModules)
                {
                    AddPrefix(el.Prefix, el.Type);
                }
                return;
            }
        #endif
            ConfigurationSettings.GetConfig("system.net/webRequestModules");
#endif
        }
Esempio n. 9
0
        public static void SetImage([NotNull] this Image image, [NotNull, Localizable(false)] string imagePath)
        {
            Assert.ArgumentNotNull(image, nameof(image));
            Assert.ArgumentNotNull(imagePath, nameof(imagePath));

            if (!imagePath.StartsWith(@"/") && !imagePath.StartsWith(@"http"))
            {
                BitmapImage result;
                try
                {
                    result = new BitmapImage();

                    result.BeginInit();
                    result.UriSource = new Uri("pack://application:,,,/Sitecore.Rocks;component/" + imagePath);
                    result.EndInit();
                }
                catch (IOException ex)
                {
                    AppHost.Output.LogException(ex);
                    result = Icon.Empty.GetSource();
                }

                image.Source = result;
            }
            else
            {
                var policy = new RequestCachePolicy(RequestCacheLevel.Default);
                image.Source = new BitmapImage(new Uri(imagePath), policy);
            }
        }
Esempio n. 10
0
        public static void SetImage([NotNull] this Image image, [NotNull] Site site, [NotNull] string imagePath)
        {
            Assert.ArgumentNotNull(image, nameof(image));
            Assert.ArgumentNotNull(site, nameof(site));
            Assert.ArgumentNotNull(imagePath, nameof(imagePath));

            if (!imagePath.StartsWith(@"/") && !imagePath.StartsWith(@"http"))
            {
                SetImage(image, imagePath);
            }
            else
            {
                var server = site.GetHost();

                var url = server + imagePath;

                if (url.IndexOf(@"~/icon", StringComparison.InvariantCultureIgnoreCase) >= 0)
                {
                    url += @".aspx";
                }

                var policy = new RequestCachePolicy(RequestCacheLevel.Default);
                try
                {
                    image.Source = new BitmapImage(new Uri(url), policy);
                }
                catch (Exception ex)
                {
                    AppHost.Output.LogException(ex);
                    image.Source = Icon.Empty.GetSource();
                }
            }
        }
Esempio n. 11
0
        public RestRequest(string resource)
        {
            PathParams = new PathParams();
            Resource   = resource;

            Headers = new WebHeaderCollection
            {
                { HttpRequestHeader.CacheControl, "no-store, must-revalidate" },
                { HttpRequestHeader.AcceptEncoding, "gzip" }
            };

            Advanced                     = new AdvancedRestRequest(this);
            AllowAutoRedirect            = true;
            AllowWriteStreamBuffering    = true;
            AuthenticationLevel          = AuthenticationLevel.MutualAuthRequested;
            AutomaticDecompression       = DecompressionMethods.None;
            CachePolicy                  = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            ClientCertificates           = new X509Certificate2Collection();
            ContentLength                = 0;
            ContentType                  = ContentType.TXT;
            Encoding                     = Encoding.UTF8;
            HttpMethod                   = HttpMethod.GET;
            ImpersonationLevel           = TokenImpersonationLevel.Delegation;
            KeepAlive                    = true;
            MaximumAutomaticRedirections = 50;
            MaximumResponseHeadersLength = 64;
            Pipelined                    = true;
            ProtocolVersion              = new Version(1, 1);
            ReadWriteTimeout             = 300000;
            QueryString                  = new QueryString();
            Timeout = GlobalTimeout;
        }
        private void RenderIcons([NotNull] Image image, [Localizable(false), NotNull] string imageName)
        {
            Debug.ArgumentNotNull(image, nameof(image));
            Debug.ArgumentNotNull(imageName, nameof(imageName));

            var server = AppHost.Settings.Options.PluginRespositoryUrl;

            if (!server.StartsWith(@"http://"))
            {
                server = @"http://" + server;
            }

            var path = string.Format(@"{0}/icons/icons_{1}.png", server, imageName);

            var policy = new RequestCachePolicy(RequestCacheLevel.Default);

            try
            {
                image.Source = new BitmapImage(new Uri(path), policy);
            }
            catch (OutOfMemoryException)
            {
                AppHost.MessageBox("Ouch, the image is too big to fit inside your computer.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                Image.Source = Data.Icon.Empty.GetSource();
            }

            images[imageName] = image;
        }
Esempio n. 13
0
        private Stream GetNonFileStream(Uri uri, ICredentials credentials, IWebProxy proxy,
                                        RequestCachePolicy cachePolicy)
        {
            WebRequest req = WebRequest.Create(uri);

            if (credentials != null)
            {
                req.Credentials = credentials;
            }
            if (proxy != null)
            {
                req.Proxy = proxy;
            }
            if (cachePolicy != null)
            {
                req.CachePolicy = cachePolicy;
            }

            using (WebResponse resp = req.GetResponse())
                using (Stream respStream = resp.GetResponseStream())
                {
                    var result = new MemoryStream();
                    respStream.CopyTo(result);
                    result.Position = 0;
                    return(result);
                }
        }
Esempio n. 14
0
 private void InternalSetCachePolicy(RequestCachePolicy policy)
 {
     if ((((this.m_CacheBinding != null) && (this.m_CacheBinding.Cache != null)) && ((this.m_CacheBinding.Validator != null) && (this.CacheProtocol == null))) && ((policy != null) && (policy.Level != RequestCacheLevel.BypassCache)))
     {
         this.CacheProtocol = new RequestCacheProtocol(this.m_CacheBinding.Cache, this.m_CacheBinding.Validator.CreateValidator());
     }
     this.m_CachePolicy = policy;
 }
Esempio n. 15
0
 public INoneBodyBuilder CachePolicy(RequestCachePolicy policy)
 {
     if (policy != null)
     {
         _cachePolicy = policy;
     }
     return(this);
 }
        void LoadImage(object source)
        {
            Uri uriSource             = (Uri)source;
            RequestCachePolicy policy =
                new RequestCachePolicy(RequestCacheLevel.Revalidate);

            BeginInvoke(new Action(() => { ImageSource = new BitmapImage(uriSource, policy); }));
        }
Esempio n. 17
0
        private static void DownLoadASheet(string sAddr, string sFileName)
        {
            RequestCachePolicy policy = new RequestCachePolicy(RequestCacheLevel.Reload);

            string address = sAddr;

            //"http://localhost/Sheets/" + sFileName + ".xls";

            System.Threading.AutoResetEvent waiter = new System.Threading.AutoResetEvent(false);
            Uri uri = new Uri(address);

            try
            {
                WebClient wc = new WebClient();
                wc.Proxy = null;
                wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
                wc.CachePolicy = policy;


                wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(wcDownLoadDone);
                wc.DownloadDataCompleted   += new DownloadDataCompletedEventHandler(wcDownLoadDone);
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcCallbackDown);

                wc.DownloadFileAsync(uri, sFileName);
                Console.Write("DownLoading with {0}", sFileName);
                while (wc.IsBusy)
                {
                    waiter.WaitOne(100);
                    Debug.Assert(wc.IsBusy, "Still Busy");
                }
                try
                {
                    Debug.Print("Done");
                }
                catch (Exception ex)
                {
                    throw ex;
                }


                Console.WriteLine("Done with {0}", sFileName);
                // Got the File
                // Download the Files
            }

            catch (WebException ex)
            {
                Console.WriteLine("  Download Error -" + ex.Message);
                throw ex;
                //   Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }
Esempio n. 18
0
 public TimeoutWebClient(int timeout, IPEndPoint ip)
     : base()
 {
     m_OutIPEndPoint = ip;
     Timeout         = timeout;
     CachePolicy     = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
     Encoding        = System.Text.Encoding.UTF8;
     Proxy           = null;
 }
Esempio n. 19
0
        public static string DownloadHead(Uri absoluteUri, Options _options)
        {
            try
            {
                if (_headPool.ContainsKey(absoluteUri))
                {
                    return(_headPool[absoluteUri]);
                }

                else
                {
                    Trace.WriteLine($"Reading head from Url {absoluteUri}");

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(absoluteUri);
                    request.Method = @"HEAD";

                    RequestCachePolicy cp = new RequestCachePolicy(
                        RequestCacheLevel.BypassCache);
                    request.CachePolicy = cp;

                    request.Proxy = _options.ProxyAddress;

                    using (HttpWebResponse resp =
                               (HttpWebResponse)request.GetResponse())
                    {
                        _headPool[absoluteUri] = resp.ContentType;
                        return(resp.ContentType);
                    }
                }
            }
            catch (Exception ex)
            {
                WebException x = (WebException)ex;

                if (x.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse resp =
                        (HttpWebResponse)x.Response;

                    if (resp.StatusCode == HttpStatusCode.NotFound ||
                        resp.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        Trace.WriteLine($"Ignoring web exception: {x.Message}.");

                        return(null);
                    }
                    else
                    {
                        throw;
                    }
                }
                else
                {
                    throw;
                }
            }
        }
Esempio n. 20
0
        private async Task <Stream> GetNonFileStreamAsync(Uri uri, ICredentials credentials, IWebProxy proxy,
                                                          RequestCachePolicy cachePolicy)
        {
            WebRequest req = WebRequest.Create(uri);

            if (credentials != null)
            {
                req.Credentials = credentials;
            }
            if (proxy != null)
            {
                req.Proxy = proxy;
            }
            if (cachePolicy != null)
            {
                req.CachePolicy = cachePolicy;
            }

            WebResponse resp = await Task <WebResponse> .Factory.FromAsync(req.BeginGetResponse, req.EndGetResponse, null).ConfigureAwait(false);

            HttpWebRequest webReq = req as HttpWebRequest;

            if (webReq != null)
            {
                lock (this) {
                    if (connections == null)
                    {
                        connections = new Hashtable();
                    }
                    OpenedHost openedHost = (OpenedHost)connections[webReq.Address.Host];
                    if (openedHost == null)
                    {
                        openedHost = new OpenedHost();
                    }

                    if (openedHost.nonCachedConnectionsCount < webReq.ServicePoint.ConnectionLimit - 1)
                    {
                        // we are not close to connection limit -> don't cache the stream
                        if (openedHost.nonCachedConnectionsCount == 0)
                        {
                            connections.Add(webReq.Address.Host, openedHost);
                        }
                        openedHost.nonCachedConnectionsCount++;
                        return(new XmlRegisteredNonCachedStream(resp.GetResponseStream(), this, webReq.Address.Host));
                    }
                    else
                    {
                        // cache the stream and save the connection for the next request
                        return(new XmlCachedStream(resp.ResponseUri, resp.GetResponseStream()));
                    }
                }
            }
            else
            {
                return(resp.GetResponseStream());
            }
        }
Esempio n. 21
0
        public MyWebClient(IPEndPoint outIp)
        {
            if (outIp == null)
            {
                throw new ArgumentNullException("outIp");
            }

            m_OutIPEndPoint = outIp;
            CachePolicy     = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
            Proxy           = null;
        }
Esempio n. 22
0
 public WebRequestChannel()
 {
     // Set HWR default values
     this.allowPipelining                      = true;
     this.authenticationLevel                  = AuthenticationLevel.MutualAuthRequested;
     this.cachePolicy                          = WebRequest.DefaultCachePolicy;
     this.impersonationLevel                   = TokenImpersonationLevel.Delegation;
     this.maxResponseHeadersLength             = HttpWebRequest.DefaultMaximumResponseHeadersLength;
     this.readWriteTimeout                     = 5 * 60 * 1000; // 5 minutes
     this.unsafeAuthenticatedConnectionSharing = false;
 }
Esempio n. 23
0
 internal Stream GetStream(Uri uri, ICredentials credentials, IWebProxy proxy,
                           RequestCachePolicy cachePolicy)
 {
     if (uri.Scheme == "file")
     {
         return(new FileStream(uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 1));
     }
     else
     {
         return(GetNonFileStream(uri, credentials, proxy, cachePolicy));
     }
 }
Esempio n. 24
0
 public WebRequestHandler()
 {
     allowPipelining                      = true;
     authenticationLevel                  = AuthenticationLevel.MutualAuthRequested;
     cachePolicy                          = System.Net.WebRequest.DefaultCachePolicy;
     continueTimeout                      = TimeSpan.FromMilliseconds(350);
     impersonationLevel                   = TokenImpersonationLevel.Delegation;
     maxResponseHeadersLength             = HttpWebRequest.DefaultMaximumResponseHeadersLength;
     readWriteTimeout                     = 300000;
     serverCertificateValidationCallback  = null;
     unsafeAuthenticatedConnectionSharing = false;
 }
Esempio n. 25
0
 internal Task <Stream> GetStreamAsync(Uri uri, ICredentials credentials, IWebProxy proxy,
                                       RequestCachePolicy cachePolicy)
 {
     if (uri.Scheme == "file")
     {
         return(Task.Run <Stream>(() => { return new FileStream(uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 1, true); }));
     }
     else
     {
         return(GetNonFileStreamAsync(uri, credentials, proxy, cachePolicy));
     }
 }
Esempio n. 26
0
        public static void DownloadBinary(Uri absoluteUri, out byte[] binaryContent, Options option)
        {
            Trace.WriteLine($"Reading Content from URL {absoluteUri}");

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(absoluteUri);
                request.Proxy = option.ProxyAddress;

                RequestCachePolicy cp = new RequestCachePolicy(RequestCacheLevel.BypassCache);

                request.CachePolicy = cp;

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    using (Stream stream = response.GetResponseStream())
                        using (MemoryStream memstream = new MemoryStream())
                        {
                            int    blockSize   = 16384;
                            byte[] blockBuffer = new byte[blockSize];
                            int    read;

                            while ((read = stream.Read(blockBuffer, 0, blockSize)) > 0)
                            {
                                memstream.Write(blockBuffer, 0, read);
                            }

                            memstream.Seek(0, SeekOrigin.Begin);
                            binaryContent = memstream.GetBuffer();
                        }
            }
            catch (Exception ex)
            {
                WebException x = (WebException)ex;
                if (x.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse resp = (HttpWebResponse)x.Response;

                    if (resp.StatusCode == HttpStatusCode.NotFound || resp.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        Trace.WriteLine($"Ignoring web exception {x.Message}");
                        binaryContent = null;
                    }
                    else
                    {
                        throw;
                    }
                }
                else
                {
                    throw;
                }
            }
        }
        public void HttpCachePolicy_Is_Set_On_Webrequest()
        {
            var requestCachePoliciy = new RequestCachePolicy();

            var factory = this.CreateWebRequestFactory(new ApiConfiguration(string.Empty)
            {
                RequestCachePolicy = requestCachePoliciy
            });

            var request = factory.Create(new Uri("http://asdf/"));

            Assert.AreSame(requestCachePoliciy, request.CachePolicy);
        }
Esempio n. 28
0
        /// <summary>
        /// Construct a BitmapImage with the given Uri and RequestCachePolicy
        /// </summary>
        /// <param name="uriSource">Uri of the source Bitmap</param>
        /// <param name="uriCachePolicy">Optional web request cache policy</param>
        public BitmapImage(Uri uriSource, RequestCachePolicy uriCachePolicy)
            : base(true) // Use base class virtuals
        {
            if (uriSource == null)
            {
                throw new ArgumentNullException("uriSource");
            }

            BeginInit();
            UriSource      = uriSource;
            UriCachePolicy = uriCachePolicy;
            EndInit();
        }
Esempio n. 29
0
        //</snippet12>

        //<snippet13>
        public static WebResponse GetResponseFromCache(Uri uri)
        {
            RequestCachePolicy policy =
                new  RequestCachePolicy(RequestCacheLevel.CacheOnly);
            WebRequest request = WebRequest.Create(uri);

            request.CachePolicy = policy;
            WebResponse response = request.GetResponse();

            Console.WriteLine("Policy level is {0}.", policy.Level.ToString());
            Console.WriteLine("Is the response from the cache? {0}", response.IsFromCache);
            return(response);
        }
Esempio n. 30
0
        //</snippet14>

        // <snippet15>
        public static WebResponse GetResponseFromServer2(Uri uri)
        {
            RequestCachePolicy policy =
                new  RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
            WebRequest request = WebRequest.Create(uri);

            WebRequest.DefaultCachePolicy = policy;
            WebResponse response = request.GetResponse();

            Console.WriteLine("Policy is {0}.", policy.ToString());
            Console.WriteLine("Is the response from the cache? {0}", response.IsFromCache);
            return(response);
        }