Ejemplo n.º 1
0
        // ------------------------------------
        // API needed for RTF-to-XAML Converter
        // ------------------------------------

        internal Stream CreateXamlStream()
        {
            PackagePart part = this.CreateWpfEntryPart();

            // Return a stream opened for writing an image data
            return(part.GetSeekableStream());
        }
Ejemplo n.º 2
0
        // Creates a part containing an image with a relationship to it from a sourcePart
        private void CreateImagePart(PackagePart sourcePart, BitmapSource imageSource, string imageContentType, int imageIndex)
        {
            // Generate a new unique image part name
            string imagePartUriString = GetImageName(imageIndex, imageContentType);

            // Define an image part uri
            Uri imagePartUri = new Uri(XamlPayloadDirectory + imagePartUriString, UriKind.Relative);

            // Create a part for the image
            PackagePart imagePart = _package.CreatePart(imagePartUri, imageContentType, CompressionOption.NotCompressed);

            // Create the relationship referring from the enrty part to the image part
            PackageRelationship componentRelationship = sourcePart.CreateRelationship(imagePartUri, TargetMode.Internal, XamlRelationshipFromXamlPartToComponentPart);

            // Encode the image data
            BitmapEncoder bitmapEncoder = GetBitmapEncoder(imageContentType);

            bitmapEncoder.Frames.Add(BitmapFrame.Create(imageSource));

            // Save encoded image data into the image part in the package
            Stream imageStream = imagePart.GetSeekableStream();

            using (imageStream)
            {
                bitmapEncoder.Save(imageStream);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Loads xaml content from a WPF package.
        /// </summary>
        /// <param name="stream">
        /// Stream that must be accessible for reading and structured as
        /// a WPF container: part XamlEntryPart is expected as one of
        /// its entry parts.
        /// </param>
        /// <returns>
        /// Returns a xaml element loaded from the entry part of the package.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Throws parsing exception when the xaml content does not comply with the xaml schema.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Throws validation exception when the package is not well structured.
        /// </exception>
        /// <exception cref="Exception">
        /// Throws uri exception when the pachageBaseUri is not correct absolute uri.
        /// </exception>
        /// <remarks>
        /// USED IN LEXICON VIA REFLECTION
        /// </remarks>
        internal static object LoadElement(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            object xamlObject;

            try
            {
                WpfPayload wpfPayload = WpfPayload.OpenWpfPayload(stream);

                // Now load the package
                using (wpfPayload.Package)
                {
                    // Validate WPF paypoad and get its entry part
                    PackagePart xamlEntryPart = wpfPayload.ValidatePayload();

                    // Define a unique uri for this instance of PWF payload.
                    // Uniqueness is required to make sure that cached images are not mixed up.
                    int newWpfPayoutCount = Interlocked.Increment(ref _wpfPayloadCount);
                    Uri payloadUri        = new Uri("payload://wpf" + newWpfPayoutCount, UriKind.Absolute);
                    Uri entryPartUri      = System.IO.Packaging.PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part
                    Uri packageUri        = System.IO.Packaging.PackUriHelper.GetPackageUri(entryPartUri);           // extracts package uri from combined package+part uri
                    PackageStore.AddPackage(packageUri, wpfPayload.Package);                                         // Register the package

                    // Set this temporary uri as a base uri for xaml parser
                    ParserContext parserContext = new ParserContext();
                    parserContext.BaseUri = entryPartUri;

                    // Call xaml parser
                    xamlObject = XamlReader.Load(xamlEntryPart.GetSeekableStream(), parserContext, useRestrictiveXamlReader: true);

                    // Remove the temporary uri from the PackageStore
                    PackageStore.RemovePackage(packageUri);
                }
            }
            catch (XamlParseException e)
            {
                // Incase of xaml parsing or package structure failure
                // we return null.
                Invariant.Assert(e != null); //to make compiler happy about not using a variable e. This variable is useful in debugging process though - to see a reason of a parsing failure
                xamlObject = null;
            }
            catch (System.IO.FileFormatException)
            {
                xamlObject = null;
            }
            catch (System.IO.FileLoadException)
            {
                xamlObject = null;
            }
            catch (System.OutOfMemoryException)
            {
                xamlObject = null;
            }

            return(xamlObject);
        }
Ejemplo n.º 4
0
        internal Stream GetImageStream(string imageSourceString)
        {
            Invariant.Assert(imageSourceString.StartsWith("./", StringComparison.OrdinalIgnoreCase));
            imageSourceString = imageSourceString.Substring(1); // cut the leading dot out
            Uri         imagePartUri = new Uri(XamlPayloadDirectory + imageSourceString, UriKind.Relative);
            PackagePart imagePart    = _package.GetPart(imagePartUri);

            return(imagePart.GetSeekableStream());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Saves the content of the range in the given stream as a WPF payload.
        /// </summary>
        /// <param name="range">
        /// The range whose content is to be serialized.
        /// </param>
        /// <param name="stream">
        /// When the stream is not null, it is a request to unconditionally
        /// creatte WPF package in this stream.
        /// If this parameter is null, then the package is created
        /// only when necessary - when there are images in the range.
        /// The new MemoryStream is created in this case and assigned to this
        /// parameter on exit.
        /// </param>
        /// <param name="useFlowDocumentAsRoot">
        /// </param>
        /// <param name="preserveTextElements">
        /// If set false, custom TextElements will be upcasted to known types.
        /// </param>
        /// <returns>
        /// A xaml part of serialized content.
        /// </returns>
        internal static string SaveRange(ITextRange range, ref Stream stream, bool useFlowDocumentAsRoot, bool preserveTextElements)
        {
            if (range == null)
            {
                throw new ArgumentNullException("range");
            }

            // Create the wpf package in the stream
            WpfPayload wpfPayload = new WpfPayload(/*package:*/ null);

            // Create a string representing serialized xaml
            StringWriter  stringWriter = new StringWriter(CultureInfo.InvariantCulture);
            XmlTextWriter xmlWriter    = new XmlTextWriter(stringWriter);

            TextRangeSerialization.WriteXaml(xmlWriter, range, useFlowDocumentAsRoot, wpfPayload, preserveTextElements);
            string xamlText = stringWriter.ToString();

            // Decide whether we need to create a package
            if (stream != null || wpfPayload._images != null)
            {
                // There are images in the content. Need to create a package
                if (stream == null)
                {
                    stream = new MemoryStream();
                }

                // Create a package in the stream
                using (wpfPayload.CreatePackage(stream))
                {
                    // Create the entry part for xaml content of the WPF package
                    PackagePart xamlEntryPart = wpfPayload.CreateWpfEntryPart();

                    // Write the part's content
                    Stream xamlPartStream = xamlEntryPart.GetSeekableStream();
                    using (xamlPartStream)
                    {
                        StreamWriter xamlPartWriter = new StreamWriter(xamlPartStream);
                        using (xamlPartWriter)
                        {
                            xamlPartWriter.Write(xamlText);
                        }
                    }

                    // Write relationships from xaml entry part to all images
                    wpfPayload.CreateComponentParts(xamlEntryPart);
                }

                Invariant.Assert(wpfPayload._images == null); // must have beed cleared in CreateComponentParts
            }

            return(xamlText);
        }
        private static XmlNode GeneratePartSigningReference(
            PackageDigitalSignatureManager manager,
            XmlDocument xDoc,
            HashAlgorithm hashAlgorithm,
            Uri partName)
        {
            PackagePart part = manager.Package.GetPart(partName);

            // <Reference>
            XmlElement reference = xDoc.CreateElement(XTable.Get(XTable.ID.ReferenceTagName), SignedXml.XmlDsigNamespaceUrl);

            // add Uri with content type as Query
            XmlAttribute uriAttr = xDoc.CreateAttribute(XTable.Get(XTable.ID.UriAttrName));

            uriAttr.Value = PackUriHelper.GetStringForPartUri(partName) + _contentTypeQueryStringPrefix + part.ContentType;
            reference.Attributes.Append(uriAttr);

            // add transforms tag if necessary
            String transformName = String.Empty;

            if (manager.TransformMapping.ContainsKey(part.ContentType))
            {
                transformName = manager.TransformMapping[part.ContentType];

                // <Transforms>
                XmlElement transforms = xDoc.CreateElement(XTable.Get(XTable.ID.TransformsTagName), SignedXml.XmlDsigNamespaceUrl);

                // <Transform>
                XmlElement   transform     = xDoc.CreateElement(XTable.Get(XTable.ID.TransformTagName), SignedXml.XmlDsigNamespaceUrl);
                XmlAttribute algorithmAttr = xDoc.CreateAttribute(XTable.Get(XTable.ID.AlgorithmAttrName));
                algorithmAttr.Value = transformName;
                transform.Attributes.Append(algorithmAttr);

                transforms.AppendChild(transform);
                reference.AppendChild(transforms);
            }

            // <DigestMethod>
            reference.AppendChild(GenerateDigestMethod(manager, xDoc));

            // <DigestValue>
            using (Stream s = part.GetSeekableStream(FileMode.Open, FileAccess.Read))
            {
                reference.AppendChild(GenerateDigestValueNode(xDoc, hashAlgorithm, s, transformName));
            }

            return(reference);
        }
Ejemplo n.º 7
0
        // Creates a WPF container in new MemoryStream and places an image into it
        // with the simplest xaml part referring to it (wrapped into InlineUIContainer).
        internal static MemoryStream SaveImage(BitmapSource bitmapSource, string imageContentType)
        {
            MemoryStream stream = new MemoryStream();

            // Create the wpf package in the stream
            WpfPayload wpfPayload = new WpfPayload(/*package:*/ null);

            // Create a package in the stream
            using (wpfPayload.CreatePackage(stream))
            {
                // Define a reference for the image
                int    imageIndex     = 0;
                string imageReference = GetImageReference(GetImageName(imageIndex, imageContentType));

                // Create the entry part for xaml content of the WPF package
                PackagePart xamlEntryPart = wpfPayload.CreateWpfEntryPart();

                // Write the part's content
                Stream xamlPartStream = xamlEntryPart.GetSeekableStream();
                using (xamlPartStream)
                {
                    StreamWriter xamlPartWriter = new StreamWriter(xamlPartStream);
                    using (xamlPartWriter)
                    {
                        string xamlText =
                            "<Span xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +
                            "<InlineUIContainer><Image " +
                            "Width=\"" +
                            bitmapSource.Width + "\" " +
                            "Height=\"" +
                            bitmapSource.Height + "\" " +
                            "><Image.Source><BitmapImage CacheOption=\"OnLoad\" UriSource=\"" +
                            imageReference +
                            "\"/></Image.Source></Image></InlineUIContainer></Span>";
                        xamlPartWriter.Write(xamlText);
                    }
                }

                // Add image to a package
                wpfPayload.CreateImagePart(xamlEntryPart, bitmapSource, imageContentType, imageIndex);
            }

            return(stream);
        }
Ejemplo n.º 8
0
        internal Stream CreateImageStream(int imageCount, string contentType, out string imagePartUriString)
        {
            // Generate a new unique image part name
            imagePartUriString = GetImageName(imageCount, contentType);

            // Add image part to the conntainer
            // Define an image part uri
            Uri imagePartUri = new Uri(XamlPayloadDirectory + imagePartUriString, UriKind.Relative);

            // Create a part for the image
            PackagePart imagePart = _package.CreatePart(imagePartUri, contentType, CompressionOption.NotCompressed);

            // Create the relationship referring from the enrty part to the image part
            //PackageRelationship entryRelationship = _currentXamlPart.CreateRelationship(imagePartUri, TargetMode.Internal, XamlRelationshipFromXamlPartToComponentPart);

            // Return relative name for the image part as out parameter
            imagePartUriString = GetImageReference(imagePartUriString);

            // Return a stream opened for writing an image data
            return(imagePart.GetSeekableStream());
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Move iterator to the next part that has an associated filter and (re)initialize the
        /// relevant filter.
        /// </summary>
        /// <remarks>
        /// This function results in _progress and _currentFilter being updated.
        /// </remarks>
        private void MoveToNextFilter()
        {
            // Reset _isInternalFilter.
            _isInternalFilter = false;

            switch (_progress)
            {
            case Progress.FilteringNotStarted:

                #region Progress.FilteringNotStarted

                // Filtering not started yet. Start with core properties filter.

                IndexingFilterMarshaler corePropertiesFilterMarshaler
                    = new IndexingFilterMarshaler(
                          new CorePropertiesFilter(_package.PackageProperties));

                // Avoid exception on end of chunks from part filter.
                corePropertiesFilterMarshaler.ThrowOnEndOfChunks = false;

                _currentFilter = corePropertiesFilterMarshaler;
                _currentFilter.Init(_grfFlags, _cAttributes, _aAttributes);
                _isInternalFilter = true;

                // Update progress to indicate filtering core properties.
                _progress = Progress.FilteringCoreProperties;

                break;

                #endregion Progress.FilteringNotStarted

            case Progress.FilteringCoreProperties:

                #region Progress.FilteringCoreProperties

                // Core properties were being filtered. Next move to content filtering.

                #endregion Progress.FilteringCoreProperties

            case Progress.FilteringContent:

                #region Progress.FilteringContent

                //
                // Content being filtered. Move to next content part filter if it exists.
                // Update progress to indicate filtering content if there is a next content
                // filter, else to indicate filtering is completed.
                //

                if (_currentStream != null)
                {
                    // Close the stream for the previous PackagePart.
                    _currentStream.Close();
                    _currentStream = null;
                }

                for (_currentFilter = null; _partIterator.MoveNext(); _currentFilter = null)
                {
                    PackagePart currentPart = (PackagePart)_partIterator.Current;
                    ContentType contentType = currentPart.ValidatedContentType();

                    // Find the filter's CLSID based on the MIME content type.
                    string filterClsid = GetFilterClsid(contentType, currentPart.Uri);
                    if (filterClsid != null)
                    {
                        _currentFilter = GetFilterFromClsid(new Guid(filterClsid));
                        if (_currentFilter != null)
                        {
                            _currentStream = currentPart.GetSeekableStream();
                            ManagedIStream stream = new ManagedIStream(_currentStream);
                            try
                            {
                                IPersistStreamWithArrays filterLoader = (IPersistStreamWithArrays)_currentFilter;
                                filterLoader.Load(stream);
                                _currentFilter.Init(_grfFlags, _cAttributes, _aAttributes);

                                // Filter found and properly initialized. Search is over.
                                break;
                            }
                            catch (InvalidCastException)
                            {
                                // If a filter does not implement IPersistStream, then, by design, it should
                                // be ignored.
                            }
                            catch (COMException)
                            {
                                // Any initialization bug giving rise to an exception in the initialization
                                // code should be ignored, since this will be due to faulty external code.
                            }
                            catch (IOException)
                            {
                                // Initialization problem can be reported as IOException. See preceding comment.
                            }
                        }
                    }

                    //
                    // No valid externally registered filters found for this content part.
                    // If this is xaml part, use the internal XamlFilter.
                    //

                    if (BindUriHelper.IsXamlMimeType(contentType))
                    {
                        if (_currentStream == null)
                        {
                            _currentStream = currentPart.GetSeekableStream();
                        }

                        IndexingFilterMarshaler xamlFilterMarshaler
                            = new IndexingFilterMarshaler(new XamlFilter(_currentStream));

                        // Avoid exception on end of chunks from part filter.
                        xamlFilterMarshaler.ThrowOnEndOfChunks = false;

                        _currentFilter = xamlFilterMarshaler;
                        _currentFilter.Init(_grfFlags, _cAttributes, _aAttributes);
                        _isInternalFilter = true;

                        // Filter found and properly initialized. Search is over.
                        break;
                    }

                    if (_currentStream != null)
                    {
                        _currentStream.Close();
                        _currentStream = null;
                    }
                }

                if (_currentFilter == null)
                {
                    // Update progress to indicate filtering is completed.
                    _progress = Progress.FilteringCompleted;
                }
                else
                {
                    // Tell GetChunk that we are getting input from a new filter.
                    _firstChunkFromFilter = true;

                    // Update progress to indicate content being filtered.
                    _progress = Progress.FilteringContent;
                }
                break;

                #endregion Progress.FilteringContent

            case Progress.FilteringCompleted:

                #region Progress.FilteringCompleted

                Debug.Assert(false);
                break;

                #endregion Progress.FilteringCompleted

            default:

                #region Default

                Debug.Assert(false);
                break;

                #endregion Default
            }
        }