// Constructors static WebRequest () { #if NET_2_1 AddPrefix ("http", typeof (HttpRequestCreator)); AddPrefix ("https", typeof (HttpRequestCreator)); #if MOBILE AddPrefix ("file", typeof (FileWebRequestCreator)); AddPrefix ("ftp", typeof (FtpRequestCreator)); #endif #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 }
/// <summary> /// Upload new Media File by using V2 API /// </summary> /// <param name="SecretKey">Backlot Secret Key</param> /// <param name="APIKey">Backlot API Key</param> /// <param name="hs">File's Standard Metadata in Hashtable Format</param> /// <param name="file">Upload File Object</param> public static void NewMediaUploadStream(string SecretKey, string APIKey, string id, Stream inStream) { ArrayList resHS = new ArrayList(); string json = OoyalaAPI.getJSON(SecretKey, APIKey, string.Format(formatUploadURLs, id), null); resHS = (ArrayList)JSON.JsonDecode(json); foreach (string uploadurl in resHS) { System.Net.Cache.RequestCachePolicy requestCachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); HttpWebRequest request = HttpWebRequest.Create(uploadurl) as HttpWebRequest; request.CachePolicy = requestCachePolicy; request.Method = "PUT"; request.AllowWriteStreamBuffering = false; request.Timeout = UPLOAD_TIMEOUT; request.SendChunked = false; request.ContentLength = inStream.Length; var outStream = request.GetRequestStream(); byte[] b = new byte[1024]; int r; while ((r = inStream.Read(b, 0, b.Length)) > 0) { outStream.Write(b, 0, r); } outStream.Flush(); outStream.Close(); } }
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); } return this.GetNonFileStream(uri, credentials, proxy, cachePolicy); }
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); } }
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); }
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; }
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; }
/// <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(); }
/// <summary> /// Create BitmapFrame from the uri or stream /// </summary> internal static BitmapFrame CreateFromUriOrStream( Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy ) { // Create a decoder and return the first frame if (uri != null) { Debug.Assert((stream == null), "Both stream and uri are non-null"); BitmapDecoder decoder = BitmapDecoder.CreateFromUriOrStream( baseUri, uri, null, createOptions, cacheOption, uriCachePolicy, true ); if (decoder.Frames.Count == 0) { throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames), "uri"); } return decoder.Frames[0]; } else { Debug.Assert((stream != null), "Both stream and uri are null"); BitmapDecoder decoder = BitmapDecoder.Create( stream, createOptions, cacheOption ); if (decoder.Frames.Count == 0) { throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames), "stream"); } return decoder.Frames[0]; } }
public static string downloadSelfUpdater(Uri uri) { WebClient client = new WebClient(); RequestCachePolicy policy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); client.CachePolicy = policy; string fileName = Path.GetTempPath() + Path.GetFileName(uri.AbsolutePath); try { client.DownloadFile(uri, fileName); return fileName; } catch (Exception) { } return ""; }
internal void FetchRequest(System.Uri uri, WebRequest request) { this._Request = request; this._Policy = request.CachePolicy; this._Response = null; this._ResponseCount = 0; this._ValidationStatus = CacheValidationStatus.DoNotUseCache; this._CacheFreshnessStatus = System.Net.Cache.CacheFreshnessStatus.Undefined; this._CacheStream = null; this._CacheStreamOffset = 0L; this._CacheStreamLength = 0L; if (!uri.Equals(this._Uri)) { this._CacheKey = uri.GetParts(UriComponents.AbsoluteUri, UriFormat.Unescaped); } this._Uri = uri; }
private Stream GetNonFileStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy) { WebRequest request = WebRequest.Create(uri); if (credentials != null) { request.Credentials = credentials; } if (proxy != null) { request.Proxy = proxy; } if (cachePolicy != null) { request.CachePolicy = cachePolicy; } WebResponse response = request.GetResponse(); HttpWebRequest request2 = request as HttpWebRequest; if (request2 != null) { lock (this) { if (this.connections == null) { this.connections = new Hashtable(); } OpenedHost host = (OpenedHost) this.connections[request2.Address.Host]; if (host == null) { host = new OpenedHost(); } if (host.nonCachedConnectionsCount < (request2.ServicePoint.ConnectionLimit - 1)) { if (host.nonCachedConnectionsCount == 0) { this.connections.Add(request2.Address.Host, host); } host.nonCachedConnectionsCount++; return new XmlRegisteredNonCachedStream(response.GetResponseStream(), this, request2.Address.Host); } return new XmlCachedStream(response.ResponseUri, response.GetResponseStream()); } } return response.GetResponseStream(); }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Net.WebClient" /> class. /// </summary> public NexusWebClient(IAuthManager authManager) { _authManager = authManager; var os = OperatingSystem.Detect(); // Workaround: disable certificate cache on MacOSX. if (os == SupportedOperatingSystem.MacOSX) { CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true; } // Add a version number header of requests. var version = $"{Assembly.GetEntryAssembly().GetName().Version}-{os}"; Headers.Add("X-ParkitectNexusInstaller-Version", version); Headers.Add("user-agent", $"ParkitectNexus/{version}"); }
/*-------------- internal members -------------*/ // internal void FetchRequest(Uri uri, WebRequest request) { _Request = request; _Policy = request.CachePolicy; _Response = null; _ResponseCount = 0; _ValidationStatus = CacheValidationStatus.DoNotUseCache; _CacheFreshnessStatus = CacheFreshnessStatus.Undefined; _CacheStream = null; _CacheStreamOffset = 0L; _CacheStreamLength = 0L; if (!uri.Equals(_Uri)) { // it's changed from previous call _CacheKey = uri.GetParts(UriComponents.AbsoluteUri, UriFormat.Unescaped); } _Uri = uri; }
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(); } }
private Stream GetNonFileStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy) { HttpClient client = new HttpClient(); HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, uri); lock (this) { if (_connections == null) { _connections = new Hashtable(); } } HttpResponseMessage resp = client.SendAsync(req).GetAwaiter().GetResult(); Stream respStream = new MemoryStream(); resp.Content.CopyToAsync(respStream); return respStream; }
internal RequestCachingSectionInternal(RequestCachingSection section) { if (!section.DisableAllCaching) { this.defaultCachePolicy = new RequestCachePolicy(section.DefaultPolicyLevel); this.isPrivateCache = section.IsPrivateCache; this.unspecifiedMaximumAge = section.UnspecifiedMaximumAge; } else { this.disableAllCaching = true; } this.httpRequestCacheValidator = new HttpRequestCacheValidator(false, this.UnspecifiedMaximumAge); this.ftpRequestCacheValidator = new FtpRequestCacheValidator(false, this.UnspecifiedMaximumAge); this.defaultCache = new WinInetCache(this.IsPrivateCache, true, true); if (!section.DisableAllCaching) { HttpCachePolicyElement defaultHttpCachePolicy = section.DefaultHttpCachePolicy; if (defaultHttpCachePolicy.WasReadFromConfig) { if (defaultHttpCachePolicy.PolicyLevel == HttpRequestCacheLevel.Default) { HttpCacheAgeControl cacheAgeControl = (defaultHttpCachePolicy.MinimumFresh != TimeSpan.MinValue) ? HttpCacheAgeControl.MaxAgeAndMinFresh : HttpCacheAgeControl.MaxAgeAndMaxStale; this.defaultHttpCachePolicy = new HttpRequestCachePolicy(cacheAgeControl, defaultHttpCachePolicy.MaximumAge, (defaultHttpCachePolicy.MinimumFresh != TimeSpan.MinValue) ? defaultHttpCachePolicy.MinimumFresh : defaultHttpCachePolicy.MaximumStale); } else { this.defaultHttpCachePolicy = new HttpRequestCachePolicy(defaultHttpCachePolicy.PolicyLevel); } } FtpCachePolicyElement defaultFtpCachePolicy = section.DefaultFtpCachePolicy; if (defaultFtpCachePolicy.WasReadFromConfig) { this.defaultFtpCachePolicy = new RequestCachePolicy(defaultFtpCachePolicy.PolicyLevel); } } }
// Constructors static WebRequest () { if (Platform.IsMacOS) { #if MONOTOUCH Type type = Type.GetType ("MonoTouch.CoreFoundation.CFNetwork, monotouch"); #else Type type = Type.GetType ("MonoMac.CoreFoundation.CFNetwork, monomac"); #endif if (type != null) cfGetDefaultProxy = type.GetMethod ("GetDefaultProxy"); } #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 }
public List<GitHubRelease> GetReleases() { RequestCachePolicy cachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); using (WebClient wc = new WebClient { Proxy = Proxy, CachePolicy = cachePolicy }) { string response = wc.DownloadString(ReleasesURL); if (!string.IsNullOrEmpty(response)) { return JsonConvert.DeserializeObject<List<GitHubRelease>>(response); } } return null; }
public static void CachePolicy_Roundtrips() { var wc = new WebClient(); var c = new RequestCachePolicy(RequestCacheLevel.BypassCache); wc.CachePolicy = c; Assert.Same(c, wc.CachePolicy); }
public bool CheckUpdate() { UpdateInfo = new UpdateInfo(ReleaseChannel); UpdateInfo.CurrentVersion = ApplicationVersion; try { RequestCachePolicy cachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); using (WebClient wc = new WebClient { Proxy = Proxy, CachePolicy = cachePolicy }) using (MemoryStream ms = new MemoryStream(wc.DownloadData(URL))) using (XmlTextReader xml = new XmlTextReader(ms)) { XDocument xd = XDocument.Load(xml); if (xd != null) { string node; switch (ReleaseChannel) { default: case ReleaseChannelType.Stable: node = "Stable"; break; case ReleaseChannelType.Beta: node = "Beta|Stable"; break; case ReleaseChannelType.Dev: node = "Dev|Beta|Stable"; break; } string path = string.Format("Update/{0}/{1}", ApplicationName, node); XElement xe = xd.GetNode(path); if (xe != null) { UpdateInfo.LatestVersion = new Version(xe.GetValue("Version")); UpdateInfo.URL = xe.GetValue("URL"); string date = xe.GetValue("Date"); if (!string.IsNullOrEmpty(date)) { DateTime dateTime; if (DateTime.TryParse(date, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) { UpdateInfo.Date = dateTime; } } UpdateInfo.Summary = xe.GetValue("Summary"); if (UpdateInfo.IsUpdateRequired) { UpdateInfo.Status = UpdateStatus.UpdateRequired; if (!string.IsNullOrEmpty(UpdateInfo.Summary) && UpdateInfo.Summary.IsValidUrl()) { try { wc.Encoding = Encoding.UTF8; UpdateInfo.Summary = wc.DownloadString(UpdateInfo.Summary.Trim()); } catch (Exception ex) { DebugHelper.WriteException(ex); } } } else { UpdateInfo.Status = UpdateStatus.UpToDate; } return true; } } } } catch (Exception ex) { DebugHelper.WriteException(ex); } UpdateInfo.Status = UpdateStatus.UpdateCheckFailed; return false; }
/// <summary> /// Create a BitmapDecoder from a Uri with the specified BitmapCreateOptions and /// BitmapCacheOption /// </summary> /// <param name="bitmapUri">Uri to decode</param> /// <param name="createOptions">Bitmap Create Options</param> /// <param name="cacheOption">Bitmap Caching Option</param> /// <param name="uriCachePolicy">Optional web request cache policy</param> public static BitmapDecoder Create( Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy ) { if (bitmapUri == null) { throw new ArgumentNullException("bitmapUri"); } return CreateFromUriOrStream( null, bitmapUri, null, createOptions, cacheOption, uriCachePolicy, true ); }
// ------------------------------------------------------------------ /// <summary> /// Downloads the head. /// </summary> /// <param name="absoluteUri">The absolute URI.</param> /// <param name="options">The options.</param> /// <returns></returns> public static string DownloadHead( Uri absoluteUri, WebSiteDownloaderOptions options ) { try { if ( _headPool.ContainsKey( absoluteUri ) ) { return _headPool[absoluteUri]; } else { Debug.WriteLine( string.Format( @"Reading HEAD from URL '{0}'.", absoluteUri ) ); HttpWebRequest req = (HttpWebRequest)WebRequest.Create( absoluteUri ); req.Method = @"HEAD"; ApplyProxy( req, options ); RequestCachePolicy cp = new RequestCachePolicy( RequestCacheLevel.BypassCache ); req.CachePolicy = cp; using ( HttpWebResponse resp = (HttpWebResponse)req.GetResponse() ) { _headPool[absoluteUri] = resp.ContentType; return resp.ContentType; } } } catch ( WebException x ) { if ( x.Status == WebExceptionStatus.ProtocolError ) { HttpWebResponse resp = (HttpWebResponse)x.Response; if ( resp.StatusCode == HttpStatusCode.NotFound || resp.StatusCode == HttpStatusCode.InternalServerError ) { Trace.WriteLine( string.Format( @"Ignoring web exception: '{0}'.", x.Message ) ); return null; } else { try { throw; } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } } else { try { throw; } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } } return "Out OF Robot"; }
internal RequestCacheBinding(RequestCache requestCache, RequestCacheValidator cacheValidator, RequestCachePolicy policy) { this.m_RequestCache = requestCache; this.m_CacheValidator = cacheValidator; this.m_Policy = policy; }
internal RequestCacheBinding(RequestCache requestCache, RequestCacheValidator cacheValidator, RequestCachePolicy policy) { m_RequestCache = requestCache; m_CacheValidator = cacheValidator; m_Policy = policy; }
/// <summary> /// Internal method which does the actual work of getting the Mark data. /// </summary> private ReevooMarkData ObtainReevooMarkDataInternal(Parameters params_, String baseUri_) { var _builder = new UriBuilder (baseUri_); _builder.Query = params_.ToQueryString(); //Console.WriteLine ("URL: " + _builder.Uri); HttpWebRequest _req = (HttpWebRequest)WebRequest.Create (_builder.ToString ()); //Explicitly set the cache level. .NET Framework default is to always bypass the //cache and go straight to the server. RequestCacheLevel.Default will request cache-control //and age headers defined in RFC-2616. var _cachePolicy = new System.Net.Cache.RequestCachePolicy (RequestCacheLevel.Default); _req.CachePolicy = _cachePolicy; HttpWebResponse _res = null; String _content = String.Empty; try { //stream web content into a string try { _res = (HttpWebResponse)_req.GetResponse (); } catch (WebException e) { _res = (HttpWebResponse)e.Response; } if( _res.StatusCode == HttpStatusCode.OK){ using (var s = new StreamReader (_res.GetResponseStream ())) { _content = s.ReadToEnd (); } } else { _content = null; } } catch (Exception e_) { throw new ReevooException (e_); } return new ReevooMarkData { Content = _content, BestPrice = GetBestPrice (_res.Headers), ReviewCount = GetReviewCount (_res.Headers), ScoreCount = GetScoreCount (_res.Headers), OverallScore = GetOverallScore (_res.Headers), Sku = params_["sku"], Retailer = params_["trkref"], Params = params_, }; }
/// <summary> /// Upload new Media File by using V2 API /// </summary> /// <param name="SecretKey">Backlot Secret Key</param> /// <param name="APIKey">Backlot API Key</param> /// <param name="hs">File's Standard Metadata in Hashtable Format</param> /// <param name="file">Upload File Object</param> public static void NewMediaUploadStream(string SecretKey, string APIKey, string id, Stream inStream) { ArrayList resHS = new ArrayList(); string json = OoyalaAPI.getJSON(SecretKey, APIKey, string.Format(formatUploadURLs, id), null); resHS = (ArrayList)JSON.JsonDecode(json); foreach (string uploadurl in resHS) { System.Net.Cache.RequestCachePolicy requestCachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); HttpWebRequest request = HttpWebRequest.Create(uploadurl) as HttpWebRequest; request.CachePolicy = requestCachePolicy; request.Method = "PUT"; request.AllowWriteStreamBuffering = false; request.Timeout = UPLOAD_TIMEOUT; request.SendChunked = false; request.ContentLength = inStream.Length; var outStream = request.GetRequestStream(); byte[] b = new byte[1024]; int r; while ((r = inStream.Read(b, 0, b.Length)) > 0) outStream.Write(b, 0, r); outStream.Flush(); outStream.Close(); } }
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; }
/// <summary> /// Donwload a binary content. /// </summary> /// <param name="absoluteUri">The absolute URI.</param> /// <param name="binaryContent">Content of the binary.</param> /// <param name="options">The options.</param> public static void DownloadBinary( Uri absoluteUri, out byte[] binaryContent, WebSiteDownloaderOptions options ) { Debug.WriteLine( string.Format( @"Reading content from URL '{0}'.", absoluteUri ) ); try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create( absoluteUri ); ApplyProxy( req, options ); RequestCachePolicy cp = new RequestCachePolicy( RequestCacheLevel.BypassCache ); req.CachePolicy = cp; using ( HttpWebResponse resp = (HttpWebResponse)req.GetResponse() ) using ( Stream stream = resp.GetResponseStream() ) using ( MemoryStream mem = new MemoryStream() ) { int blockSize = 16384; byte[] blockBuffer = new byte[blockSize]; int read; while ( (read = stream.Read( blockBuffer, 0, blockSize )) > 0 ) { mem.Write( blockBuffer, 0, read ); } mem.Seek( 0, SeekOrigin.Begin ); binaryContent = mem.GetBuffer(); } } catch ( WebException x ) { if ( x.Status == WebExceptionStatus.ProtocolError ) { HttpWebResponse resp = (HttpWebResponse)x.Response; if ( resp.StatusCode == HttpStatusCode.NotFound || resp.StatusCode == HttpStatusCode.InternalServerError ) { Trace.WriteLine( string.Format( @"Ignoring web exception: '{0}'.", x.Message ) ); binaryContent = null; } else { throw; } } else { throw; } } }
void InternalSetCachePolicy(RequestCachePolicy policy){ // Delayed creation of CacheProtocol until caching is actually turned on. if (m_CacheBinding != null && m_CacheBinding.Cache != null && m_CacheBinding.Validator != null && CacheProtocol == null && policy != null && policy.Level != RequestCacheLevel.BypassCache) { CacheProtocol = new RequestCacheProtocol(m_CacheBinding.Cache, m_CacheBinding.Validator.CreateValidator()); } m_CachePolicy = policy; }
internal static void BeginDownload( BitmapDecoder decoder, Uri uri, RequestCachePolicy uriCachePolicy, Stream stream ) { lock (_syncLock) { if (!_thread.IsAlive) { _thread.IsBackground = true; _thread.Start(); } } QueueEntry entry; // If there is already a download for this uri, just add the decoder to the list if (uri != null) { lock (_syncLock) { if (_uriTable[uri] != null) { entry = (QueueEntry)_uriTable[uri]; entry.decoders.Add(decoder); return; } } } entry = new QueueEntry(); entry.decoders = new List<BitmapDecoder>(); lock (_syncLock) { entry.decoders.Add(decoder); } entry.inputUri = uri; entry.inputStream = stream; string cacheFolder = MS.Win32.WinInet.InternetCacheFolder.LocalPath; bool passed = false; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // BlessedAssert try { // Get the file path StringBuilder tmpFileName = new StringBuilder(NativeMethods.MAX_PATH); MS.Win32.UnsafeNativeMethods.GetTempFileName(cacheFolder, "WPF", 0, tmpFileName); try { string pathToUse = tmpFileName.ToString(); SafeFileHandle fileHandle = MS.Win32.UnsafeNativeMethods.CreateFile( pathToUse, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, /* dwDesiredAccess */ 0, /* dwShare */ null, /* lpSecurityAttributes */ NativeMethods.CREATE_ALWAYS, /* dwCreationDisposition */ NativeMethods.FILE_ATTRIBUTE_TEMPORARY | NativeMethods.FILE_FLAG_DELETE_ON_CLOSE, /* dwFlagsAndAttributes */ IntPtr.Zero /* hTemplateFile */ ); if (fileHandle.IsInvalid) { throw new Win32Exception(); } entry.outputStream = new FileStream(fileHandle, FileAccess.ReadWrite); entry.streamPath = pathToUse; passed = true; } catch(Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } } } finally { SecurityPermission.RevertAssert(); } if (!passed) { throw new IOException(SR.Get(SRID.Image_CannotCreateTempFile)); } entry.readBuffer = new byte[READ_SIZE]; entry.contentLength = -1; entry.contentType = string.Empty; entry.lastPercent = 0; // Add the entry to the table if we know the uri if (uri != null) { lock (_syncLock) { _uriTable[uri] = entry; } } if (stream == null) { bool fElevate = false; if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) { SecurityHelper.BlockCrossDomainForHttpsApps(uri); // In this case we first check to see if the consumer has media permissions for // safe media (Site of Origin + Cross domain), if it // does we assert and run the code that requires the assert if (SecurityHelper.CallerHasMediaPermission(MediaPermissionAudio.NoAudio, MediaPermissionVideo.NoVideo, MediaPermissionImage.SafeImage)) { fElevate = true; } } // This is the case where we are accessing an http image from an http site and we have media permission if (fElevate) { (new WebPermission(NetworkAccess.Connect, BindUriHelper.UriToString(uri))).Assert(); // BlessedAssert } try { entry.webRequest = WpfWebRequestHelper.CreateRequest(uri); if (uriCachePolicy != null) { entry.webRequest.CachePolicy = uriCachePolicy; } } finally { if(fElevate) { WebPermission.RevertAssert(); } } entry.webRequest.BeginGetResponse(_responseCallback, entry); } else { _workQueue.Enqueue(entry); // Signal _waitEvent.Set(); } }
internal static BitmapDecoder CreateFromUriOrStream( Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy, bool insertInDecoderCache ) { Guid clsId = Guid.Empty; bool isOriginalWritable = false; SafeMILHandle decoderHandle = null; BitmapDecoder cachedDecoder = null; Uri finalUri = null; Stream uriStream = null; UnmanagedMemoryStream unmanagedMemoryStream = null; SafeFileHandle safeFilehandle = null; // check to ensure that images are allowed in partial trust DemandIfImageBlocked(); if (uri != null) { finalUri = (baseUri != null) ? System.Windows.Navigation.BaseUriHelper.GetResolvedUri(baseUri, uri) : uri; if (insertInDecoderCache) { if ((createOptions & BitmapCreateOptions.IgnoreImageCache) != 0) { ImagingCache.RemoveFromDecoderCache(finalUri); } cachedDecoder = CheckCache( finalUri, out clsId ); } } // try to retrieve the cached decoder if (cachedDecoder != null) { decoderHandle = cachedDecoder.InternalDecoder; } else if ((finalUri != null) && (finalUri.IsAbsoluteUri) && (stream == null) && ((finalUri.Scheme == Uri.UriSchemeHttp) || (finalUri.Scheme == Uri.UriSchemeHttps))) { return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy); } else if ((stream != null) && (!stream.CanSeek)) { return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy); } else { // Create an unmanaged decoder decoderHandle = BitmapDecoder.SetupDecoderFromUriOrStream( finalUri, stream, cacheOption, out clsId, out isOriginalWritable, out uriStream, out unmanagedMemoryStream, out safeFilehandle ); } BitmapDecoder decoder = null; // Find out the decoder type and wrap it appropriately and return that if (MILGuidData.GUID_ContainerFormatBmp == clsId) { decoder = new BmpBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatGif == clsId) { decoder = new GifBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatIco == clsId) { decoder = new IconBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatJpeg == clsId) { decoder = new JpegBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatPng == clsId) { decoder = new PngBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatTiff == clsId) { decoder = new TiffBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatWmp == clsId) { decoder = new WmpBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else { decoder = new UnknownBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } return decoder; }