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);
        }
示例#2
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // Getting a Stream out of the Resource file, strDocument
            string strDocument   = "View.Help.legendgenerator_english.xps";
            string strSchemaPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "." + strDocument;
            Stream stream        = Assembly.GetExecutingAssembly().GetManifestResourceStream(strSchemaPath);
            // Getting the length of the Stream we just obtained
            int length = (int)stream.Length;
            // Setting up a new MemoryStream and Byte Array
            MemoryStream ms = new MemoryStream();

            ms.Capacity = (int)length;
            byte[] buffer = new byte[length];
            // Copying the Stream to the Byte Array (Buffer)
            stream.Read(buffer, 0, length);
            // Copying the Byte Array (Buffer) to the MemoryStream
            ms.Write(buffer, 0, length);
            // Setting up a new Package based on the MemoryStream
            Package pkg = Package.Open(ms);
            // Putting together a Uri for the Package using the document name (strDocument)
            string strMemoryPackageName = string.Format("memorystream://{0}.xps", "legendgenerator_english.xps");
            Uri    packageUri           = new Uri(strMemoryPackageName);

            // Adding the Package to PackageStore using the Uri
            if (PackageStore.GetPackage(packageUri) == null)
            {
                PackageStore.AddPackage(packageUri, pkg);
            }
            // Finally, putting together the XpsDocument
            doc = new XpsDocument(pkg, CompressionOption.Maximum, strMemoryPackageName);
            // Feeding the DocumentViewer, which was declared at Design Time as a variable called "viewer"
            documentViewer1.Document = doc.GetFixedDocumentSequence();
            documentViewer1.FitToWidth();
            documentViewer1.FitToHeight();
        }
示例#3
0
        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            doc = new XpsDocument("ch19.xps", FileAccess.ReadWrite);
            docViewer.Document = doc.GetFixedDocumentSequence();

            service = AnnotationService.GetService(docViewer);
            if (service == null)
            {
                Uri         annotationUri  = PackUriHelper.CreatePartUri(new Uri("AnnotationStream", UriKind.Relative));
                Package     package        = PackageStore.GetPackage(doc.Uri);
                PackagePart annotationPart = null;
                if (package.PartExists(annotationUri))
                {
                    annotationPart = package.GetPart(annotationUri);
                }
                else
                {
                    annotationPart = package.CreatePart(annotationUri, "Annotations/Stream");
                }

                // Load annotations from the package.
                AnnotationStore store = new XmlStreamStore(annotationPart.GetStream());
                service = new AnnotationService(docViewer);
                service.Enable(store);
            }
        }
示例#4
0
        public ejpXpsDocument(string path, string title, bool isExternalToAssignment,
                              Guid xpsDocumentId, Guid parentStudyId)
        {
            this._isExternalToAssignment = isExternalToAssignment;

            if (!File.Exists(path))
            {
                throw new IOException(Application.Current.Resources["EX_Fnf_XPSNotFound"] as string);                //Properties.Resources.EX_Fnf_XPSNotFound);
            }
            this._xpsDocumentPath = path;
            this._packageUri      = new Uri(path, UriKind.Absolute);

            try
            {
                this._xpsDocument = new XpsDocument(path, FileAccess.ReadWrite);

                FileInfo fi = new FileInfo(path);
                this._xpsDocument.CoreDocumentProperties.Title      = title;
                this._xpsDocument.CoreDocumentProperties.Identifier = xpsDocumentId.ToString();

                this._xpsPackage = PackageStore.GetPackage(this._packageUri);
                if ((this._xpsPackage == null) || (this._xpsDocument == null))
                {
                    throw new Exception(Application.Current.Resources["EX_Fnf_XPSNotFound"] as string);                    //Properties.Resources.EX_Fnf_XPSNotFound);
                }
                this.GetFixedDocumentSequenceUri();
            }
            catch (Exception)
            {
            }
        }        // end:Constructor()
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageId, "No package ID was specified. Please pass --packageId YourPackage");
            Guard.NotNullOrWhiteSpace(packageVersion, "No package version was specified. Please pass --packageVersion 1.0.0.0");
            Guard.NotNullOrWhiteSpace(packageHash, "No package hash was specified. Please pass --packageHash YourPackageHash");

            var fileSystem        = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
            var commandLineRunner = new CommandLineRunner(
                new SplitCommandOutput(
                    new ConsoleCommandOutput(),
                    new ServiceMessageCommandOutput(
                        new CalamariVariableDictionary())));

            NuGetVersion version;

            if (!NuGetVersion.TryParse(packageVersion, out version))
            {
                throw new CommandException(String.Format("Package version '{0}' is not a valid Semantic Version", packageVersion));
            }

            var packageStore = new PackageStore(
                new GenericPackageExtractorFactory().createJavaGenericPackageExtractor(fileSystem));
            var packageMetadata = new ExtendedPackageMetadata()
            {
                Id = packageId, Version = packageVersion, Hash = packageHash
            };
            var package = packageStore.GetPackage(packageMetadata);

            if (package == null)
            {
                Log.VerboseFormat("Package {0} version {1} hash {2} has not been uploaded.",
                                  packageMetadata.Id, packageMetadata.Version, packageMetadata.Hash);

                Log.VerboseFormat("Finding earlier packages that have been uploaded to this Tentacle.");
                var nearestPackages = packageStore.GetNearestPackages(packageId, version).ToList();
                if (!nearestPackages.Any())
                {
                    Log.VerboseFormat("No earlier packages for {0} has been uploaded", packageId);
                    return(0);
                }

                Log.VerboseFormat("Found {0} earlier {1} of {2} on this Tentacle",
                                  nearestPackages.Count, nearestPackages.Count == 1 ? "version" : "versions", packageId);
                foreach (var nearestPackage in nearestPackages)
                {
                    Log.VerboseFormat("  - {0}: {1}", nearestPackage.Metadata.Version, nearestPackage.FullPath);
                    Log.ServiceMessages.PackageFound(nearestPackage.Metadata.Id, nearestPackage.Metadata.Version, nearestPackage.Metadata.Hash, nearestPackage.Metadata.FileExtension, nearestPackage.FullPath);
                }

                return(0);
            }

            Log.VerboseFormat("Package {0} {1} hash {2} has already been uploaded", package.Metadata.Id, package.Metadata.Version, package.Metadata.Hash);
            Log.ServiceMessages.PackageFound(package.Metadata.Id, package.Metadata.Version, package.Metadata.Hash, package.Metadata.FileExtension, package.FullPath, true);
            return(0);
        }
示例#6
0
        public static void PrintPreview(Window owner, object data, bool IsSinglePage = false)
        {
            using (MemoryStream xpsStream = new MemoryStream())
            {
                using (Package package = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite))
                {
                    string packageUriString = "memorystream://data.xps";

                    Uri packageUri = new Uri(packageUriString);


                    if (PackageStore.GetPackage(packageUri) != null)
                    {
                        PackageStore.RemovePackage(packageUri);
                    }
                    PackageStore.AddPackage(packageUri, package);



                    XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.NotCompressed, packageUriString);

                    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);

                    // Form visual = new Form();



                    // PrintTicket printTicket = new PrintTicket();

                    //  printTicket.PageMediaSize = A4PaperSize;
                    // var d = PrintOnMultiPage(data, true);
                    //((IDocumentPaginatorSource)data).DocumentPaginator
                    if (!IsSinglePage)
                    {
                        writer.Write(PrintOnMultiPage(data, true));
                    }
                    else
                    {
                        writer.Write(Print((Visual)data, true));
                    }

                    FixedDocumentSequence document = xpsDocument.GetFixedDocumentSequence();

                    xpsDocument.Close();



                    PrintPreviewWindow printPreviewWnd = new PrintPreviewWindow(document);

                    printPreviewWnd.Owner = owner;

                    printPreviewWnd.ShowDialog();

                    PackageStore.RemovePackage(packageUri);
                }
            }
        }
示例#7
0
        //</SnippetDocViewAnnXpsDocPaginator>


        // ------------------------ GetAnnotationsPart ------------------------
        /// <summary>
        ///   Returns the part within an XPS document
        ///   for storing user annotations.</summary>
        /// <param name="documentUri">
        ///   The URI of the FixedDocumentSequence
        ///   within the package to annotate.</param>
        /// <returns>
        ///   The package part containing existing user annotations
        ///   and for storing new annotations.</returns>
        /// <remarks>
        ///   If the document package does not as yet contain an annotations
        ///   part, a new empty one is created and returned.</remarks>
        private PackagePart GetAnnotationPart(Uri documentUri)
        {
            // Open the document package.
            Package package = PackageStore.GetPackage(_packageUri);

            if (package == null)
            {
                throw new InvalidOperationException(
                          "The document package '" + _packageUri + "' does not exist.");
            }

            // Get the FixedDocumentSequence part from the package.
            PackagePart docPart = package.GetPart(documentUri);

            // Search through all the document relationships to find the
            // annotations relationship part (or null, of there is none).
            PackageRelationship annotRel = null;

            foreach (PackageRelationship rel in
                     docPart.GetRelationshipsByType(_annotRelsType))
            {
                annotRel = rel;
            }

            // If annotations relationship does not exist, create a new
            // annotations part along with a relationship part for it.
            PackagePart annotPart = null;

            if (annotRel == null)
            {
                // Create a new Annotations part.
                annotPart = package.CreatePart(PackUriHelper.CreatePartUri(
                                                   new Uri(_annotFile, UriKind.Relative)), _annotContentType);
                // Create a new relationship that points to the Annotations part.
                docPart.CreateRelationship(
                    annotPart.Uri, TargetMode.Internal, _annotRelsType);
            }

            // If an annotations relationship exists,
            // get the annotations part that it references.
            else // if (annotRel != null)
            {   // Get the Annotations part specified by the relationship.
                annotPart = package.GetPart(annotRel.TargetUri);
                if (annotPart == null)
                {
                    throw new InvalidOperationException(
                              "The Annotations part referenced by the Annotations " +
                              "Relationship TargetURI '" + annotRel.TargetUri +
                              "' could not be found.");
                }
            }

            return(annotPart);
        }// end:GetAnnotationPart()
示例#8
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageId, "No package ID was specified. Please pass --packageId YourPackage");
            Guard.NotNullOrWhiteSpace(packageVersion, "No package version was specified. Please pass --packageVersion 1.0.0.0");
            Guard.NotNullOrWhiteSpace(packageHash, "No package hash was specified. Please pass --packageHash YourPackageHash");

            SemanticVersion version;

            if (!SemanticVersion.TryParse(packageVersion, out version))
            {
                throw new CommandException(String.Format("Package version '{0}' is not a valid Semantic Version", packageVersion));
            }

            var packageStore    = new PackageStore();
            var packageMetadata = new PackageMetadata {
                Id = packageId, Version = packageVersion, Hash = packageHash
            };
            var package = packageStore.GetPackage(packageMetadata);

            if (package == null)
            {
                Log.VerboseFormat("Package {0} version {1} hash {2} has not been uploaded.",
                                  packageMetadata.Id, packageMetadata.Version, packageMetadata.Hash);

                Log.VerboseFormat("Finding earlier packages that have been uploaded to this Tentacle.");
                var nearestPackages = packageStore.GetNearestPackages(packageId, version).ToList();
                if (!nearestPackages.Any())
                {
                    Log.VerboseFormat("No earlier packages for {0} has been uploaded", packageId);
                    return(0);
                }

                Log.VerboseFormat("Found {0} earlier {1} of {2} on this Tentacle",
                                  nearestPackages.Count, nearestPackages.Count == 1 ? "version" : "versions", packageId);
                foreach (var nearestPackage in nearestPackages)
                {
                    Log.VerboseFormat("  - {0}: {1}", nearestPackage.Metadata.Version, nearestPackage.FullPath);
                    Log.ServiceMessages.PackageFound(nearestPackage.Metadata.Id, nearestPackage.Metadata.Version, nearestPackage.Metadata.Hash, nearestPackage.FullPath);
                }

                return(0);
            }

            Log.VerboseFormat("Package {0} {1} hash {2} has already been uploaded", package.Metadata.Id, package.Metadata.Version, package.Metadata.Hash);
            Log.ServiceMessages.PackageFound(package.Metadata.Id, package.Metadata.Version, package.Metadata.Hash, package.FullPath, true);
            return(0);
        }
示例#9
0

        
示例#10
0
        public void ReloadPreview(PageOrientation pageOrientation, PaperSize currentPaper)
        {
            ReloadingPreview = true;
            if (FullScreenPrintWindow != null)
            {
                WaitScreen.Show("Loading Preview");
            }

            if (PageOrientation == PageOrientation.Portrait)
            {
                FlowDocument.PageHeight = currentPaper.Height;
                FlowDocument.PageWidth  = currentPaper.Width;
            }
            else
            {
                FlowDocument.PageHeight = currentPaper.Width;
                FlowDocument.PageWidth  = currentPaper.Height;
            }

            _ms  = new MemoryStream();
            _pkg = Package.Open(_ms, FileMode.Create, FileAccess.ReadWrite);
            const string pack       = "pack://temp.xps";
            var          oldPackage = PackageStore.GetPackage(new Uri(pack));

            if (oldPackage == null)
            {
                PackageStore.AddPackage(new Uri(pack), _pkg);
            }
            else
            {
                PackageStore.RemovePackage(new Uri(pack));
                PackageStore.AddPackage(new Uri(pack), _pkg);
            }
            _xpsDocument = new XpsDocument(_pkg, CompressionOption.SuperFast, pack);
            var xpsWriter = XpsDocument.CreateXpsDocumentWriter(_xpsDocument);

            var documentPaginator = ((IDocumentPaginatorSource)FlowDocument).DocumentPaginator;

            xpsWriter.Write(documentPaginator);
            Paginator   = documentPaginator;
            MaxCopies   = NumberOfPages = ApproaxNumberOfPages = Paginator.PageCount;
            PagesAcross = 2;
            DisplayPagePreviewsAll(documentPaginator);
            WaitScreen.Hide();
            ReloadingPreview = false;
        }
示例#11
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageId, "No package ID was specified. Please pass --packageId YourPackage");
            Guard.NotNullOrWhiteSpace(rawPackageVersion, "No package version was specified. Please pass --packageVersion 1.0.0.0");
            Guard.NotNullOrWhiteSpace(packageHash, "No package hash was specified. Please pass --packageHash YourPackageHash");

            var fileSystem   = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
            var extractor    = new GenericPackageExtractorFactory().createJavaGenericPackageExtractor(fileSystem);
            var packageStore = new PackageStore(extractor);

            if (!VersionFactory.TryCreateVersion(rawPackageVersion, out IVersion version, versionFormat))
            {
                throw new CommandException($"Package version '{rawPackageVersion}' is not a valid {versionFormat} version string. Please pass --packageVersionFormat with a different version type.");
            }
            ;

            var package = packageStore.GetPackage(packageId, version, packageHash);

            if (package == null)
            {
                Log.Verbose($"Package {packageId} version {version} hash {packageHash} has not been uploaded.");

                if (exactMatchOnly)
                {
                    return(0);
                }

                FindEarlierPackages(packageStore, version);

                return(0);
            }

            Log.VerboseFormat("Package {0} {1} hash {2} has already been uploaded", package.PackageId, package.Version, package.Hash);
            Log.ServiceMessages.PackageFound(
                package.PackageId,
                package.Version,
                package.Hash,
                package.Extension,
                package.FullFilePath,
                true);
            return(0);
        }
示例#12
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var uri = new Uri("pack://application:,,,/SimpleScan_Manual.xps");

            Package package = PackageStore.GetPackage(uri);

            if (package == null)
            {
                var stream = Application.GetResourceStream(uri).Stream;
                package = Package.Open(stream);
                PackageStore.AddPackage(uri, package);
            }

            var xpsDoc = new XpsDocument(package, CompressionOption.Maximum, uri.AbsoluteUri);
            var fixedDocumentSequence = xpsDoc.GetFixedDocumentSequence();

            doc.Document = fixedDocumentSequence;
            xpsDoc.Close();
        }
示例#13
0
        public ejpXpsDocument(string path, string title, bool isExternalToAssignment,
                              Guid xpsDocumentId, Guid parentStudyId)
        {
            this._isExternalToAssignment = isExternalToAssignment;

            if (!File.Exists(path))
            {
                throw new IOException("Xps Document not Found.");
            }

            this._xpsDocumentPath = path;
            this._packageUri      = new Uri(path, UriKind.Absolute);

            try
            {
                this._xpsDocument = new XpsDocument(path, FileAccess.ReadWrite);

                FileInfo fi = new FileInfo(path);
                this._xpsDocument.CoreDocumentProperties.Title      = title;
                this._xpsDocument.CoreDocumentProperties.Identifier = xpsDocumentId.ToString();

                this._xpsPackage = PackageStore.GetPackage(this._packageUri);
                if ((this._xpsPackage == null) || (this._xpsDocument == null))
                {
                    throw new Exception("Unable to get Package from file.");
                }

                this.GetFixedDocumentSequenceUri();
            }
            catch (Exception ex)
            {
                //SiliconStudio.DebugManagers.DebugReporter.Report(
                //	SiliconStudio.DebugManagers.MessageType.Error,
                System.Diagnostics.Debug.Assert(false, ex.Message);
                //	"Failed to create Xps Document Instance",
                //	"\nPath: " + path +
                //	"\nIs External To Assignment: " + isExternalToAssignment.ToString() +
                //	"\nError: " + ex.Message);
            }
        }        // end:Constructor()
示例#14
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageId, "No package ID was specified. Please pass --packageId YourPackage");
            Guard.NotNullOrWhiteSpace(packageVersion, "No package version was specified. Please pass --packageVersion 1.0.0.0");
            Guard.NotNullOrWhiteSpace(packageHash, "No package hash was specified. Please pass --packageHash YourPackageHash");

            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            var packageMetadata = new MetadataFactory().GetMetadataFromPackageID(packageId, packageVersion, null, 0, packageHash);

            var extractor    = new GenericPackageExtractorFactory().createJavaGenericPackageExtractor(fileSystem);
            var packageStore = new PackageStore(extractor);
            var package      = packageStore.GetPackage(packageMetadata);

            if (package == null)
            {
                Log.Verbose($"Package {packageMetadata.PackageId} version {packageMetadata.Version} hash {packageMetadata.Hash} has not been uploaded.");

                if (exactMatchOnly)
                {
                    return(0);
                }

                FindEarlierPackages(packageStore, packageMetadata);

                return(0);
            }

            Log.VerboseFormat("Package {0} {1} hash {2} has already been uploaded", package.Metadata.PackageId, package.Metadata.Version, package.Metadata.Hash);
            Log.ServiceMessages.PackageFound(
                package.Metadata.PackageId,
                package.Metadata.Version,
                package.Metadata.Hash,
                package.Metadata.FileExtension,
                package.FullPath,
                true);
            return(0);
        }
示例#15
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageId, "No package ID was specified. Please pass --packageId YourPackage");
            Guard.NotNullOrWhiteSpace(packageVersion, "No package version was specified. Please pass --packageVersion 1.0.0.0");
            Guard.NotNullOrWhiteSpace(packageHash, "No package hash was specified. Please pass --packageHash YourPackageHash");

            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            if (!NuGetVersion.TryParse(packageVersion, out var version))
            {
                throw new CommandException($"Package version '{packageVersion}' is not a valid Semantic Version");
            }

            var packageStore = new PackageStore(
                new GenericPackageExtractorFactory().createJavaGenericPackageExtractor(fileSystem));
            var packageMetadata = new ExtendedPackageMetadata {
                Id = packageId, Version = packageVersion, Hash = packageHash
            };
            var package = packageStore.GetPackage(packageMetadata);

            if (package == null)
            {
                Log.Verbose($"Package {packageMetadata.Id} version {packageMetadata.Version} hash {packageMetadata.Hash} has not been uploaded.");

                if (exactMatchOnly)
                {
                    return(0);
                }

                FindEarlierPackages(packageStore, version);

                return(0);
            }

            Log.VerboseFormat("Package {0} {1} hash {2} has already been uploaded", package.Metadata.Id, package.Metadata.Version, package.Metadata.Hash);
            Log.ServiceMessages.PackageFound(package.Metadata.Id, package.Metadata.Version, package.Metadata.Hash, package.Metadata.FileExtension, package.FullPath, true);
            return(0);
        }
示例#16
0
        public static FixedDocumentSequence BytesToXpsDocument(byte[] bytes)
        {
            Package      package;
            Stream       stream    = new MemoryStream(bytes);
            BinaryReader br        = new BinaryReader(stream);
            string       uriString = br.ReadString();
            int          length    = br.ReadInt32();

            byte[] docData = br.ReadBytes(length);
            stream.Close();
            stream  = new MemoryStream(docData);
            package = Package.Open(stream);
            Uri uri = new Uri(uriString);

            if (PackageStore.GetPackage(uri) != null)
            {
                PackageStore.RemovePackage(uri);
            }
            PackageStore.AddPackage(uri, package);
            XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum, uriString);

            return(xpsDocument.GetFixedDocumentSequence());
        }
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            _doc = new XpsDocument("ch19.xps", FileAccess.ReadWrite);
            DocViewer.Document = _doc.GetFixedDocumentSequence();
            _service           = AnnotationService.GetService(DocViewer);
            if (_service != null)
            {
                return;
            }

            var annotationUri  = PackUriHelper.CreatePartUri(new Uri("AnnotationStream", UriKind.Relative));
            var package        = PackageStore.GetPackage(_doc.Uri);
            var annotationPart = package.PartExists(annotationUri)
            ? package.GetPart(annotationUri)
            : package.CreatePart(annotationUri, "Annotations/Stream");

            // Load annotations from the package.
            if (annotationPart != null)
            {
                AnnotationStore store = new XmlStreamStore(annotationPart.GetStream());
                _service = new AnnotationService(DocViewer);
                _service.Enable(store);
            }
        }
示例#18
0
 private bool PackageStoreContains(Uri packageUri)
 {
     return(PackageStore.GetPackage(packageUri) != null);
 }
示例#19
0

        
示例#20
0
        }// end:OnOpen()


        // --------------------------- OpenDocument ---------------------------
        /// <summary>
        ///   Loads and displays a given XPS document file.</summary>
        /// <param name="filename">
        ///   The path and filename of the XPS document
        ///   to load and display.</param>
        /// <returns>
        ///   true if the document loads successfully; otherwise false.</returns>
        public bool OpenDocument(string filename)
        {
            // Save the document path and filename.
            _xpsDocumentPath = filename;

            // Extract the document filename without the path.
            _xpsDocumentName = filename.Remove(0, filename.LastIndexOf('\\')+1);

            _packageUri = new Uri(filename, UriKind.Absolute);
            try
            {
                _xpsDocument = new XpsDocument(filename, FileAccess.Read);
            }
            catch (System.IO.FileFormatException)
            {
                string msg = filename + "\n\nThe specified file " +
                    "in not a valid unprotected XPS document.\n\n" +
                    "The file is possibly encrypted with rights management.  " +
                    "Please see the RightsManagedPackageViewer\nsample that " +
                    "shows how to access and view a rights managed XPS document.";
                MessageBox.Show(msg, "Invalid File Format",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            // Get the document's PackageStore into which
            // new user annotations will be added and saved.
            _xpsPackage = PackageStore.GetPackage(_packageUri);
            if ((_xpsPackage == null) || (_xpsDocument == null))
            {
                MessageBox.Show("Unable to get Package from file.");
                return false;
            }

            // Get the FixedDocumentSequence from the open document.
            FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence();
            if (fds == null)
            {
                string msg = filename +
                    "\n\nThe document package within the specified " +
                    "file does not contain a FixedDocumentSequence.";
                MessageBox.Show(msg, "Package Error");
                return false;
            }

            // Load the FixedDocumentSequence to the DocumentViewer control.
            docViewer.Document = fds;

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

            // Give the DocumentViewer focus.
            docViewer.Focus();

            WriteStatus("Opened '" + _xpsDocumentName + "'");
            WritePrompt("Click 'File | Rights...' to select an " +
                        "eXtensible Rights Markup (XrML) permissions file.");
            return true;
        }// end:OpenDocument()
示例#21
0
        }// end:OnOpen()


        // --------------------------- OpenDocument ---------------------------
        /// <summary>
        ///   Loads and displays a given XPS document file.</summary>
        /// <param name="filename">
        ///   The path and file name of the XPS
        ///   document to load and display.</param>
        /// <returns>
        ///   true if the document loads successfully; otherwise false.</returns>
        public bool OpenDocument(string xpsFile)
        {
            // Check to see if the document is encrypted.
            // If encrypted, use OpenEncryptedDocument().
            if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(xpsFile))
                return OpenEncryptedDocument(xpsFile);

            // Document is not encrypted, open normally.
            ShowStatus("Opening '" + Filename(xpsFile) + "'");

            _packageUri = new Uri(xpsFile, UriKind.Absolute);
            try
            {
                _xpsDocument = new XpsDocument(xpsFile, FileAccess.Read);
            }
            catch (System.IO.FileFormatException ex)
            {
                MessageBox.Show(xpsFile + "\n\nThe file " +
                    "is not a valid XPS document.\n\n" +
                    "Exception: " + ex.Message + "\n\n" +
                    ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                    "Invalid File Format",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }


            // Get the document's PackageStore into which
            // new user annotations will be added and saved.
            _xpsPackage = PackageStore.GetPackage(_packageUri);
            if ((_xpsPackage == null) || (_xpsDocument == null))
            {
                MessageBox.Show("Unable to get Package from file.");
                return false;
            }

            // Get the FixedDocumentSequence from the open document.
            FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence();
            if (fds == null)
            {
                MessageBox.Show(xpsFile + "\n\nThe document package within " +
                    "the specified file does not contain a " +
                    "FixedDocumentSequence.", "Package Error");
                return false;
            }

            // Load the FixedDocumentSequence to the DocumentViewer control.
            DocViewer.Document = fds;

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

            // Give the DocumentViewer focus.
            docViewer.Focus();

            this.Title = "RightsManagedPackageViewer SDK Sample - " +
                         Filename(xpsFile);
            return true;
        }// end:OpenDocument()
示例#22
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);
            string deltaFilePath;
            string newFilePath;
            string basisFilePath;

            ValidateParameters(out basisFilePath, out deltaFilePath, out newFilePath);
            fileSystem.EnsureDiskHasEnoughFreeSpace(packageStore.GetPackagesDirectory());

            var commandLineRunner = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(),
                                                                                 new ServiceMessageCommandOutput(new VariableDictionary())));

            var tempNewFilePath = newFilePath + ".partial";
            var executable      = FindOctoDiffExecutable();
            var octoDiff        = CommandLine.Execute(executable)
                                  .Action("patch")
                                  .PositionalArgument(basisFilePath)
                                  .PositionalArgument(deltaFilePath)
                                  .PositionalArgument(tempNewFilePath);

            if (skipVerification)
            {
                octoDiff.Flag("skip-verification");
            }

            if (showProgress)
            {
                octoDiff.Flag("progress");
            }

            Log.Info("Applying delta to {0} with hash {1} and storing as {2}", basisFilePath, fileHash,
                     newFilePath);

            var result = commandLineRunner.Execute(octoDiff.Build());

            if (result.ExitCode != 0)
            {
                fileSystem.DeleteFile(tempNewFilePath, DeletionOptions.TryThreeTimes);
                throw new CommandLineException(executable, result.ExitCode, result.Errors);
            }

            File.Move(tempNewFilePath, newFilePath);

            if (!File.Exists(newFilePath))
            {
                throw new CommandException("Failed to apply delta file " + deltaFilePath + " to " +
                                           basisFilePath);
            }

            var package = packageStore.GetPackage(newFilePath);

            if (package == null)
            {
                return(0);
            }

            using (var file = new FileStream(package.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var size = file.Length;
                Log.ServiceMessages.DeltaVerification(package.FullPath, package.Metadata.Hash, size);
            }

            return(0);
        }
示例#23
0
        }// end:GetContentFolder()

        // --------------------------- OpenDocument ---------------------------
        /// <summary>
        ///   Loads, displays, and enables user annotations
        ///   a given XPS document file.</summary>
        /// <param name="filename">
        ///   The path and filename of the XPS document
        ///   to load, display, and annotate.</param>
        /// <returns>
        ///   true if the document loads successfully; otherwise false.</returns>
        public bool OpenDocument(string filename)
        {
            // Load an XPS document into a DocumentViewer
            // and enable user Annotations.
            _xpsDocumentPath = filename;

            _packageUri = new Uri(filename, UriKind.Absolute);
            try
            {
                _xpsDocument = new XpsDocument(filename, FileAccess.ReadWrite);
            }
            catch (System.UnauthorizedAccessException)
            {
                string msg = filename +
                             "\n\nThe specified file is Read-Only which " +
                             "prevents storing user annotations.";
                MessageBox.Show(msg, "Read-Only file",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            // Get the document's PackageStore into which
            // new user annotations will be added and saved.
            _xpsPackage = PackageStore.GetPackage(_packageUri);
            if ((_xpsPackage == null) || (_xpsDocument == null))
            {
                MessageBox.Show("Unable to get Package from file.");
                return(false);
            }

            // Get the FixedDocumentSequence from the open document.
            FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence();

            if (fds == null)
            {
                string msg = filename +
                             "\n\nThe document package within the specified " +
                             "file does not contain a FixedDocumentSequence.";
                MessageBox.Show(msg, "Package Error");
                return(false);
            }

            // Load the FixedDocumentSequence to the DocumentViewer control.
            docViewer.Document = fds;

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

            // Enable user annotations on the document.
            Uri fixedDocumentSeqUri = GetFixedDocumentSequenceUri();

            _annotHelper.SetSource(_packageUri, fixedDocumentSeqUri);
            if (menuViewAnnotations.IsChecked)
            {
                _annotHelper.StartAnnotations();
            }

            // Give the DocumentViewer focus.
            docViewer.Focus();

            return(true);
        }// end:OpenDocument()
示例#24
0
        private PackagePart GetAnnotationPart(Uri uri)
        {
            Package package = PackageStore.GetPackage(documentUri);

            if (package == null)
            {
                return(null);
            }

            // Get the FixedDocumentSequence part from the package.
            PackagePart fdsPart = package.GetPart(uri);

            // Search through all the document relationships to find the
            // annotations relationship part (or null, of there is none).
            PackageRelationship annotRel = null;

            annotRel
                = fdsPart.GetRelationships().FirstOrDefault <PackageRelationship>(
                      pr => pr.RelationshipType == annotRelsType);

            PackagePart annotPart;

            //If annotations relationship does not exist, create a new
            //annotations part, if required, and a relationship for it.
            if (annotRel == null)
            {
                Uri annotationUri =
                    PackUriHelper.CreatePartUri(new Uri("annotations.xml",
                                                        UriKind.Relative));

                if (package.PartExists(annotationUri))
                {
                    annotPart = package.GetPart(annotationUri);
                }
                else
                {
                    //Create a new Annotations part in the document.
                    annotPart = package.CreatePart(annotationUri, annotContentType);
                }

                //Create a new relationship that points to the Annotations part.
                fdsPart.CreateRelationship(annotPart.Uri,
                                           TargetMode.Internal,
                                           annotRelsType);
            }
            else
            {
                //If an annotations relationship exists,
                //get the annotations part that it references.

                //Get the Annotations part specified by the relationship.
                annotPart = package.GetPart(annotRel.TargetUri);

                if (annotPart == null)
                {
                    //The annotations part pointed to by the annotation
                    //relationship Uri is not present. Handle as required.
                    return(null);
                }
            }

            return(annotPart);
        }
示例#25
0
        //Presents the user with an OpenFileDialog, used to get a path
        //to the XPS document they want to open. If this succeeds,
        //the XPS document is loaded and displayed in the document viewer,
        //ready for annotating.
        private void LoadFixedDocument()
        {
            //Get a path to the file to be opened.
            string fileName = GetDocumentPath();

            //If we didn't get a valid file path, we're done.
            //You might want to log an error here.
            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }

            //Create a URI for the file path.
            documentUri = new Uri(fileName, UriKind.Absolute);

            try
            {
                //Attempts to open the specified xps document with
                //read and write permission.
                xpsDocument = new XpsDocument(fileName, FileAccess.ReadWrite);
            }
            catch (Exception)
            {
                //You may want to handle any errors that occur during
                //the loading of the XPS document. For example a
                //UnauthorizedAccessException will be thrown if the
                //file is marked as read-only.
            }

            //Get the document's Package from the PackageStore.
            xpsPackage = PackageStore.GetPackage(documentUri);

            //If either the package or document are null, the
            //document is not valid.
            if ((xpsPackage == null) || (xpsDocument == null))
            {
                //You may want to log an error here.
                return;
            }

            //Get the FixedDocumentSequence of the loaded document.
            FixedDocumentSequence fixedDocumentSequence
                = xpsDocument.GetFixedDocumentSequence();

            //If the document's FixedDocumentSequence is not found,
            //the document is corrupt.
            if (fixedDocumentSequence == null)
            {
                //Handle as required.
                return;
            }

            //Load the document's FixedDocumentSequence into
            //the DocumentViewer control.
            dvViewer.Document = fixedDocumentSequence;

            //Enable user annotations on the document.
            StartFixedDocumentAnnotations();

            hasOpenDocument = true;
        }