Пример #1
0
 private static void InitWPFResourcesSystem()
 {
     // Hinky stuff to get the resource dictionary working
     PackUriHelper.Create(new Uri("reliable://0"));
     new FrameworkElement();
     Application.ResourceAssembly = typeof(App).Assembly;
 }
        private static Uri GetStructureUriFromRelationship(Uri contentUri, string relationshipName)
        {
            Uri result = null;

            if (contentUri != null && relationshipName != null)
            {
                Uri partUri = PackUriHelper.GetPartUri(contentUri);
                if (partUri != null)
                {
                    Uri     packageUri = PackUriHelper.GetPackageUri(contentUri);
                    Package package    = PreloadedPackages.GetPackage(packageUri);
                    if (package == null && SecurityHelper.CheckEnvironmentPermission())
                    {
                        package = PackageStore.GetPackage(packageUri);
                    }
                    if (package != null)
                    {
                        PackagePart part = package.GetPart(partUri);
                        PackageRelationshipCollection relationshipsByType = part.GetRelationshipsByType(relationshipName);
                        Uri uri = null;
                        foreach (PackageRelationship packageRelationship in relationshipsByType)
                        {
                            uri = PackUriHelper.ResolvePartUri(partUri, packageRelationship.TargetUri);
                        }
                        if (uri != null)
                        {
                            result = PackUriHelper.Create(packageUri, uri);
                        }
                    }
                }
            }
            return(result);
        }
Пример #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      = PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part
                    Uri packageUri        = 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.GetStream(), parserContext);

                    // 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);
        }
        static int _wpfPayloadCount;     // used to disambiguate between all acts of loading from different WPF payloads.


        internal static object LoadElement(Stream stream)
        {
            Package    package    = Package.Open(stream, FileMode.Open, FileAccess.Read);
            WpfPayload wpfPayload = new WpfPayload(package);

            PackagePart xamlEntryPart = wpfPayload.GetWpfEntryPart();


            int newWpfPayoutCount = _wpfPayloadCount++;
            Uri payloadUri        = new Uri("payload://wpf" + newWpfPayoutCount, UriKind.Absolute);
            Uri entryPartUri      = PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part
            Uri packageUri        = PackUriHelper.GetPackageUri(entryPartUri);           // extracts package uri from combined package+part uri

            PackageStore.AddPackage(packageUri, wpfPayload.Package);                     // Register the package
            ParserContext parserContext = new ParserContext();

            parserContext.BaseUri = entryPartUri;

            object xamlObject = XamlReader.Load(xamlEntryPart.GetStream(), parserContext);

            // Remove the temporary uri from the PackageStore
            PackageStore.RemovePackage(packageUri);

            return(xamlObject);
        }
Пример #5
0
 public void Setup()
 {
     a = PackUriHelper.Create(new Uri("http://www.test.com/pack1.pkg"));
     b = PackUriHelper.Create(new Uri("http://www.test.com/pack2.pkg"));
     Console.WriteLine("A is: {0}", a);
     Console.WriteLine("B is: {0}", b);
 }
Пример #6
0
        public void RoundTripTest(Stream originalStream, XamlWriterMode expressionMode, bool attemptDisplay)
        {
            if (originalStream == null)
            {
                throw new ArgumentNullException("originalStream");
            }

            Dispatcher dispatcher = Dispatcher.CurrentDispatcher;


            if (dispatcher == null)
            {
                throw new InvalidOperationException("The current thread has not entered a Dispatcher.");
            }

            object firstTreeRoot = null;

            //
            // Parse original xaml.
            // We create a ParserContext here. It will be reused by subsequent parsing
            // operations.
            //

            GlobalLog.LogStatus("Constructing object tree using LoadXml...");
            _parserContext         = new ParserContext();
            _parserContext.BaseUri = PackUriHelper.Create(new Uri("siteoforigin://"));
            firstTreeRoot          = ParseXaml(originalStream);

            RoundTripTestObject(firstTreeRoot, expressionMode, attemptDisplay);
        }
Пример #7
0
        }// end:GetPackage()

        // ------------------------ GetFixedDocument --------------------------
        /// <summary>
        ///   Returns the fixed document at a given URI within
        ///   the currently open XPS package.</summary>
        /// <param name="fixedDocUri">
        ///   The URI of the fixed document to return.</param>
        /// <returns>
        ///   The fixed document at a given URI
        ///   within the current XPS package.</returns>
        private FixedDocument GetFixedDocument(Uri fixedDocUri)
        {
            FixedDocument fixedDocument = null;

            // Create the URI for the fixed document within the package. The URI
            // is used to set the Parser context so fonts & other items can load.
            Uri           tempUri       = new Uri(_xpsDocumentPath, UriKind.RelativeOrAbsolute);
            ParserContext parserContext = new ParserContext();

            parserContext.BaseUri = PackUriHelper.Create(tempUri);

            // Retrieve the fixed document.
            PackagePart fixedDocPart = _xpsPackage.GetPart(fixedDocUri);

            if (fixedDocPart != null)
            {
                object fixedObject =
                    XamlReader.Load(fixedDocPart.GetStream(), parserContext);
                if (fixedObject != null)
                {
                    fixedDocument = fixedObject as FixedDocument;
                }
            }

            return(fixedDocument);
        }// end:GetFixedDocument()
Пример #8
0
 static BaseUriHelper()
 {
     _siteOfOriginBaseUri = PackUriHelper.Create(new Uri("SiteOfOrigin://"));
     _packAppBaseUri      = PackUriHelper.Create(new Uri("application://"));
     BaseUriProperty      = DependencyProperty.RegisterAttached("BaseUri", typeof(Uri), typeof(BaseUriHelper), new PropertyMetadata((object)null));
     _baseUri             = new MS.Internal.SecurityCriticalDataForSet <Uri>(_packAppBaseUri);
     PreloadedPackages.AddPackage(PackUriHelper.GetPackageUri(SiteOfOriginBaseUri), new SiteOfOriginContainer(), true);
 }
        /// <summary>Creates a Pack URI for a content file.</summary>
        /// <param name="assemblyName">
        ///   The assembly name where the content resides.
        /// </param>
        /// <param name="path">The relative pack URI of the file.</param>
        /// <returns>An absolute content file Pack URI.</returns>
        public static Uri MakeContentPackUri(AssemblyName assemblyName, string path)
        {
            var name = FormatName(assemblyName);

            return(PackUriHelper.Create(
                       ContentFileAuthority,
                       new Uri($"/{name};component/{path}", UriKind.Relative)));
        }
Пример #10
0
        public void Setup()
        {
            PackUriHelper.Create(new Uri("someuri://0"));
            new FrameworkElement();
            System.Windows.Application.ResourceAssembly = typeof(App).Assembly;

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
Пример #11
0
        public Tests()
        {
            PackUriHelper.Create(new Uri("http://example.com"));

            var asm = Assembly.GetExecutingAssembly();

            assetPath = Path.GetDirectoryName(asm.Location);
            baseUri   = new Uri($"pack://application:,,,/{asm.GetName().Name};Component/");
        }
Пример #12
0
 public static Uri ToPackUri(this string relativePath)
 {
     if (!relativePath.StartsWith("/"))
     {
         relativePath = "/" + relativePath;
     }
     return(PackUriHelper.Create(new Uri("application:///"),
                                 new Uri(relativePath, UriKind.Relative)));
 }
Пример #13
0
        /////////////////////////////////////////////////////////////////////////////////////////////////////
        #region NON-PUBLIC PROCEDURES
        /////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Gets an absolute pack URI for the assembly resource identified by <paramref name="relativeUri"/>.
        /// </summary>
        /// <param name="relativeUri">The relative path to the resource.</param>
        /// <returns></returns>
        private static Uri GetResourceUri(Uri relativeUri)
        {
            if (relativeUri.IsAbsoluteUri)
            {
                throw new ArgumentException("value must be a relative URI", "relativeUri");
            }
            return(PackUriHelper.Create(
                       new Uri("application:///", UriKind.Absolute),
                       new Uri("/" + Assembly.GetExecutingAssembly().GetName().Name + ";component" + relativeUri, UriKind.Relative)));
        }
Пример #14
0
        public void GetPartUriTest()
        {
            var pack      = PackUriHelper.Create(new Uri("http://www.test.com/pack1.pkg"));
            var part      = new Uri("/main.html", UriKind.Relative);
            var pack_part = new Uri(@"pack://pack:,,http:%2C%2Cwww.test.com%2Cpack1.pkg,/main.html");

            Assert.IsNull(PackUriHelper.GetPartUri(pack), "#1");
            Assert.AreEqual(pack_part, PackUriHelper.Create(pack, part), "#2");
            Assert.AreEqual(part, PackUriHelper.GetPartUri(PackUriHelper.Create(pack, part)), "#3");
        }
Пример #15
0
        public Uri CreatePart(Stream stream, string contentType)
        {
            var partUri = new Uri("/stream" + (++this.partCounter) + ".ttf", UriKind.Relative);

            var part = this.package.CreatePart(partUri, contentType);

            using (var partStream = part.GetStream())
                CopyStream(stream, partStream);

            // Each packUri must be globally unique because WPF might perform some caching based on it.
            return(PackUriHelper.Create(this.packageUri, partUri));
        }
Пример #16
0
        /// <summary>
        /// Using PackWebRequest to retrieve the photo from photo package on
        /// archive server.
        /// </summary>
        /// <param name="packageUri">
        /// Absolute Uri of the photo package on archive server.
        /// </param>
        /// <param name="partUri">
        /// Part Uri of the photo in the photo package.
        /// </param>
        /// <returns>
        /// WebResponse that has the stream of requested photo image.
        /// </returns>
        private static WebResponse PackWebRequestForPhotoPart(Uri packageUri,
                                                              Uri partUri)
        {
            Uri fullUri = PackUriHelper.Create(packageUri, partUri);

            Console.WriteLine("Pack URI= " + fullUri);

            // Create PackWebRequest.
            WebRequest request = _webRequestCreate.Create(fullUri);

            return(request.GetResponse());
        }
Пример #17
0
 public void CreateTest()
 {
     Assert.AreEqual("pack://http:,,www.test.com,pack.pkg/",
                     PackUriHelper.Create(new Uri("http://www.test.com/pack.pkg")).ToString(), "#1");
     Assert.AreEqual("pack://http:,,www.test.com,pack.pkg/",
                     PackUriHelper.Create(new Uri("http://www.test.com/pack.pkg"), null, null).ToString(), "#2");
     Assert.AreEqual("pack://http:,,www.test.com,pack.pkg/main.html#frag",
                     PackUriHelper.Create(new Uri("http://www.test.com/pack.pkg"),
                                          new Uri("/main.html", UriKind.Relative), "#frag").ToString(), "#3");
     Assert.AreEqual("pack://http:,,www.test.com,pack.pkg/main.html#frag",
                     PackUriHelper.Create(new Uri("http://www.test.com/pack.pkg"),
                                          new Uri("/main.html", UriKind.Relative), "#frag").ToString(), "#3");
 }
Пример #18
0
        public Uri CreatePart(Stream stream, string contentType = "application/octet-stream")
        {
            var partUri = new Uri("/stream" + ++partCounter, UriKind.Relative);

            var part = package.CreatePart(partUri, contentType);

            Debug.Assert(part != null, "part != null");
            using (var partStream = part.GetStream())
                CopyStream(stream, partStream);

            // Each packUri must be globally unique because WPF might perform some caching based on it.
            return(PackUriHelper.Create(this.packageUri, partUri));
        }
        /// <summary>
        /// Pack Uri's are not recognized untill they have been registered in the appl domain
        /// This method makes sure pack Uri's do no throw an exception regarding incorrect port.
        /// </summary>
        private void SetupRecognizePackUir()
        {
            PackUriHelper.Create(new Uri("reliable://0"));
            new FrameworkElement();

            try
            {
                Application.ResourceAssembly = typeof(AddinRibbonPart).Assembly;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public void TestConvert()
        {
            PackUriHelper.Create(new Uri("reliable://0"));
            //new FrameworkElement();
            var converter = new LogLevelImageConverter();

            var im = converter.Convert("Info", null, null, null);

            Assert.IsNotNull(im);

            im = converter.Convert("Warn", null, null, null);
            Assert.IsNotNull(im);

            im = converter.Convert("Error", null, null, null);
            Assert.IsNotNull(im);
        }
Пример #21
0
        // Token: 0x06003F20 RID: 16160 RVA: 0x0012075C File Offset: 0x0011E95C
        internal static object LoadElement(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            object result;

            try
            {
                WpfPayload wpfPayload = WpfPayload.OpenWpfPayload(stream);
                using (wpfPayload.Package)
                {
                    PackagePart packagePart = wpfPayload.ValidatePayload();
                    int         num         = Interlocked.Increment(ref WpfPayload._wpfPayloadCount);
                    Uri         packageUri  = new Uri("payload://wpf" + num, UriKind.Absolute);
                    Uri         uri         = PackUriHelper.Create(packageUri, packagePart.Uri);
                    Uri         packageUri2 = PackUriHelper.GetPackageUri(uri);
                    PackageStore.AddPackage(packageUri2, wpfPayload.Package);
                    ParserContext parserContext = new ParserContext();
                    parserContext.BaseUri = uri;
                    bool useRestrictiveXamlReader = !Clipboard.UseLegacyDangerousClipboardDeserializationMode();
                    result = XamlReader.Load(packagePart.GetStream(), parserContext, useRestrictiveXamlReader);
                    PackageStore.RemovePackage(packageUri2);
                }
            }
            catch (XamlParseException ex)
            {
                Invariant.Assert(ex != null);
                result = null;
            }
            catch (FileFormatException)
            {
                result = null;
            }
            catch (FileLoadException)
            {
                result = null;
            }
            catch (OutOfMemoryException)
            {
                result = null;
            }
            return(result);
        }
Пример #22
0
 private void RegisterFonts()
 {
     foreach (KeyValuePair <string, byte[]> fontFile in ChapterContent.Fonts)
     {
         MemoryStream packageStream = new MemoryStream();
         Package      package       = Package.Open(packageStream, FileMode.Create, FileAccess.ReadWrite);
         Uri          packageUri    = new Uri(fontFile.Key + ":");
         PackageStore.AddPackage(packageUri, package);
         Uri         packPartUri = new Uri("/content", UriKind.Relative);
         PackagePart packPart    = package.CreatePart(packPartUri, "font/content");
         packPart.GetStream().Write(fontFile.Value, 0, fontFile.Value.Length);
         Uri fontUri = PackUriHelper.Create(packageUri, packPart.Uri);
         foreach (FontFamily fontFamilty in System.Windows.Media.Fonts.GetFontFamilies(fontUri))
         {
             HtmlRender.AddFontFamily(fontFamilty);
         }
     }
     areFontsRegistered = true;
 }
Пример #23
0
 private void CheckUri(string localName, string attr)
 {
     if (!object.ReferenceEquals(attr, _lastAttr))      // Check for same string object, not for equality!
     {
         _lastAttr = attr;
         string [] uris = _schema.ExtractUriFromAttr(localName, attr);
         if (uris != null)
         {
             foreach (string uriAttr in uris)
             {
                 if (uriAttr.Length > 0)
                 {
                     Uri targetUri    = PackUriHelper.ResolvePartUri(_baseUri, new Uri(uriAttr, UriKind.Relative));
                     Uri absTargetUri = PackUriHelper.Create(_packageUri, targetUri);
                     _loader.UriHitHandler(_node, absTargetUri);
                 }
             }
         }
     }
 }
 // Token: 0x06008483 RID: 33923 RVA: 0x00248558 File Offset: 0x00246758
 private void CheckUri(string localName, string attr)
 {
     if (attr != this._lastAttr)
     {
         this._lastAttr = attr;
         string[] array = this._schema.ExtractUriFromAttr(localName, attr);
         if (array != null)
         {
             foreach (string text in array)
             {
                 if (text.Length > 0)
                 {
                     Uri partUri = PackUriHelper.ResolvePartUri(this._baseUri, new Uri(text, UriKind.Relative));
                     Uri uri     = PackUriHelper.Create(this._packageUri, partUri);
                     this._loader.UriHitHandler(this._node, uri);
                 }
             }
         }
     }
 }
Пример #25
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            IList  list     = SpellCheck.GetCustomDictionaries(textBox);
            string fileName = "customwords.lex";

            System.IO.StreamReader file = new System.IO.StreamReader(fileName);
            string        line;
            StringBuilder sb = new StringBuilder();

            while ((line = file.ReadLine()) != null)
            {
                System.Console.WriteLine(line);
                sb.Append(line);
                sb.Append("\r\n");
            }

            // Create in-memory Package to store custom dictionary
            UTF8Encoding encoding = new UTF8Encoding();
            var          bytes    = encoding.GetBytes(sb.ToString());

            MemoryStream stream  = new MemoryStream();
            Package      pack    = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);
            Uri          packUri = new Uri("SpellCheckDictionary:");

            PackageStore.RemovePackage(packUri);
            PackageStore.AddPackage(packUri, pack);
            Uri         packPartUri = new Uri("/Content", UriKind.Relative);
            PackagePart packPart    = pack.CreatePart(packPartUri, "text/plain");

            if (packPart != null)
            {
                Stream packageStream = packPart.GetStream();
                packageStream.Write(bytes, 0, bytes.Length);
                packageStream.Close();
                spellUri = PackUriHelper.Create(packUri, packPart.Uri);
            }

            textBox.SpellCheck.CustomDictionaries.Clear();
            textBox.SpellCheck.CustomDictionaries.Add(spellUri);
        }
Пример #26
0
        public void Setup()
        {
            MockDeploymentRepositoryAdapter = new Mock <IDeploymentRepositoryAdapter>();
            MockConnectionTester            = new Mock <IConnectionTester>();
            MockConnectionTester.Setup(m => m.Test()).ReturnsAsync((true, String.Empty));

            MockContainer = new MockContainer
            {
                MockDeploymentRepositoryAdapter = MockDeploymentRepositoryAdapter,
                MockConnectionTester            = MockConnectionTester,
            };

            // Set the server URL so the settings command isn't run
            Properties.Settings.Default.ServerUrl = "http://localhost";

            Container.Current = MockContainer;
            Container.Current.Configure();

            PackUriHelper.Create(new Uri("reliable://0"));
            new FrameworkElement();
            Application.ResourceAssembly = typeof(App).Assembly;
        }
 internal void Cleanup()
 {
     if (Application.Current != null)
     {
         IBrowserCallbackServices browserCallbackServices = Application.Current.BrowserCallbackServices;
         if (browserCallbackServices != null)
         {
             Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new DispatcherOperationCallback(this.ReleaseBrowserCallback), browserCallbackServices);
         }
     }
     this.ServiceProvider = null;
     this.ClearRootBrowserWindow();
     if (this._storageRoot != null && this._storageRoot.Value != null)
     {
         this._storageRoot.Value.Close();
     }
     if (this._document.Value is PackageDocument)
     {
         PreloadedPackages.RemovePackage(PackUriHelper.GetPackageUri(PackUriHelper.Create(this.Uri)));
         ((PackageDocument)this._document.Value).Dispose();
         this._document.Value = null;
     }
     if (this._mimeType.Value == MimeType.Document)
     {
         DocumentManager.CleanUp();
     }
     if (this._packageStream.Value != null)
     {
         this._packageStream.Value.Close();
     }
     if (this._unmanagedStream.Value != null)
     {
         Marshal.ReleaseComObject(this._unmanagedStream.Value);
         this._unmanagedStream = new SecurityCriticalData <object>(null);
     }
 }
Пример #28
0
        public bool OpenEncryptedDocument(string xpsFile)
        {
            // Check to see if the document is encrypted.
            // If not encrypted, use OpenDocument().
            if (!EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(xpsFile))
                return OpenDocument(xpsFile);

            ShowStatus("Opening encrypted '" + Filename(xpsFile) + "'");

            // Get the ID of the current user log-in.
            string currentUserId;
            try
                { currentUserId = GetDefaultWindowsUserName(); }
            catch
                { currentUserId = null; }
            if (currentUserId == null)
            {
                MessageBox.Show("No valid user ID available", "Invalid User ID",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                ShowStatus("   No valid user ID available.");
                return false;
            }

            ShowStatus("   Current user ID:  '" + currentUserId + "'");
            ShowStatus("   Using " + _authentication + " authentication.");
            ShowStatus("   Checking rights list for user:\n       " +
                           currentUserId);
            ShowStatus("   Initializing the environment.");

            try
            {
                string applicationManifest = "<manifest></manifest>";
                if (File.Exists("rvc.xml"))
                {
                    ShowStatus("   Reading manifest 'rvc.xml'.");
                    StreamReader manifestReader = File.OpenText("rvc.xml");
                    applicationManifest = manifestReader.ReadToEnd();
                }

                ShowStatus("   Initiating SecureEnvironment as user: \n       " +
                    currentUserId + " [" + _authentication + "]");
                if (SecureEnvironment.IsUserActivated(
                    new ContentUser(currentUserId, _authentication)))
                {
                    ShowStatus("   User is already activated.");
                    _secureEnv = SecureEnvironment.Create(applicationManifest,
                                    new ContentUser(currentUserId, _authentication));
                }
                else // if user is not yet activated.
                {
                    ShowStatus("   User is NOT activated,\n       activating now....");
                    // If using the current Windows user, no credentials are
                    // required and we can use UserActivationMode.Permanent.
                    _secureEnv = SecureEnvironment.Create(applicationManifest,
                                    _authentication, UserActivationMode.Permanent);

                    // If not using the current Windows user, use
                    // UserActivationMode.Temporary to display the Windows
                    // credentials pop-up window.
                    ///_secureEnv = SecureEnvironment.Create(applicationManifest,
                    ///     a_authentication, UserActivationMode.Temporary);
                }
                ShowStatus("   Created SecureEnvironment for user:\n       " +
                    _secureEnv.User.Name +
                    " [" + _secureEnv.User.AuthenticationType + "]");

                ShowStatus("   Opening the encrypted Package.");
                EncryptedPackageEnvelope ePackage =
                    EncryptedPackageEnvelope.Open(xpsFile, FileAccess.ReadWrite);
                RightsManagementInformation rmi =
                    ePackage.RightsManagementInformation;

                ShowStatus("   Looking for an embedded UseLicense for user:\n       " +
                           currentUserId + " [" + _authentication + "]");
                UseLicense useLicense =
                    rmi.LoadUseLicense(
                        new ContentUser(currentUserId, _authentication));

                ReadOnlyCollection<ContentGrant> grants;
                if (useLicense == null)
                {
                    ShowStatus("   No Embedded UseLicense found.\n       " +
                               "Attempting to acqure UseLicnese\n       " +
                               "from the PublishLicense.");
                    PublishLicense pubLicense = rmi.LoadPublishLicense();

                    ShowStatus("   Referral information:");

                    if (pubLicense.ReferralInfoName == null)
                        ShowStatus("       Name: (null)");
                    else
                        ShowStatus("       Name: " + pubLicense.ReferralInfoName);

                    if (pubLicense.ReferralInfoUri == null)
                        ShowStatus("    Uri: (null)");
                    else
                        ShowStatus("    Uri: " +
                            pubLicense.ReferralInfoUri.ToString());

                    useLicense = pubLicense.AcquireUseLicense(_secureEnv);
                    if (useLicense == null)
                    {
                        ShowStatus("   User DOES NOT HAVE RIGHTS\n       " +
                            "to access this document!");
                        return false;
                    }
                }// end:if (useLicense == null)
                ShowStatus("   UseLicense acquired.");

                ShowStatus("   Binding UseLicense with the SecureEnvironment" +
                         "\n       to obtain the CryptoProvider.");
                rmi.CryptoProvider = useLicense.Bind(_secureEnv);

                ShowStatus("   Obtaining BoundGrants.");
                grants = rmi.CryptoProvider.BoundGrants;

                // You can access the Package via GetPackage() at this point.

                rightsBlock.Text = "GRANTS LIST\n-----------\n";
                foreach (ContentGrant grant in grants)
                {
                    rightsBlock.Text += "USER  :"******" [" +
                        grant.User.AuthenticationType + "]\n";
                    rightsBlock.Text += "RIGHT :" + grant.Right.ToString()+"\n";
                    rightsBlock.Text += "    From:  " + grant.ValidFrom + "\n";
                    rightsBlock.Text += "    Until: " + grant.ValidUntil + "\n";
                }

                if (rmi.CryptoProvider.CanDecrypt == true)
                    ShowStatus("   Decryption granted.");
                else
                    ShowStatus("   CANNOT DECRYPT!");

                ShowStatus("   Getting the Package from\n" +
                           "      the EncryptedPackage.");
                _xpsPackage = ePackage.GetPackage();
                if (_xpsPackage == null)
                {
                    MessageBox.Show("Unable to get Package.");
                    return false;
                }

                // Set a PackageStore Uri reference for the encrypted stream.
                // ("sdk://packLocation" is a pseudo URI used by
                //  PackUriHelper.Create to define the parserContext.BaseURI
                //  that XamlReader uses to access the encrypted data stream.)
                Uri packageUri = new Uri(@"sdk://packLocation", UriKind.Absolute);
                // Add the URI package
                PackageStore.AddPackage(packageUri, _xpsPackage);
                // Determine the starting part for the package.
                PackagePart startingPart = GetPackageStartingPart(_xpsPackage);

                // Set the DocViewer.Document property.
                ShowStatus("   Opening in DocumentViewer.");
                ParserContext parserContext = new ParserContext();
                parserContext.BaseUri = PackUriHelper.Create(
                                            packageUri, startingPart.Uri);
                parserContext.XamlTypeMapper = XamlTypeMapper.DefaultMapper;
                DocViewer.Document = XamlReader.Load(
                    startingPart.GetStream(), parserContext)
                        as IDocumentPaginatorSource;

                // Enable document menu controls.
                menuFileClose.IsEnabled = true;
                menuFilePrint.IsEnabled = true;
                menuViewIncreaseZoom.IsEnabled = true;
                menuViewDecreaseZoom.IsEnabled = true;

                // Give the DocumentViewer focus.
                DocViewer.Focus();
            }// end:try
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                    ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                    "Exception",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            this.Title = "RightsManagedPackageViewer SDK Sample - " +
                         Filename(xpsFile) + " (encrypted)";
            return true;
        }// end:OpenEncryptedDocument()
Пример #29
0
        public override void ValidateRelationships(SecurityCriticalData <Package> package, Uri packageUri, Uri partUri, ContentType mimeType)
        {
            PackagePart part = package.Value.GetPart(partUri);
            PackageRelationshipCollection checkRels;
            int count;

            // Can only have 0 or 1 PrintTicket per FDS, FD or FP part
            checkRels = part.GetRelationshipsByType(_printTicketRel);
            count     = 0;
            foreach (PackageRelationship rel in checkRels)
            {
                count++;
                if (count > 1)
                {
                    throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOnePrintTicketPart));
                }

                // Also check for existence and type
                Uri targetUri    = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
                Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);

                PackagePart targetPart = package.Value.GetPart(targetUri);

                if (!_printTicketContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
                {
                    throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderPrintTicketHasIncorrectType));
                }
            }

            checkRels = part.GetRelationshipsByType(_thumbnailRel);
            count     = 0;
            foreach (PackageRelationship rel in checkRels)
            {
                count++;
                if (count > 1)
                {
                    throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneThumbnailPart));
                }

                // Also check for existence and type
                Uri targetUri    = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
                Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);

                PackagePart targetPart = package.Value.GetPart(targetUri);

                if (!_jpgContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) &&
                    !_pngContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
                {
                    throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderThumbnailHasIncorrectType));
                }
            }

            // FixedDocument only has restricted font relationships
            if (_fixedDocumentContentType.AreTypeAndSubTypeEqual(mimeType))
            {
                // Check if target of restricted font relationship is present and is actually a font
                checkRels = part.GetRelationshipsByType(_restrictedFontRel);
                foreach (PackageRelationship rel in checkRels)
                {
                    // Check for existence and type
                    Uri targetUri    = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
                    Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);

                    PackagePart targetPart = package.Value.GetPart(targetUri);

                    if (!_fontContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) &&
                        !_obfuscatedContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderRestrictedFontHasIncorrectType));
                    }
                }
            }

            // check constraints for XPS fixed payload start part
            if (_fixedDocumentSequenceContentType.AreTypeAndSubTypeEqual(mimeType))
            {
                // This is the XPS payload root part. We also should check if the Package only has at most one discardcontrol...
                checkRels = package.Value.GetRelationshipsByType(_discardControlRel);
                count     = 0;
                foreach (PackageRelationship rel in checkRels)
                {
                    count++;
                    if (count > 1)
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneDiscardControlInPackage));
                    }

                    // Also check for existence and type
                    Uri targetUri    = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
                    Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);

                    PackagePart targetPart = package.Value.GetPart(targetUri);

                    if (!_discardControlContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderDiscardControlHasIncorrectType));
                    }
                }

                // This is the XPS payload root part. We also should check if the Package only has at most one thumbnail...
                checkRels = package.Value.GetRelationshipsByType(_thumbnailRel);
                count     = 0;
                foreach (PackageRelationship rel in checkRels)
                {
                    count++;
                    if (count > 1)
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneThumbnailInPackage));
                    }

                    // Also check for existence and type
                    Uri targetUri    = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
                    Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);

                    PackagePart targetPart = package.Value.GetPart(targetUri);

                    if (!_jpgContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) &&
                        !_pngContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderThumbnailHasIncorrectType));
                    }
                }
            }
        }
Пример #30
0
 public void Init()
 {
     PackUriHelper.Create(new Uri("reliable://0"));
     Application.LoadComponent(
         new Uri("/KBS2;component/App.xaml", UriKind.Relative));
 }