Пример #1
0
        private FixedDocument _LoadDocument()
        {
            FixedDocument fixedDocument = null;
            Uri           uri           = this._ResolveUri();

            if (uri != null)
            {
                ContentType contentType = null;
                Stream      stream      = WpfWebRequestHelper.CreateRequestAndGetResponseStream(uri, out contentType);
                if (stream == null)
                {
                    throw new ApplicationException(SR.Get("DocumentReferenceNotFound"));
                }
                ParserContext parserContext = new ParserContext();
                parserContext.BaseUri = uri;
                if (BindUriHelper.IsXamlMimeType(contentType))
                {
                    XpsValidatingLoader xpsValidatingLoader = new XpsValidatingLoader();
                    fixedDocument = (xpsValidatingLoader.Load(stream, ((IUriContext)this).BaseUri, parserContext, contentType) as FixedDocument);
                }
                else
                {
                    if (!MimeTypeMapper.BamlMime.AreTypeAndSubTypeEqual(contentType))
                    {
                        throw new ApplicationException(SR.Get("DocumentReferenceUnsupportedMimeType"));
                    }
                    fixedDocument = (XamlReader.LoadBaml(stream, parserContext, null, true) as FixedDocument);
                }
                fixedDocument.DocumentReference = this;
            }
            return(fixedDocument);
        }
Пример #2
0
        /// <summary>
        /// Download the requested bytes
        /// </summary>
        private HttpWebRequest CreateHttpWebRequest(int[,] byteRanges)
        {
            HttpWebRequest request;

            // Create the request object
            request = (HttpWebRequest)WpfWebRequestHelper.CreateRequest(_requestedUri);
            request.ProtocolVersion = HttpVersion.Version11;
            request.Method          = "GET";

            // Set the Proxy to Empty one; If we don't set this to empty one, it will try to find one for us
            //  and ends up triggering JScript in another assembly. This will throw PolicyException since the JScript
            //  dll doesn't have execution right. This is a bug in CLR; supposed to be fixed later
            // Future work: Need to keep consistent HTTP stack with the WININET one (e.g. authentication, proxy, cookies)
            //            IWebProxy emptyProxy = GlobalProxySelection.GetEmptyWebProxy();
            //            request.Proxy = emptyProxy;

            request.Proxy = _proxy;

            request.Credentials = _credentials;
            request.CachePolicy = _cachePolicy;

            // Add byte ranges (to header)
            for (int i = 0; i < byteRanges.GetLength(0); ++i)
            {
                request.AddRange(byteRanges[i, Offset_Index],
                                 byteRanges[i, Offset_Index] + byteRanges[i, Length_Index] - 1);
            }

            return(request);
        }
        // Token: 0x06002CDC RID: 11484 RVA: 0x000CA334 File Offset: 0x000C8534
        private static object ValidateAndLoadPartFromAbsoluteUri(Uri AbsoluteUriDoc, bool validateOnly, string rootElement, out ContentType mimeType)
        {
            mimeType = null;
            object result = null;

            try
            {
                Stream        stream        = WpfWebRequestHelper.CreateRequestAndGetResponseStream(AbsoluteUriDoc, out mimeType);
                ParserContext parserContext = new ParserContext();
                parserContext.BaseUri = AbsoluteUriDoc;
                XpsValidatingLoader xpsValidatingLoader = new XpsValidatingLoader();
                if (validateOnly)
                {
                    xpsValidatingLoader.Validate(stream, null, parserContext, mimeType, rootElement);
                }
                else
                {
                    result = xpsValidatingLoader.Load(stream, null, parserContext, mimeType);
                }
            }
            catch (Exception ex)
            {
                if (!(ex is WebException) && !(ex is InvalidOperationException))
                {
                    throw;
                }
            }
            return(result);
        }
Пример #4
0
        public UnmanagedMemoryStream GetUnmanagedStream()
        {
            if (IsFile)
            {
                FileMapping fileMapping = new FileMapping();

                DemandFileIOPermission();

                fileMapping.OpenFile(_fontUri.LocalPath);
                return(fileMapping);
            }

            byte[] bits;

            // Try our cache first.
            lock (_resourceCache)
            {
                bits = _resourceCache.Get(_fontUri);
            }

            if (bits == null)
            {
                Stream fontStream;

                if (_isInternalCompositeFont)
                {
                    // We should read this font from our framework resources
                    fontStream = GetCompositeFontResourceStream();
                }
                else
                {
                    WebResponse response = WpfWebRequestHelper.CreateRequestAndGetResponse(_fontUri);
                    fontStream = response.GetResponseStream();
                    if (String.Equals(response.ContentType, ObfuscatedContentType, StringComparison.Ordinal))
                    {
                        // The third parameter makes sure the original stream is closed
                        // when the deobfuscating stream is disposed.
                        fontStream = new DeobfuscatingStream(fontStream, _fontUri, false);
                    }
                }

                UnmanagedMemoryStream unmanagedStream = fontStream as UnmanagedMemoryStream;

                if (unmanagedStream != null)
                {
                    return(unmanagedStream);
                }

                bits = StreamToByteArray(fontStream);

                fontStream?.Close();
            }

            lock (_resourceCache)
            {
                _resourceCache.Add(_fontUri, bits, false);
            }

            return(ByteArrayToUnmanagedStream(bits));
        }
Пример #5
0
        ///
        /// Response callback
        private static void ResponseCallback(IAsyncResult result)
        {
            QueueEntry entry = (QueueEntry)result.AsyncState;

            #pragma warning disable 6500

            // Catch all exceptions and marshal them to the correct thread
            try
            {
                WebResponse response = WpfWebRequestHelper.EndGetResponse(entry.webRequest, result);
                entry.inputStream   = response.GetResponseStream();
                entry.contentLength = response.ContentLength;
                entry.contentType   = response.ContentType;
                entry.webRequest    = null; // GC the WebRequest
                _workQueue.Enqueue(entry);

                // Signal
                _waitEvent.Set();
            }
            catch (Exception e)
            {
                MarshalException(entry, e);
            }

            #pragma warning restore 6500
        }
Пример #6
0
        /// <summary>
        /// Loads color profile given by profileUri
        /// </summary>
        private void Initialize(Uri profileUri, bool isStandardProfileUriNotFromUser)
        {
            bool tryProfileFromResource = false;

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

            if (!profileUri.IsAbsoluteUri)
            {
                throw new ArgumentException(SR.Get(SRID.UriNotAbsolute), "profileUri");
            }

            _profileUri = new SecurityCriticalData <Uri>(profileUri);
            _isProfileUriNotFromUser = new SecurityCriticalDataForSet <bool>(isStandardProfileUriNotFromUser);

            Stream profileStream = null;

            try
            {
                profileStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(profileUri);
            }
            catch (WebException)
            {
                //
                // If we couldn't load the system's default color profile (e.g. in partial trust), load a color profile from
                // a resource so the image shows up at least. If the user specified a color profile and we weren't
                // able to load it, we'll fail to avoid letting the user use this resource fallback as a way to discover
                // files on disk.
                //
                if (isStandardProfileUriNotFromUser)
                {
                    tryProfileFromResource = true;
                }
            }

            if (profileStream == null)
            {
                if (tryProfileFromResource)
                {
                    ResourceManager resourceManager = new ResourceManager(_colorProfileResources, Assembly.GetAssembly(typeof(ColorContext)));
                    byte[]          sRGBProfile     = (byte[])resourceManager.GetObject(_sRGBProfileName);

                    profileStream = new MemoryStream(sRGBProfile);
                }
                else
                {
                    //
                    // SECURITY WARNING: This exception includes the profile URI which may contain sensitive information. However, as of right now,
                    // this is safe because it can only happen when the URI is given to us by the user.
                    //
                    Invariant.Assert(!isStandardProfileUriNotFromUser);
                    throw new FileNotFoundException(SR.Get(SRID.FileNotFoundExceptionWithFileName, profileUri.AbsolutePath), profileUri.AbsolutePath);
                }
            }

            FromStream(profileStream, profileUri.AbsolutePath);
        }
Пример #7
0
        private WebRequest GetRequest(bool allowPseudoRequest)
        {
            if (_webRequest == null)
            {
                // Don't even attempt to create if we know it will fail.  This does not eliminate all failure cases
                // but most and is very common so let's save an expensive exception.
                // We still create a webRequest if possible even if we have a potential cacheEntry
                // because the caller may still specify BypassCache policy before calling GetResponse() that will force us to hit the server.
                if (!IsPreloadedPackage)
                {
                    // Need inner request so we can get/set properties or create a real WebResponse.
                    // Note: WebRequest.Create throws NotSupportedException for schemes that it does not recognize.
                    // We need to be open-ended in our support of schemes, so we need to always try to create.
                    // If WebRequest throws NotSupportedException then we catch and ignore if the WebRequest can be
                    // satisfied from the cache.  If the cache entry is missing then we simply re-throw because the request
                    // cannot possibly succeed.
                    try
                    {
                        _webRequest = WpfWebRequestHelper.CreateRequest(_innerUri);

                        // special optimization for ftp - Passive mode won't return lengths on ISA servers
                        FtpWebRequest ftpWebRequest = _webRequest as FtpWebRequest;
                        if (ftpWebRequest != null)
                        {
                            ftpWebRequest.UsePassive = false;  // default but allow override
                        }
                    }
                    catch (NotSupportedException)
                    {
                        // If the inner Uri does not match any cache entry then we throw.
                        if (!IsCachedPackage)
                        {
                            throw;
                        }
                    }
                }

                // Just return null if caller cannot accept a PseudoWebRequest
                if (_webRequest == null && allowPseudoRequest)
                {
                    // We get here if the caller can accept a PseudoWebRequest (based on argument to the function)
                    // and one of these two cases is true:
                    // 1. We have a package from the PreloadedPackages collection
                    // 2. If WebRequest.Create() failed and we have a cached package
                    // In either case, we create a pseudo request to house property values.
                    // In case 1, we know there will never be a cache bypass (we ignore cache policy for PreloadedPackages)
                    // In case 2, the caller is using a schema that we cannot use for transport (not on of ftp, http, file, etc)
                    // and we will silently accept and ignore their property modifications/queries.
                    // Note that if they change the cache policy to BypassCache they will get an exception when they call
                    // GetResponse().  If they leave cache policy intact, and call GetResponse()
                    // they will get data from the cached package.
                    _webRequest = new PseudoWebRequest(_uri, _innerUri, _partName, _cacheEntry);
                }
            }

            return(_webRequest);
        }
Пример #8
0
 internal static WebRequest CreateWebRequest(Uri uri)
 {
     if (String.Compare(uri.Scheme, PackUriHelper.UriSchemePack, StringComparison.Ordinal) == 0)
     {
         return(((IWebRequestCreate)_factorySingleton).Create(uri));
     }
     else
     {
         return(WpfWebRequestHelper.CreateRequest(uri));
     }
 }
Пример #9
0
        private void BeginLoadStream()
        {
            if (m_lastRequestedAbsoluteUri != null) // Only reload if the new source is non-null
            {
                m_streamLoadInProgress = true;

                // Step 1: Perform an asynchronous load of the WebResponse and its associated Stream
                Task.Run(() =>
                {
                    Stream result = WpfWebRequestHelper.CreateRequestAndGetResponseStream(m_lastRequestedAbsoluteUri);
                    LoadStreamCallback(result);
                });
            }
        }
Пример #10
0
        // Token: 0x06003247 RID: 12871 RVA: 0x000DC6B8 File Offset: 0x000DA8B8
        internal Stream GetPageStream()
        {
            Uri    uri    = this._ResolveUri();
            Stream stream = null;

            if (uri != null)
            {
                stream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(uri);
                if (stream == null)
                {
                    throw new ApplicationException(SR.Get("PageContentNotFound"));
                }
            }
            return(stream);
        }
        internal Stream GetPageStream()
        {
            Uri    uriToLoad  = _ResolveUri();
            Stream pageStream = null;

            if (uriToLoad != null)
            {
                pageStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(uriToLoad);
                if (pageStream == null)
                {
                    throw new ApplicationException(SR.Get(SRID.PageContentNotFound));
                }
            }

            return(pageStream);
        }
Пример #12
0
        /// <summary>
        /// This method is invoked whenever the source property changes.
        /// </summary>
        private void UriSourcePropertyChangedHook(DependencyPropertyChangedEventArgs e)
        {
            // Decided against comparing the URI because the user might want to change the shader on the filesystem
            // and reload it.

            // We do not support async loading of shaders here. If that is desired the user needs to use the SetStreamSource
            // API.

            Uri    newUri = (Uri)e.NewValue;
            Stream stream = null;

            try {
                if (newUri != null)
                {
                    if (!newUri.IsAbsoluteUri)
                    {
                        newUri = BaseUriHelper.GetResolvedUri(BaseUriHelper.BaseUri, newUri);
                    }

                    Debug.Assert(newUri.IsAbsoluteUri);

                    // Now the URI is an absolute URI.

                    //
                    // Only allow file and pack URIs.
                    if (!newUri.IsFile &&
                        !PackUriHelper.IsPackUri(newUri))
                    {
                        throw new ArgumentException(SR.Get(SRID.Effect_SourceUriMustBeFileOrPack));
                    }

                    stream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(newUri);
                }

                LoadPixelShaderFromStreamIntoMemory(stream);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
Пример #13
0
        private HttpWebRequest CreateHttpWebRequest(int[,] byteRanges)
        {
            HttpWebRequest request;

            // Create the request object
            request = (HttpWebRequest)WpfWebRequestHelper.CreateRequest(_requestedUri);
            request.ProtocolVersion = HttpVersion.Version11;
            request.Method          = "GET";

            // Set the Proxy to Empty one; If we don't set this to empty one, it will try to find one for us
            //  and ends up triggering JScript in another assembly. This will throw PolicyException since the JScript
            //  dll doesn't have execution right. This is



            // Local assert to allow Proxy get/set under partial trust
            new WebPermission(PermissionState.Unrestricted).Assert();   // Blessed
            try
            {
                request.Proxy = _proxy;
            }
            finally
            {
                WebPermission.RevertAssert();
            }

            request.Credentials = _credentials;
            request.CachePolicy = _cachePolicy;

            // Add byte ranges (to header)
            for (int i = 0; i < byteRanges.GetLength(0); ++i)
            {
                request.AddRange(byteRanges[i, Offset_Index],
                                 byteRanges[i, Offset_Index] + byteRanges[i, Length_Index] - 1);
            }

            return(request);
        }
Пример #14
0
        private FixedDocument _LoadDocument()
        {
            FixedDocument idp       = null;
            Uri           uriToLoad = _ResolveUri();

            if (uriToLoad != null)
            {
                ContentType mimeType  = null;
                Stream      docStream = null;

                docStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(uriToLoad, out mimeType);
                if (docStream == null)
                {
                    throw new ApplicationException(SR.Get(SRID.DocumentReferenceNotFound));
                }

                ParserContext pc = new ParserContext();

                pc.BaseUri = uriToLoad;

                if (BindUriHelper.IsXamlMimeType(mimeType))
                {
                    XpsValidatingLoader loader = new XpsValidatingLoader();
                    idp = loader.Load(docStream, ((IUriContext)this).BaseUri, pc, mimeType) as FixedDocument;
                }
                else if (MS.Internal.MimeTypeMapper.BamlMime.AreTypeAndSubTypeEqual(mimeType))
                {
                    idp = XamlReader.LoadBaml(docStream, pc, null, true) as FixedDocument;
                }
                else
                {
                    throw new ApplicationException(SR.Get(SRID.DocumentReferenceUnsupportedMimeType));
                }
                idp.DocumentReference = this;
            }

            return(idp);
        }
Пример #15
0
        private Stream HandleWebSource(bool onlyNeedContentType)
        {
            WebResponse response       = WpfWebRequestHelper.CreateRequestAndGetResponse(_absoluteLocation);
            Stream      responseStream = response.GetResponseStream();

#if DEBUG
            if (SiteOfOriginContainer._traceSwitch.Enabled)
            {
                System.Diagnostics.Trace.TraceInformation(
                    DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                    System.Threading.Thread.CurrentThread.ManagedThreadId +
                    ": Successfully retrieved stream from " + _absoluteLocation);
            }
#endif

            if (_contentType == MS.Internal.ContentType.Empty)
            {
#if DEBUG
                if (SiteOfOriginContainer._traceSwitch.Enabled)
                {
                    System.Diagnostics.Trace.TraceInformation(
                        DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                        System.Threading.Thread.CurrentThread.ManagedThreadId +
                        ": SiteOfOriginPart: Setting _contentType");
                }
#endif

                _contentType = WpfWebRequestHelper.GetContentType(response);
            }

            if (onlyNeedContentType)
            {
                _cacheStream = responseStream;
            }

            return(responseStream);
        }
        internal static void _LoadPageImpl(Uri baseUri, Uri uriToLoad, out FixedPage fixedPage, out Stream pageStream)
        {
            ContentType mimeType;

            pageStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(uriToLoad, out mimeType);
            object o = null;

            if (pageStream == null)
            {
                throw new ApplicationException(SR.Get(SRID.PageContentNotFound));
            }

            ParserContext pc = new ParserContext();

            pc.BaseUri = uriToLoad;

            if (BindUriHelper.IsXamlMimeType(mimeType))
            {
                XpsValidatingLoader loader = new XpsValidatingLoader();
                o = loader.Load(pageStream, baseUri, pc, mimeType);
            }
            else if (MS.Internal.MimeTypeMapper.BamlMime.AreTypeAndSubTypeEqual(mimeType))
            {
                o = XamlReader.LoadBaml(pageStream, pc, null, true);
            }
            else
            {
                throw new ApplicationException(SR.Get(SRID.PageContentUnsupportedMimeType));
            }

            if (o != null && !(o is FixedPage))
            {
                throw new ApplicationException(SR.Get(SRID.PageContentUnsupportedPageType, o.GetType()));
            }

            fixedPage = (FixedPage)o;
        }
Пример #17
0
        // Token: 0x06003252 RID: 12882 RVA: 0x000DC99C File Offset: 0x000DAB9C
        internal static void _LoadPageImpl(Uri baseUri, Uri uriToLoad, out FixedPage fixedPage, out Stream pageStream)
        {
            ContentType contentType;

            pageStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(uriToLoad, out contentType);
            if (pageStream == null)
            {
                throw new ApplicationException(SR.Get("PageContentNotFound"));
            }
            ParserContext parserContext = new ParserContext();

            parserContext.BaseUri = uriToLoad;
            object obj;

            if (BindUriHelper.IsXamlMimeType(contentType))
            {
                XpsValidatingLoader xpsValidatingLoader = new XpsValidatingLoader();
                obj = xpsValidatingLoader.Load(pageStream, baseUri, parserContext, contentType);
            }
            else
            {
                if (!MimeTypeMapper.BamlMime.AreTypeAndSubTypeEqual(contentType))
                {
                    throw new ApplicationException(SR.Get("PageContentUnsupportedMimeType"));
                }
                obj = XamlReader.LoadBaml(pageStream, parserContext, null, true);
            }
            if (obj != null && !(obj is FixedPage))
            {
                throw new ApplicationException(SR.Get("PageContentUnsupportedPageType", new object[]
                {
                    obj.GetType()
                }));
            }
            fixedPage = (FixedPage)obj;
        }
Пример #18
0
        // Token: 0x06001CE3 RID: 7395 RVA: 0x00086FA8 File Offset: 0x000851A8
        private void CreateDocFromExternalSource(WebRequest request)
        {
            bool        flag        = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Transfer);
            XmlDocument xmlDocument = new XmlDocument();
            Exception   ex          = null;

            try
            {
                if (flag)
                {
                    TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadSource(new object[]
                    {
                        TraceData.Identify(this),
                        base.Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
                        TraceData.Identify(request.RequestUri.ToString())
                    }));
                }
                WebResponse response = WpfWebRequestHelper.GetResponse(request);
                if (response == null)
                {
                    throw new InvalidOperationException(SR.Get("GetResponseFailed"));
                }
                Stream responseStream = response.GetResponseStream();
                if (flag)
                {
                    TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadDoc(new object[]
                    {
                        TraceData.Identify(this)
                    }));
                }
                xmlDocument.Load(responseStream);
                responseStream.Close();
            }
            catch (Exception ex2)
            {
                if (CriticalExceptions.IsCriticalException(ex2))
                {
                    throw;
                }
                ex = ex2;
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.XmlDPAsyncDocError, this.Source, ex);
                }
            }
            catch
            {
                throw;
            }
            if (ex != null)
            {
                if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Attach))
                {
                    TraceData.Trace(TraceEventType.Warning, TraceData.QueryFinished(new object[]
                    {
                        TraceData.Identify(this),
                        base.Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
                        TraceData.Identify(null),
                        TraceData.IdentifyException(ex)
                    }));
                }
                this.OnQueryFinished(null, ex, this.CompletedCallback, null);
                return;
            }
            this.BuildNodeCollection(xmlDocument);
        }
Пример #19
0
        // this method can run on a worker thread!
        private void CreateDocFromExternalSource(WebRequest request)
        {
            bool isExtendedTraceEnabled = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.XmlProvider);

            XmlDocument doc = new XmlDocument();
            Exception   ex  = null;

            // request the content from the URI
            try
            {
                if (isExtendedTraceEnabled)
                {
                    TraceData.Trace(TraceEventType.Warning,
                                    TraceData.XmlLoadSource(
                                        TraceData.Identify(this),
                                        Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
                                        TraceData.Identify(request.RequestUri.ToString())));
                }

                WebResponse response = WpfWebRequestHelper.GetResponse(request);
                if (response == null)
                {
                    throw new InvalidOperationException(SR.Get(SRID.GetResponseFailed));
                }

                // Get Stream and content type from WebResponse.
                Stream stream = response.GetResponseStream();

                if (isExtendedTraceEnabled)
                {
                    TraceData.Trace(TraceEventType.Warning,
                                    TraceData.XmlLoadDoc(
                                        TraceData.Identify(this)));
                }

                // load the XML from the stream
                doc.Load(stream);
                stream.Close();
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e))
                {
                    throw;
                }
                ex = e;
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.XmlDPAsyncDocError, Source, ex);
                }
            }
            //FXCop Fix: CatchNonClsCompliantExceptionsInGeneralHandlers
            catch
            {
                throw;
            }

            if (ex != null)
            {
                if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.ProviderQuery))
                {
                    TraceData.Trace(TraceEventType.Warning,
                                    TraceData.QueryFinished(
                                        TraceData.Identify(this),
                                        Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
                                        TraceData.Identify(null),
                                        TraceData.IdentifyException(ex)));
                }

                // we're done if we got an error up to this point
                // both .Data and .Document properties will be reset to null
                OnQueryFinished(null, ex, CompletedCallback, null);
                return;  // have an error, no processing of DOM
            }

            BuildNodeCollection(doc);
            // above method also calls OnQueryFinished to push new property values
        }
Пример #20
0
        ///
        /// Begin a download
        ///
        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(new WeakReference(decoder));

                        return;
                    }
                }
            }

            entry          = new QueueEntry();
            entry.decoders = new List <WeakReference>();

            lock (_syncLock)
            {
                entry.decoders.Add(new WeakReference(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)
            {
                entry.webRequest = WpfWebRequestHelper.CreateRequest(uri);
                if (uriCachePolicy != null)
                {
                    entry.webRequest.CachePolicy = uriCachePolicy;
                }

                entry.webRequest.BeginGetResponse(_responseCallback, entry);
            }
            else
            {
                _workQueue.Enqueue(entry);
                // Signal
                _waitEvent.Set();
            }
        }
Пример #21
0
        //------------------------------------------------------
        //
        //  Public Methods
        //
        //------------------------------------------------------

        #region WebResponse Overloads
        /// <summary>
        /// Retrieves a stream for reading bytes from the requested resource
        /// </summary>
        /// <returns>stream</returns>
        public override Stream GetResponseStream()
        {
            CheckDisposed();

            // redirect
            if (FromPackageCache)
            {
                return(_cachedResponse.GetResponseStream());
            }

            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXGetStreamBegin);

#if DEBUG
            if (PackWebRequestFactory._traceSwitch.Enabled)
            {
                System.Diagnostics.Trace.TraceInformation(
                    DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                    System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                    "PackWebResponse - GetResponseStream()");
            }
#endif
            // create and return only a single stream for multiple calls
            if (_responseStream == null)
            {
                // can't do this until the response is available
                WaitForResponse();  // after this call, we have a viable _fullResponse object because WaitForResponse would have thrown otherwise

                // determine content length
                long streamLength = _fullResponse.ContentLength;

#if DEBUG
                if (_forceWebResponseLengthFailureSwitch.Enabled)
                {
                    streamLength = -1;
                }

                // special handling for servers that won't or can't give us the length of the resource - byte-range downloading is impossible
                if (streamLength <= 0)
                {
                    if (PackWebRequestFactory._traceSwitch.Enabled)
                    {
                        System.Diagnostics.Trace.TraceInformation(
                            DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                            System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                            "PackWebResponse - GetResponseStream() - stream length not available - disabling progressive download");
                    }
                }
#endif

                //  Start reading data from the response stream.
                _responseStream = _fullResponse.GetResponseStream();

                // require NetStream for progressivity and for network streams that don't
                // directly support seeking.
                if (!_responseStream.CanSeek || !_innerUri.IsFile)
                {
                    // Create a smart stream that will spawn byte-range requests as needed
                    // and support seeking. Each read has overhead of Mutex and many of the
                    // reads come through asking for 4 bytes at a time
                    _responseStream = new NetStream(
                        _responseStream, streamLength,
                        _innerUri, _webRequest, _fullResponse);

                    // wrap our stream for efficiency (short reads are expanded)
                    _responseStream = new BufferedStream(_responseStream);
                }

                // handle degenerate case where there is no part name
                if (_partName == null)
                {
                    _fullStreamLength = streamLength;    // entire container
                    _mimeType         = WpfWebRequestHelper.GetContentType(_fullResponse);

                    // pass this so that ResponseStream holds a reference to us until the stream is closed
                    _responseStream = new ResponseStream(_responseStream, this);
                }
                else
                {
                    // open container on netStream
                    Package c = Package.Open(_responseStream);
                    if (!c.PartExists(_partName))
                    {
                        throw new WebException(SR.Get(SRID.WebResponsePartNotFound));
                    }

                    PackagePart p = c.GetPart(_partName);

                    Stream s = p.GetSeekableStream(FileMode.Open, FileAccess.Read);

                    _mimeType         = new MS.Internal.ContentType(p.ContentType); // save this for use in ContentType property - may still be null
                    _fullStreamLength = s.Length;                                   // just this stream

                    // Wrap in a ResponseStream so that this container will be released
                    // when the stream is closed
                    _responseStream = new ResponseStream(s, this, _responseStream, c);
                }

                // length available? (-1 means the server chose not to report it)
                if (_fullStreamLength >= 0)
                {
                    _lengthAvailable = true;
                }
            }

            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXGetStreamEnd);

            return(_responseStream);
        }
Пример #22
0
        /// <summary>
        /// ResponseCallBack
        /// </summary>
        /// <param name="ar">async result</param>
        /// <remarks>static method not necessary</remarks>
        private void ResponseCallback(IAsyncResult ar)
        {
            HttpWebResponse webResponse = null;

            lock (_syncObject)
            {
                try
                {
                    if (_disposed)
                    {
                        return;
                    }

                    // The caller thread can dispose this class and the worker thread need to check the disposed
                    //  condition; need to lock
                    // If disposed, there is nothing to handle
                    webResponse = (HttpWebResponse)WpfWebRequestHelper.EndGetResponse(_webRequest, ar);

                    // If it is not partial content, no need to look further
                    if (webResponse.StatusCode == HttpStatusCode.PartialContent)
                    {
                        //
                        // Check for few conditions
                        //

                        // Get the header and make sure that it was indeed the byte range response
                        int beginOffset = _byteRangesInProgress[0, Offset_Index];
                        int endOffset   = beginOffset + _byteRangesInProgress[0, Length_Index] - 1;

                        // HttpWebRequest in the current CLR does not allow multiple byte range requests.
                        // At this point, none of the callers of this class will make more than one range at a time
                        //  So, we should not receive any response with more than one range returned

                        // When multiple byte ranges requests are support in HttpWebRequest eventually,
                        // there is a question on how to handle multipart response (Content-Type=multipart/byteranges)

                        // At this point we only need to handle one byte range response (Content-Range header) only
                        // Request was successful
                        // Note: endOffset could be trimmed offset in the case where the response didn't
                        //  satisfy the entire request
                        if (CheckContentRange(webResponse.Headers, beginOffset, ref endOffset))
                        {
                            // Write out the bytes to the temp file
                            if (WriteByteRange(webResponse, beginOffset, endOffset - beginOffset + 1))
                            {
                                // The range is downloaded successfully; add it to the list
                                _byteRangesAvailable.Add(beginOffset);
                                _byteRangesAvailable.Add(endOffset - beginOffset + 1);
                            }
                            else
                            {
                                _erroredOut = true;
                            }
                        }
                        else
                        {
                            _erroredOut          = true;
                            _erroredOutException = new NotSupportedException(SR.Get(SRID.ByteRangeRequestIsNotSupported));
                        }
                    }
                    else
                    {
                        _erroredOut = true;
                    }
                }
                catch (Exception e)  // catch (and re-throw) exceptions so we can inform the other thread
                {
                    _erroredOut          = true;
                    _erroredOutException = e;

                    throw e;
                }
                catch   // catch (and re-throw) all kinds of exceptions so we can inform the other thread
                {
                    // inform other thread of error condition
                    _erroredOut          = true;
                    _erroredOutException = null;

                    throw;
                }
                finally
                {
                    if (webResponse != null)
                    {
                        webResponse.Close();
                    }

                    // bytes requested are downloaded or errored out
                    //  inform the caller that these ranges are available
                    RaiseEvent(!_erroredOut);
                }

                // If we haven't errored out already, process the next batch
                if (!_erroredOut)
                {
                    ProcessWaitQueue();
                }
            }
        }
 // Token: 0x06005655 RID: 22101 RVA: 0x0017E6BD File Offset: 0x0017C8BD
 private Stream LoadStreamAsync(Uri uri)
 {
     return(WpfWebRequestHelper.CreateRequestAndGetResponseStream(uri));
 }
Пример #24
0
        /// <summary>
        /// TypeConverter method implementation.
        /// </summary>
        /// <param name="context">ITypeDescriptorContext</param>
        /// <param name="culture">current culture (see CLR specs)</param>
        /// <param name="value">value to convert from</param>
        /// <returns>value that is result of conversion</returns>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                string text = ((string)value).Trim();

                if (text != String.Empty)
                {
                    if (text.LastIndexOf('.') == -1)
                    {
                        CursorType ct = (CursorType)Enum.Parse(typeof(CursorType), text);

                        switch (ct)
                        {
                        case CursorType.Arrow:
                            return(Cursors.Arrow);

                        case CursorType.AppStarting:
                            return(Cursors.AppStarting);

                        case CursorType.Cross:
                            return(Cursors.Cross);

                        case CursorType.Help:
                            return(Cursors.Help);

                        case CursorType.IBeam:
                            return(Cursors.IBeam);

                        case CursorType.SizeAll:
                            return(Cursors.SizeAll);

                        case CursorType.SizeNESW:
                            return(Cursors.SizeNESW);

                        case CursorType.SizeNS:
                            return(Cursors.SizeNS);

                        case CursorType.SizeNWSE:
                            return(Cursors.SizeNWSE);

                        case CursorType.SizeWE:
                            return(Cursors.SizeWE);

                        case CursorType.UpArrow:
                            return(Cursors.UpArrow);

                        case CursorType.Wait:
                            return(Cursors.Wait);

                        case CursorType.Hand:
                            return(Cursors.Hand);

                        case CursorType.No:
                            return(Cursors.No);

                        case CursorType.None:
                            return(Cursors.None);

                        case CursorType.Pen:
                            return(Cursors.Pen);

                        case CursorType.ScrollNS:
                            return(Cursors.ScrollNS);

                        case CursorType.ScrollWE:
                            return(Cursors.ScrollWE);

                        case CursorType.ScrollAll:
                            return(Cursors.ScrollAll);

                        case CursorType.ScrollN:
                            return(Cursors.ScrollN);

                        case CursorType.ScrollS:
                            return(Cursors.ScrollS);

                        case CursorType.ScrollW:
                            return(Cursors.ScrollW);

                        case CursorType.ScrollE:
                            return(Cursors.ScrollE);

                        case CursorType.ScrollNW:
                            return(Cursors.ScrollNW);

                        case CursorType.ScrollNE:
                            return(Cursors.ScrollNE);

                        case CursorType.ScrollSW:
                            return(Cursors.ScrollSW);

                        case CursorType.ScrollSE:
                            return(Cursors.ScrollSE);

                        case CursorType.ArrowCD:
                            return(Cursors.ArrowCD);
                        }
                    }
                    else
                    {
                        if (text.EndsWith(".cur", StringComparison.OrdinalIgnoreCase) || text.EndsWith(".ani", StringComparison.OrdinalIgnoreCase))
                        {
                            UriHolder uriHolder = TypeConverterHelper.GetUriFromUriContext(context, text);
                            Uri       finalUri  = BindUriHelper.GetResolvedUri(uriHolder.BaseUri, uriHolder.OriginalUri);

                            if (finalUri.IsAbsoluteUri && finalUri.IsFile)
                            {
                                return(new Cursor(finalUri.LocalPath));
                            }
                            else
                            {
                                System.Net.WebRequest request = WpfWebRequestHelper.CreateRequest(finalUri);
                                WpfWebRequestHelper.ConfigCachePolicy(request, false);
                                return(new Cursor(WpfWebRequestHelper.GetResponseStream(request)));
                            }
                        }
                    }
                }
                else
                {
                    // An empty string means no cursor.
                    return(null);
                }
            }

            throw GetConvertFromException(value);
        }
Пример #25
0
        ///
        /// Begin a download
        ///
        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(new WeakReference(decoder));

                        return;
                    }
                }
            }

            entry          = new QueueEntry();
            entry.decoders = new List <WeakReference>();

            lock (_syncLock)
            {
                entry.decoders.Add(new WeakReference(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();
            }
        }