public override bool Marshall(PackagePart part, Stream out1)
	{
		if (!(out1 is ZipOutputStream)) {
			throw new ArgumentException("ZipOutputStream expected!");
		}
		ZipOutputStream zos = (ZipOutputStream) out1;

		// Saving the part in the zip file
		string name = ZipHelper
				.GetZipItemNameFromOPCName(part.PartName.URI.ToString());
        ZipEntry ctEntry = new ZipEntry(name);

        try
        {
            // Save in ZIP
            zos.PutNextEntry(ctEntry); // Add entry in ZIP

            base.Marshall(part, out1); // Marshall the properties inside a XML
            // Document
            StreamHelper.SaveXmlInStream(xmlDoc, out1);

            zos.CloseEntry();
        }
        catch (IOException e)
        {
            throw new OpenXml4NetException(e.Message);
        }
        catch
        {
            return false; 
        }
		return true;
	}
예제 #2
0
        public void MapPublishedPackageToPackagePart(PublishedPackage publishedPackage, PackagePart packagePart) {
            packagePart.PackageID = publishedPackage.Id;
            packagePart.PackageVersion = publishedPackage.Version;
            packagePart.Title = string.IsNullOrWhiteSpace(publishedPackage.Title) ? publishedPackage.Id : publishedPackage.Title;
            packagePart.Description = publishedPackage.Description;
            packagePart.Summary = publishedPackage.Summary;

            packagePart.Slug = _packageSlugCreator.CreateSlug(packagePart.PackageID, packagePart.PackageVersion);

            packagePart.Authors = publishedPackage.Authors;
            packagePart.DownloadCount = publishedPackage.VersionDownloadCount;
            packagePart.TotalDownloadCount = publishedPackage.DownloadCount;
            packagePart.Copyright = publishedPackage.Copyright;
            packagePart.ProjectUrl = publishedPackage.ProjectUrl;
            packagePart.LicenseUrl = publishedPackage.LicenseUrl;
            packagePart.IconUrl = publishedPackage.IconUrl;
            packagePart.PackageHashAlgorithm = publishedPackage.PackageHashAlgorithm;
            packagePart.PackageHash = publishedPackage.PackageHash;
            packagePart.PackageSize = publishedPackage.PackageSize;
            packagePart.ExternalPackageUrl = publishedPackage.ExternalPackageUrl;
            packagePart.ReportAbuseUrl = publishedPackage.ReportAbuseUrl;
            packagePart.LastUpdated = publishedPackage.LastUpdated;
            packagePart.Price = publishedPackage.Price;
            packagePart.Created = publishedPackage.Created;
            packagePart.Published = publishedPackage.Published;
            packagePart.IsRecommendedVersion = publishedPackage.IsLatestVersion;
        }
        private void SetupRoutePart(PackagePart packagePartToMapTo) {
            var contentItem = new ContentItem { ContentType = "Package" };
            var routePart = new AutoroutePart {Record = new AutoroutePartRecord()};
            contentItem.Weld(routePart);
            contentItem.Weld(packagePartToMapTo);

        }
예제 #4
0
 public void UpdateTags(PublishedPackage publishedPackage, PackagePart packagePart) {
     if (publishedPackage.Tags != null)
     {
         string whitespaceProcessedTagString = new Regex(@"\s+").Replace(publishedPackage.Tags.Trim(), " ");
         _tagService.UpdateTagsForContentItem(packagePart.ContentItem, whitespaceProcessedTagString.Split(' '));
     }
 }
 public void UpdateExtendedPackageInfo(PublishedPackage publishedPackage, PackagePart packagePart) {
     packagePart.DownloadUrl = _oDataContext.GetDownloadUrl(publishedPackage);
     _packagePartTagUpdater.UpdateTags(publishedPackage, packagePart);
     _packagePartTaxonomyUpdater.UpdatePackageTaxonomy(publishedPackage, packagePart);
     _screenshotPartDeleter.DeleteScreenshotsForPackage(publishedPackage.Id, publishedPackage.Version);
     _screenshotPartCreator.AddScreenshotsForPackage(publishedPackage.Id, publishedPackage.Version);
 }
        public void ShouldDoNothingWhenGivenPackageIsNotRecommendedVersion()
        {
            var recommendedPackage = new PackagePart { Record = new PackagePartRecord(), IsRecommendedVersion = false };

            _updater.SetRecommendedVersionFlagsOfOtherPackagesWithSameId(recommendedPackage);

            _mockedPackageService.Verify(ps => ps.GetById(recommendedPackage.PackageID, It.IsAny<bool>()), Times.Never());
        }
 public void UpdatePackageTaxonomy(PublishedPackage publishedPackage, PackagePart packagePart) {
     int packageTypesTaxonomyId = _taxonomyService.GetTaxonomyByName("Package Types").Id;
     if (!string.IsNullOrEmpty(publishedPackage.PackageType)) {
         SetPackagePartTaxonomyToPackageTypeTerm(packageTypesTaxonomyId, packagePart, publishedPackage);
     }
     else {
         SetPackagePartTaxonomyToDefaultTerm(packageTypesTaxonomyId, packagePart);
     }
 }
 private void SetPackagePartTaxonomyToDefaultTerm(int packageTypesTaxonomyId, PackagePart packagePart) {
     IEnumerable<TermPart> termParts = _taxonomyService.GetTerms(packageTypesTaxonomyId)
         .Where(tp => tp.GetLevels() == 0);
     if (termParts.Count() == 1)
     {
         var terms = new List<TermPart> { termParts.Single() };
         _taxonomyService.UpdateTerms(packagePart.ContentItem, terms, PACKAGE_TYPE_TAXONOMY_FIELD_NAME);
     }
 }
        public void ShouldSetTitleToIdWhenPublishedPackageTitleIsNullOrEmpty(string title)
        {
            PublishedPackage publishedPackage = new PublishedPackage { Id="SomeId", Title = title};
            PackagePart packagePartToMapTo = new PackagePart {Record = new PackagePartRecord()};
            SetupRoutePart(packagePartToMapTo);

            _packagePartMapper.MapPublishedPackageToPackagePart(publishedPackage, packagePartToMapTo);

            Assert.AreEqual(publishedPackage.Id, packagePartToMapTo.Title, "Id should have been mapped to Title.");
        }
예제 #10
0
 private void UpdatePackage(PackageLogEntry log, PublishedPackage publishedPackage, PackagePart packagePart) {
     if (log.Action == PackageLogAction.Update || log.Action == PackageLogAction.RePublish) {
         _packagePartMapper.MapPublishedPackageToPackagePart(publishedPackage, packagePart);
         _recommendedVersionUpdater.SetRecommendedVersionFlagsOfOtherPackagesWithSameId(packagePart);
     }
     else {
         packagePart.DownloadCount = publishedPackage.VersionDownloadCount;
         packagePart.TotalDownloadCount = publishedPackage.DownloadCount;
     }
 }
        public void ShouldUpdateIsRecommendedVersionFieldForAllOtherPackagesWithTheSameId() {
            var recommendedPackage = new PackagePart {Record = new PackagePartRecord(), PackageID = "Pack1", PackageVersion = "V2", IsRecommendedVersion = true};
            var otherVersionOfPackage = new PackagePart { Record = new PackagePartRecord(), PackageID = "Pack1", PackageVersion = "V1", IsRecommendedVersion = true };
            _mockedPackageService.Setup(ps => ps.GetById(recommendedPackage.PackageID, It.IsAny<bool>()))
                .Returns(new[] { recommendedPackage, otherVersionOfPackage});

            _updater.SetRecommendedVersionFlagsOfOtherPackagesWithSameId(recommendedPackage);

            Assert.IsTrue(recommendedPackage.IsRecommendedVersion);
            Assert.IsFalse(otherVersionOfPackage.IsRecommendedVersion);
        }
        public void SetRecommendedVersionFlagsOfOtherPackagesWithSameId(PackagePart packagePart) {
            if (packagePart.IsRecommendedVersion) {
                IEnumerable<PackagePart> packagePartsToUpdate = _packageService.GetById(packagePart.PackageID)
                    .Where(pp => pp.PackageVersion != packagePart.PackageVersion);

                foreach (var packagePartToUpdate in packagePartsToUpdate) {
                    packagePartToUpdate.IsRecommendedVersion = false;
                    _indexingTaskManager.CreateUpdateIndexTask(packagePartToUpdate.ContentItem);
                }
            }
        }
        public void ShouldSetDownloadCountToThePublishedPackageVersionDownloadCount() {
            //The names of these fields don't match up because they were changed on the gallery server feed not long before the sites went live,
            //and we didn't get the PackagePart updated before they went live. So we didn't want to rename columns on the live sites.
            PublishedPackage publishedPackage = new PublishedPackage {Id = "PackageId", Version = "Version", VersionDownloadCount = 5};
            PackagePart packagePartToMapTo = new PackagePart {Record = new PackagePartRecord()};
            SetupRoutePart(packagePartToMapTo);

            _packagePartMapper.MapPublishedPackageToPackagePart(publishedPackage, packagePartToMapTo);

            Assert.AreEqual(5, packagePartToMapTo.DownloadCount);
        }
        public void ShouldCallRecommendedVersionUpdater() {
            PackagePart newPackagePart = new PackagePart { Record = new PackagePartRecord(), PackageID = "foo", PackageVersion = "1.0" };
            var contentItem = new ContentItem { ContentType = "Package" };
            contentItem.Weld(newPackagePart);
            PublishedPackage publishedPackage = new PublishedPackage { Id = newPackagePart.PackageID, Version = newPackagePart.PackageVersion };
            _mockedOdataContext.SetupGet(oc => oc.Packages).Returns(new[] { publishedPackage }.AsQueryable());
            _mockedContentManager.Setup(cm => cm.New(It.IsAny<string>())).Returns(contentItem);

            _creator.CreateNewPackagePart(new PackageLogEntry { PackageId = newPackagePart.PackageID, PackageVersion = newPackagePart.PackageVersion});

            _mockedRecommendedVersionUpdater.Verify(rvu => rvu.SetRecommendedVersionFlagsOfOtherPackagesWithSameId(newPackagePart));
        }
        public void ShouldCreateNewPackagePartWhenNoExistingOrchardVersionsOfPackageExist() {
            PackagePart newPackagePart = new PackagePart { Record = new PackagePartRecord(), PackageID = "foo", PackageVersion = "1.0" };
            var contentItem = new ContentItem { ContentType = "Package" };
            contentItem.Weld(newPackagePart);
            PublishedPackage publishedPackage = new PublishedPackage { Id = newPackagePart.PackageID, Version = newPackagePart.PackageVersion };
            _mockedOdataContext.SetupGet(oc => oc.Packages).Returns(new[] { publishedPackage }.AsQueryable());
            _mockedContentManager.Setup(cm => cm.New(It.IsAny<string>())).Returns(contentItem);
            _mockedPackageService.Setup(ps => ps.PackageExists(newPackagePart.PackageID, newPackagePart.PackageVersion, It.IsAny<VersionOptions>())).Returns(false);

            _creator.CreateNewPackagePart(new PackageLogEntry { PackageId = newPackagePart.PackageID, PackageVersion = newPackagePart.PackageVersion });

            _mockedContentManager.Verify(cm => cm.Create(It.IsAny<ContentItem>(), It.IsAny<VersionOptions>()), Times.Once());
        }
        private void SetPackagePartTaxonomyToPackageTypeTerm(int packageTypesTaxonomyId, PackagePart packagePart, PublishedPackage publishedPackage) {
            TermPart packageTypeTerm = _taxonomyService.GetTermByName(packageTypesTaxonomyId, publishedPackage.PackageType);
            var terms = new List<TermPart> { packageTypeTerm };

            if (!string.IsNullOrWhiteSpace(publishedPackage.Categories)) {
                string category = publishedPackage.Categories.Split(',').Last();
                TermPart packageCategoryTerm = _taxonomyService.GetChildren(packageTypeTerm).FirstOrDefault(t => t.Name == category);
                if (packageCategoryTerm != null) {
                    terms.Add(packageCategoryTerm);
                }
            }
            _taxonomyService.UpdateTerms(packagePart.ContentItem, terms, PACKAGE_TYPE_TAXONOMY_FIELD_NAME);
        }
예제 #17
0
 public string GetFileHash(PackagePart part)
 {
     using (var inputStream = part.GetStream())
     using (var md5 = new MD5CryptoServiceProvider())
     {
         var hash = md5.ComputeHash(inputStream);
         var sb = new StringBuilder();
         foreach (var b in hash)
         {
             sb.Append(string.Format("{0:X2}", b));
         }
         return sb.ToString();
     }
 }
예제 #18
0
        public void Setup() {
            _mockedContentManager = new Mock<IContentManager>();
            _mockedPackageService = new Mock<IPackageService>();

            _existingPackagePart = new PackagePart {
                Record = new PackagePartRecord { PackageID = "PackageId", PackageVersion = "1.3" },
                ContentItem = new ContentItem { VersionRecord = new ContentItemVersionRecord { Published = true} }
            };
            _log = new PackageLogEntry { PackageId = _existingPackagePart.PackageID, PackageVersion = _existingPackagePart.PackageVersion,
                Action = PackageLogAction.Unpublish };
            _mockedPackageService.Setup(ps => ps.Get(_existingPackagePart.PackageID, _existingPackagePart.PackageVersion, true))
                .Returns(_existingPackagePart);

            _publishingService = new Gallery.PackageSynchronization.PackagePartPublishingService(_mockedContentManager.Object, _mockedPackageService.Object);
        }
        /**
         * Marshall package core properties to an XML document. Always return
         * <code>true</code>.
         */
        public virtual bool Marshall(PackagePart part, Stream out1)
        {
            if (!(part is PackagePropertiesPart))
                throw new ArgumentException(
                        "'part' must be a PackagePropertiesPart instance.");
            propsPart = (PackagePropertiesPart)part;

            // Configure the document
            xmlDoc = new XmlDocument();
            XmlElement rootElem = xmlDoc.CreateElement("coreProperties",namespaceCoreProperties);

            nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
            nsmgr.AddNamespace("cp",PackagePropertiesPart.NAMESPACE_CP_URI);
            nsmgr.AddNamespace("dc",PackagePropertiesPart.NAMESPACE_DC_URI);
            nsmgr.AddNamespace("dcterms",PackagePropertiesPart.NAMESPACE_DCTERMS_URI);
            nsmgr.AddNamespace("xsi", PackagePropertiesPart.NAMESPACE_XSI_URI);

            rootElem.SetAttribute("xmlns:cp", PackagePropertiesPart.NAMESPACE_CP_URI);
            rootElem.SetAttribute("xmlns:dc", PackagePropertiesPart.NAMESPACE_DC_URI);
            rootElem.SetAttribute("xmlns:dcterms", PackagePropertiesPart.NAMESPACE_DCTERMS_URI);
            rootElem.SetAttribute("xmlns:xsi", PackagePropertiesPart.NAMESPACE_XSI_URI);

            xmlDoc.AppendChild(rootElem);

            AddCategory();
            AddContentStatus();
            AddContentType();
            AddCreated();
            AddCreator();
            AddDescription();
            AddIdentifier();
            AddKeywords();
            AddLanguage();
            AddLastModifiedBy();
            AddLastPrinted();
            AddModified();
            AddRevision();
            AddSubject();
            AddTitle();
            AddVersion();
            return true;
        }
예제 #20
0
 public void CreateValidPart()
 {
     PackagePart part = package.CreatePart(uris [0], "img/bmp");
 }
예제 #21
0
 /**
  * Creates an POIXMLDocumentPart representing the given namespace part, relationship and parent
  * Called by {@link #read(POIXMLFactory, java.util.Map)} when Reading in an exisiting file.
  *
  * @param parent - Parent part
  * @param part - The namespace part that holds xml data represenring this sheet.
  * @param rel - the relationship of the given namespace part
  * @see #read(POIXMLFactory, java.util.Map)
  */
 public POIXMLDocumentPart(POIXMLDocumentPart parent, PackagePart part, PackageRelationship rel)
 {
     this.packagePart = part;
     this.packageRel  = rel;
     this.parent      = parent;
 }
예제 #22
0
 public void ResetRecommendedVersionForPackage(PackagePart packagePart) {
     if (!packagePart.IsRecommendedVersion) {
         return;
     }
     packagePart.IsRecommendedVersion = false;
     IEnumerable<PackagePart> packageParts = GetById(packagePart.PackageID, false);
     if (!packageParts.Any()) {
         return;
     }
     var highestVersion = packageParts.Select(p => new { Package = p, Version = new Version(p.PackageVersion) })
         .OrderByDescending(v => v.Version).First().Package;
     highestVersion.IsRecommendedVersion = true;
     _indexingTaskManager.CreateUpdateIndexTask(highestVersion.ContentItem);
     _indexNotifierHandler.UpdateIndex("Search");
 }
예제 #23
0
파일: Container.cs 프로젝트: teatime/DocX
        public virtual Paragraph InsertParagraph(Paragraph p)
        {
            #region Styles
            XDocument style_document;

            if (p.styles.Count() > 0)
            {
                Uri style_package_uri = new Uri("/word/styles.xml", UriKind.Relative);
                if (!Document.package.PartExists(style_package_uri))
                {
                    PackagePart style_package = Document.package.CreatePart(style_package_uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(style_package.GetStream())))
                    {
                        style_document = new XDocument
                                         (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            new XElement(XName.Get("styles", DocX.w.NamespaceName))
                                         );

                        style_document.Save(tw);
                    }
                }

                PackagePart styles_document = Document.package.GetPart(style_package_uri);
                using (TextReader tr = new StreamReader(styles_document.GetStream()))
                {
                    style_document = XDocument.Load(tr);
                    XElement styles_element = style_document.Element(XName.Get("styles", DocX.w.NamespaceName));

                    var ids = from d in styles_element.Descendants(XName.Get("style", DocX.w.NamespaceName))
                              let a = d.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
                                      where a != null
                                      select a.Value;

                    foreach (XElement style in p.styles)
                    {
                        // If styles_element does not contain this element, then add it.

                        if (!ids.Contains(style.Attribute(XName.Get("styleId", DocX.w.NamespaceName)).Value))
                        {
                            styles_element.Add(style);
                        }
                    }
                }

                using (TextWriter tw = new StreamWriter(new PackagePartStream(styles_document.GetStream())))
                    style_document.Save(tw);
            }
            #endregion

            XElement newXElement = new XElement(p.Xml);

            Xml.Add(newXElement);

            int index = 0;
            if (Document.paragraphLookup.Keys.Count() > 0)
            {
                index = Document.paragraphLookup.Last().Key;

                if (Document.paragraphLookup.Last().Value.Text.Length == 0)
                {
                    index++;
                }
                else
                {
                    index += Document.paragraphLookup.Last().Value.Text.Length;
                }
            }

            Paragraph newParagraph = new Paragraph(Document, newXElement, index);
            Document.paragraphLookup.Add(index, newParagraph);

            GetParent(newParagraph);

            return(newParagraph);
        }
예제 #24
0
        private List <PackagePart> GetAllPackagePartsWithRelationshipType(string relType, PackagePart parent)
        {
            PackageRelationshipCollection rels = parent == null?Package.GetRelationshipsByType(relType) : parent.GetRelationshipsByType(relType);

            List <PackagePart> pkgList = new List <PackagePart>();

            foreach (PackageRelationship rel in rels)
            {
                if (rel.TargetMode == TargetMode.Internal)
                {
                    pkgList.Add(Package.GetPart(rel.TargetUri));
                }
            }
            return(pkgList);
        }
예제 #25
0
        // create a new part in this package
        internal void CreateInternal(OpenXmlPackage openXmlPackage, OpenXmlPart parent, string contentType, string targetExt)
        {
            // openXmlPackage, parent can not be all null
            if (openXmlPackage == null && parent == null)
            {
                throw new ArgumentNullException(ExceptionMessages.PackageRelatedArgumentNullException);
            }
            else if (parent != null && openXmlPackage != null &&
                     parent.OpenXmlPackage != openXmlPackage)
            {
                throw new ArgumentOutOfRangeException(nameof(parent));
            }
            else if (parent != null && openXmlPackage == null)
            {
                openXmlPackage = parent.OpenXmlPackage;
            }

            // throw exception to catch error in our code
            if (_metroPart != null)
            {
                throw new InvalidOperationException();
            }

            // set the _openXmlPackage so ThrowIfObjectDisposed( ) do not throw.
            _openXmlPackage = openXmlPackage;

            Uri parentUri;

            if (parent != null)
            {
                parentUri = parent.Uri;
            }
            else
            {
                parentUri = new Uri("/", UriKind.Relative);
            }

            //OpenXmlPart parentPart = this._ownerPart;

            //Uri is auto generated to make sure it's unique
            string targetPath = GetTargetPath(TargetPath);

            if (targetPath == null)
            {
                targetPath = ".";
            }

            string targetFileExt = targetExt;

            if (!IsContentTypeFixed)
            {
                if (!_openXmlPackage.PartExtensionProvider.TryGetValue(contentType, out targetFileExt))
                {
                    targetFileExt = targetExt;
                }
            }

            if (targetFileExt == null)
            {
                targetFileExt = TargetFileExtension;
            }

            _uri = _openXmlPackage.GetUniquePartUri(contentType, parentUri, targetPath, TargetName, targetFileExt);

            _metroPart = _openXmlPackage.CreateMetroPart(_uri, contentType);
        }
예제 #26
0
 /**
  * Construct XWPFFootnotes from a package part
  *
  * @param part the package part holding the data of the footnotes,
  * @param rel  the package relationship of type "http://schemas.Openxmlformats.org/officeDocument/2006/relationships/footnotes"
  */
 public XWPFFootnotes(PackagePart part, PackageRelationship rel)
     : base(part, rel)
 {
     ;
 }
예제 #27
0
        private PackagePart EnsurePackagePartWithUri(string relType, string contentType, string uriStr, PackagePart parent)
        {
            Uri         partUri = new Uri(uriStr, UriKind.Relative);
            PackagePart part    = null;

            try
            {
                part = Package.GetPart(partUri);
            }
            catch { }
            if (part == null)
            {
                part = CreatePackagePart(relType, contentType, uriStr, parent);
            }
            return(part);
        }
예제 #28
0
파일: XSSFVBAPart.cs 프로젝트: zzy092/npoi
 protected XSSFVBAPart(PackagePart part, PackageRelationship rel)
     : this(part)
 {
 }
        /// <summary>
        /// Transforms a document into a html file
        /// </summary>
        /// <param name="packing">Whether save results to a package or not</param>
        /// <param name="resourcesPackageName">Name of output package</param>
        /// <param name="htmlOutputName">Name of the output html file</param>
        /// <param name="outputPath">Path where the files should be placed</param>
        /// <param name="xslFilePath">Xslt file to use to perform transformation</param>
        public override void TransformToHtml(bool packing, string resourcesPackageName, string htmlOutputName, string outputPath, string xslFilePath, XsltArgumentList arguments = null)
        {
            try {
                Package      htmlPackage = null;
                StreamWriter htmlWriter  = null;

                /*
                 * // Creates an xmlReader to get the xml of the main document part
                 * XmlReader xmlReader =
                 *  XmlReader.Create(parentDocument.Document.MainDocumentPart.GetStream(FileMode.Open, FileAccess.Read));
                 */
                // Load document and important related parts, like the styles
                XmlDocument mainDoc = new XmlDocument();
                mainDoc.Load(parentDocument.Document.MainDocumentPart.GetStream());
                XmlNamespaceManager  nsm     = createNameSpaceManager(mainDoc.NameTable);
                XmlNode              docNode = mainDoc.SelectSingleNode("./w:document", nsm);
                StyleDefinitionsPart styles  = parentDocument.Document.MainDocumentPart.StyleDefinitionsPart;
                if (styles != null)
                {
                    LoadRelatedPart(mainDoc, docNode, styles.GetStream());
                }
                NumberingDefinitionsPart numbering = parentDocument.Document.MainDocumentPart.NumberingDefinitionsPart;
                if (numbering != null)
                {
                    LoadRelatedPart(mainDoc, docNode, numbering.GetStream());
                }
                ThemePart theme = parentDocument.Document.MainDocumentPart.ThemePart;
                if (theme != null)
                {
                    LoadRelatedPart(mainDoc, docNode, theme.GetStream());
                }
                FontTablePart fontTable = parentDocument.Document.MainDocumentPart.FontTablePart;
                if (fontTable != null)
                {
                    LoadRelatedPart(mainDoc, docNode, fontTable.GetStream());
                }

                if (packing)
                {
                    // New package that will contain the html file, with the images
                    htmlPackage = Package.Open(outputPath + @"\" + resourcesPackageName, FileMode.Create);
                }
                else
                {
                    // Create the directory where images will be stored
                    Directory.CreateDirectory(outputPath + @"\images\");
                }

                HandleNumberedLists(mainDoc, nsm);

                HandleImages(mainDoc, nsm, packing, outputPath, htmlPackage);
                HandleLinks(mainDoc, nsm);

                XslCompiledTransform OpenXmlTransformer = new XslCompiledTransform();
                OpenXmlTransformer.Load(xslFilePath);

                // The Transform method apply the xslt transformation to convert the XML to HTML
                StringWriter strWriterHtml = new StringWriter();
                // Manage the mapping of paragraphs with specific style templates to elements
                OpenXmlTransformer.Transform(mainDoc, arguments, strWriterHtml);
                string strHtml = strWriterHtml.ToString();

                // Closes the package if created
                if (packing)
                {
                    // Finally, creates the html file inside the html package
                    Uri uri = null;
                    if (htmlOutputName == string.Empty)
                    {
                        uri = new Uri("/inputFileName.html", UriKind.Relative);
                    }
                    else
                    {
                        uri = new Uri("/" + htmlOutputName, UriKind.Relative);
                    }
                    PackagePart htmlPart = htmlPackage.CreatePart(uri, "text/html");
                    htmlWriter = new StreamWriter(htmlPart.GetStream());
                    htmlWriter.Write(strHtml);
                    htmlWriter.Close();
                    htmlPackage.Close();
                }
                else
                {
                    // Writes the html file
                    htmlWriter = File.CreateText(outputPath + @"\" + htmlOutputName);
                    htmlWriter.Write(strHtml);
                    htmlWriter.Close();
                }
            } catch (XsltCompileException) {
                throw new Exception("Invalid XSLT");
            } catch (XsltException) {
                throw new Exception("Invalid XSLT");
            }
        }
예제 #30
0
파일: XSSFVBAPart.cs 프로젝트: zzy092/npoi
 /**
  * Construct XSSFVBAPart from a package part
  *
  * @param part the package part holding the VBA data,
  * @param rel  the package relationship holding this part
  */
 public XSSFVBAPart(PackagePart part)
     : base(part)
 {
 }
예제 #31
0
 /**
  * Construct XSSFPictureData from a namespace part
  *
  * @param part the namespace part holding the Drawing data,
  * @param rel  the namespace relationship holding this Drawing,
  * the relationship type must be http://schemas.Openxmlformats.org/officeDocument/2006/relationships/image
  */
 internal XSSFPictureData(PackagePart part, PackageRelationship rel)
     : base(part, rel)
 {
 }
예제 #32
0
 public CalculationChain(PackagePart part, PackageRelationship rel)
     : this(part)
 {
 }
예제 #33
0
        private PackagePart CreatePackagePart(string relType, string contentType, string uriStr, PackagePart parent)
        {
            // create part & relationship
            Uri         uri  = GetUri(uriStr);
            PackagePart part = Package.CreatePart(uri, contentType, PACKAGE_COMPRESSION_LEVEL);

            if (parent == null)
            {
                Package.CreateRelationship(uri, TargetMode.Internal, relType);
            }
            else
            {
                parent.CreateRelationship(uri, TargetMode.Internal, relType);
            }
            return(part);
        }
예제 #34
0
 private static void UlozitPackagePart(string strVystup, bool blnFormatovatOdsazeni, PackagePart documentPart)
 {
     if (documentPart == null)
     {
         return;
     }
     if (blnFormatovatOdsazeni)
     {
         try
         {
             XmlReaderSettings xrs = new XmlReaderSettings();
             xrs.CloseInput       = false;
             xrs.ConformanceLevel = ConformanceLevel.Document;
             xrs.IgnoreWhitespace = true;
             //xr = XmlReader.Create(documentPart.GetStream(), xrs);
             using (XmlReader xr = XmlReader.Create(documentPart.GetStream(), xrs))
             {
                 XmlWriterSettings xws = new XmlWriterSettings();
                 xws.CloseOutput      = true;
                 xws.ConformanceLevel = ConformanceLevel.Document;
                 xws.Indent           = true;
                 xws.IndentChars      = " ";
                 using (XmlWriter xw = XmlWriter.Create(strVystup, xws))
                 {
                     xw.WriteNode(xr, false);
                     //while (xr.Read()) {
                     //  xw.WriteNode(xr, false);
                     //  if (xr.IsEmptyElement && xr.Depth == 0)
                     //    xw.WriteNode(xr, false);
                     //}
                 }
             }
         }
         catch (Exception e)
         {
             throw e;
         }
     }
     else
     {
         StreamReader sr = new StreamReader(documentPart.GetStream());
         StreamWriter sw = new StreamWriter(strVystup, false, sr.CurrentEncoding);
         while (!sr.EndOfStream)
         {
             sw.WriteLine(sr.ReadLine());
         }
         sr.Close();
         sw.Close();
     }
 }
예제 #35
0
 internal ExcelOfPieChart(ExcelDrawings drawings, XmlNode node, Uri uriChart, PackagePart part, XmlDocument chartXml, XmlNode chartNode) :
     base(drawings, node, uriChart, part, chartXml, chartNode)
 {
     SetTypeProperties();
 }
예제 #36
0
        public static void ExtrahovatStylyDoSouboru(string strDocx, string strVystup, bool blnFormatovatOdsazeni)
        {
            if (!File.Exists(strDocx))
            {
                throw new FileNotFoundException("Soubor '" + strDocx + "' nebyl nalezen.");
            }

            using (FileStream fs = new FileStream(strDocx, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    using (Package wdPackage = Package.Open(sr.BaseStream))
                    {
                        PackageRelationship docPackageRelationship = wdPackage.GetRelationshipsByType(RelDocumentRelationshipType).FirstOrDefault();
                        if (docPackageRelationship != null)
                        {
                            Uri         documentUri  = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), docPackageRelationship.TargetUri);
                            PackagePart documentPart = wdPackage.GetPart(documentUri);

                            //  Find the styles part. There will only be one.

                            //chyba typu "Invalid URI: The hostname could not be parsed.", "Neplatný identifikátor URI. Nelze analyzovat název hostitele."
                            //dokument obsahuje pole typu HYPERLINK  neplatnými adresami
                            //http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/de46d25a-2bee-47d6-a4c7-0974a7036200
                            PackageRelationship styleRelation = documentPart.GetRelationshipsByType(RelStylesRelationshipType).FirstOrDefault();
                            if (styleRelation != null)
                            {
                                Uri         styleUri  = PackUriHelper.ResolvePartUri(documentUri, styleRelation.TargetUri);
                                PackagePart stylePart = wdPackage.GetPart(styleUri);
                                UlozitPackagePart(strVystup, blnFormatovatOdsazeni, stylePart);
                            }
                        }
                    }
                }
            }

            /*
             * using (Package wdPackage = Package.Open(strDocx, FileMode.Open, FileAccess.Read))
             * {
             *      PackageRelationship docPackageRelationship = wdPackage.GetRelationshipsByType(RelDocumentRelationshipType).FirstOrDefault();
             *      if (docPackageRelationship != null)
             *      {
             *              Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), docPackageRelationship.TargetUri);
             *              PackagePart documentPart = wdPackage.GetPart(documentUri);
             *
             *              //  Find the styles part. There will only be one.
             *
             *              //chyba typu "Invalid URI: The hostname could not be parsed.", "Neplatný identifikátor URI. Nelze analyzovat název hostitele."
             *              //dokument obsahuje pole typu HYPERLINK  neplatnými adresami
             *              //http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/de46d25a-2bee-47d6-a4c7-0974a7036200
             *              PackageRelationship styleRelation = documentPart.GetRelationshipsByType(RelStylesRelationshipType).FirstOrDefault();
             *              if (styleRelation != null)
             *              {
             *                      Uri styleUri = PackUriHelper.ResolvePartUri(documentUri, styleRelation.TargetUri);
             *                      PackagePart stylePart = wdPackage.GetPart(styleUri);
             *                      UlozitPackagePart(strVystup, blnFormatovatOdsazeni, stylePart);
             *              }
             *      }
             * }
             */
        }
예제 #37
0
        internal sealed override void DeleteRelationship(string id)
        {
            ThrowIfObjectDisposed();

            PackagePart.DeleteRelationship(id);
        }
예제 #38
0
 internal CommentsTable(PackagePart part, PackageRelationship rel)
     : base(part, rel)
 {
     ReadFrom(part.GetInputStream());
 }
예제 #39
0
        /// <summary>
        /// Returns the part content stream that was opened using a specified FileMode and FileAccess.
        /// </summary>
        /// <param name="mode">The I/O mode to be used to open the content stream.</param>
        /// <param name="access">The access permissions to be used to open the content stream.</param>
        /// <returns>The content stream of the part. </returns>
        public Stream GetStream(FileMode mode, FileAccess access)
        {
            ThrowIfObjectDisposed();

            return(PackagePart.GetStream(mode, access));
        }
        public void ShouldLogMessageWhenPackageIsCreated()
        {
            PackagePart newPackagePart = new PackagePart { Record = new PackagePartRecord(), PackageID = "foo", PackageVersion = "1.0" };
            var contentItem = new ContentItem { ContentType = "Package" };
            contentItem.Weld(newPackagePart);
            PublishedPackage publishedPackage = new PublishedPackage { Id = newPackagePart.PackageID, Version = newPackagePart.PackageVersion };

            _mockedOdataContext.SetupGet(oc => oc.Packages).Returns(new[] { publishedPackage }.AsQueryable());
            _mockedContentManager.Setup(cm => cm.New(It.IsAny<string>())).Returns(contentItem);

            _creator.CreateNewPackagePart(new PackageLogEntry { PackageId = newPackagePart.PackageID, PackageVersion = newPackagePart.PackageVersion });

            _mockedLogger.Verify(l => l.Log(LogLevel.Information, null, It.Is<string>(s => s.StartsWith("Created PackagePart")),
                It.IsAny<object[]>()), Times.Once());
        }
예제 #41
0
 public XWPFSettings(PackagePart part, PackageRelationship rel)
     : base(part, rel)
 {
 }
예제 #42
0
파일: Runner.cs 프로젝트: irium/Pepita
    void ProcessPart(string packagePath, PackagePart part)
    {
        var originalString = part.Uri.OriginalString;
        if (originalString.StartsWith("/_rels") || originalString.StartsWith("/package"))
        {
            return;
        }
        var fullPath = Path.GetFullPath(Path.Combine(packagePath, "." + originalString));
        Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

        if (Directory.Exists(fullPath))
        {
            return;
        }
        using (var stream = part.GetStream())
        using (var output = File.OpenWrite(fullPath))
        {
            stream.CopyTo(output);
        }
    }
예제 #43
0
        internal void NotifyContentDeleted(PackagePart packagePart)
        {
            // if the deleted file is being shown in the content pane, close the content pane
            if (CurrentFileInfo != null && CurrentFileInfo.File == packagePart) {
                CloseContentViewer();
            }

            NotifyChanges();
        }
        public void RemoveChild(PackagePart child)
        {
            if (child == null)
            {
                throw new ArgumentNullException("child");
            }

            bool removed = Children.Remove(child);
            if (removed)
            {
                child.Dispose();
                PackageViewModel.NotifyChanges();
            }
        }
예제 #45
0
 public void NoStartingSlashPartialUri()
 {
     PackagePart part = package.CreatePart(new Uri("file1.bmp", UriKind.Relative), "bmp");
 }
 /// <summary>
 /// Detach() is different from Remove() in that it doesn't dispose the child.
 /// </summary>
 /// <param name="child"></param>
 private void Detach(PackagePart child)
 {
     Children.Remove(child);
     child.Parent = null;
 }
예제 #47
0
        }// end:main()

        //<SnippetPackageWriteCreatePackage>
        //  -------------------------- CreatePackage --------------------------
        /// <summary>
        ///   Creates a package zip file containing specified
        ///   content and resource files.</summary>
        private static void CreatePackage()
        {
            //<SnippetPackageWriteCreatePartUri>
            // Convert system path and file names to Part URIs. In this example
            // Uri partUriDocument /* /Content/Document.xml */ =
            //     PackUriHelper.CreatePartUri(
            //         new Uri("Content\Document.xml", UriKind.Relative));
            // Uri partUriResource /* /Resources/Image1.jpg */ =
            //     PackUriHelper.CreatePartUri(
            //         new Uri("Resources\Image1.jpg", UriKind.Relative));
            Uri partUriDocument = PackUriHelper.CreatePartUri(
                new Uri(documentPath, UriKind.Relative));
            Uri partUriResource = PackUriHelper.CreatePartUri(
                new Uri(resourcePath, UriKind.Relative));

            //</SnippetPackageWriteCreatePartUri>

            // Create the Package
            // (If the package file already exists, FileMode.Create will
            //  automatically delete it first before creating a new one.
            //  The 'using' statement insures that 'package' is
            //  closed and disposed when it goes out of scope.)
            //<SnippetPackageWriteUsingPackage>
            using (Package package =
                       Package.Open(packagePath, FileMode.Create))
            {
                //<SnippetPackageWriteCreatePackageRelationship>
                //<SnippetPackageWriteCreatePart>
                // Add the Document part to the Package
                PackagePart packagePartDocument =
                    package.CreatePart(partUriDocument,
                                       System.Net.Mime.MediaTypeNames.Text.Xml);

                // Copy the data to the Document Part
                using (FileStream fileStream = new FileStream(
                           documentPath, FileMode.Open, FileAccess.Read))
                {
                    CopyStream(fileStream, packagePartDocument.GetStream());
                }// end:using(fileStream) - Close and dispose fileStream.
                 //</SnippetPackageWriteCreatePart>

                // Add a Package Relationship to the Document Part
                package.CreateRelationship(packagePartDocument.Uri,
                                           TargetMode.Internal,
                                           PackageRelationshipType);
                //</SnippetPackageWriteCreatePackageRelationship>

                //<SnippetPackageWriteCreateRelationship>
                // Add a Resource Part to the Package
                PackagePart packagePartResource =
                    package.CreatePart(partUriResource,
                                       System.Net.Mime.MediaTypeNames.Image.Jpeg);

                // Copy the data to the Resource Part
                using (FileStream fileStream = new FileStream(
                           resourcePath, FileMode.Open, FileAccess.Read))
                {
                    CopyStream(fileStream, packagePartResource.GetStream());
                }// end:using(fileStream) - Close and dispose fileStream.

                // Add Relationship from the Document part to the Resource part
                packagePartDocument.CreateRelationship(
                    new Uri(@"../resources/image1.jpg",
                            UriKind.Relative),
                    TargetMode.Internal,
                    ResourceRelationshipType);
                //</SnippetPackageWriteCreateRelationship>
            } // end:using (Package package) - Close and dispose package.
             //</SnippetPackageWriteUsingPackage>
        }     // end:CreatePackage()
예제 #48
0
 private void ClearPackagePartsWithRelationshipType(string relType, PackagePart parent)
 {
     ClearPackagePartsWithRelationshipType(relType, parent, null);
 }
 public bool Contains(PackagePart child)
 {
     // we can't call Children.Contains(child) here because that will only check by file name, not the actual instance
     return Children != null && Children.Any(p => p == child);
 }
예제 #50
0
 /**
  * Construct XWPFPictureData from a package part
  *
  * @param part the package part holding the Drawing data,
  * @param rel  the package relationship holding this Drawing,
  * the relationship type must be http://schemas.Openxmlformats.org/officeDocument/2006/relationships/image
  */
 public XWPFPictureData(PackagePart part, PackageRelationship rel)
     : base(part, rel)
 {
 }
 private void Attach(PackagePart child)
 {
     Children.Add(child);
     child.Parent = this;
 }
예제 #52
0
 protected override PackagePart [] GetPartsCore ()
 {
     PackagePart [] p = new PackagePart [Parts.Count];
     Parts.Values.CopyTo (p, 0);
     return p;
 }
        private XElement CreatePackage(PackagePart package, UrlHelper urlHelper, string baseUrl, IShapeDisplay shapeDisplay, dynamic shapeFactory) {
            var element = new XElement(atomns + "entry");

            dynamic content = package.ContentItem;
            string iconUrl = null;

            if (content.Package.Icon != null && content.Package.Icon.FirstMediaUrl != null) {
                iconUrl = (string)content.Package.Icon.FirstMediaUrl;
                iconUrl = shapeDisplay.Display(shapeFactory.ResizeMediaUrl(Path: iconUrl, Width: 64, Heigth: 64));
            }

            var screenshots = new XElement(atomns + "link",
                    new XAttribute("rel", "http://schemas.microsoft.com/ado/2007/08/dataservices/related/Screenshots"),
                    new XAttribute("type", "application/atom+xml;type=feed"),
                    new XAttribute("title", "Screenshots"),
                    new XAttribute("href", "Packages(Id='" + package.PackageId + "')/Screenshots")
                    );


            foreach (var media in (IEnumerable<dynamic>)content.Package.Screenshots.MediaParts) {

                string screenshotUrl = media.MediaUrl;
                screenshotUrl = shapeDisplay.Display(shapeFactory.ResizeMediaUrl(Path: screenshotUrl, Width: 164, Heigth: 128));

                screenshots.Add(
                    new XElement(mns + "inline",
                        new XElement(atomns + "feed",
                            new XElement(atomns + "title", "Screenshots", new XAttribute("type", "text")),
                            new XElement(atomns + "id", urlHelper.MakeAbsolute("/FeedService/Packages(Id='" + package.PackageId + "')/Screenshots", baseUrl)),
                            new XElement(atomns + "link",
                                new XAttribute("rel", "self"),
                                new XAttribute("title", "Screenshots"),
                                new XAttribute("href", "Packages(Id='" + package.PackageId + "')/Screenshots")
                                ),
                            new XElement(atomns + "entry",
                                new XElement(atomns + "id", urlHelper.MakeAbsolute("/FeedService.svc/Screenshots(" + (string)media.Id.ToString() + ")", baseUrl)),
                                new XElement(atomns + "title", media.ContentItem.TitlePart.Title, new XAttribute("type", "text")),
                                new XElement(atomns + "content", new XAttribute("type", "application/xml"),
                                    new XElement(mns + "properties",
                                        new XElement(dns + "Id", media.ContentItem.Id, new XAttribute(mns + "type", "Edm.Int32")),
                                        new XElement(dns + "PublishedPackageId", package.PackageId),
                                        new XElement(dns + "ScreenshotUri", urlHelper.MakeAbsolute(screenshotUrl, baseUrl)),
                                        new XElement(dns + "Caption", new XAttribute(mns + "null", "true"))
                                    )
                                )
                            )
                        )
                    )
                );
            }

            element.Add(
                new XElement(atomns + "id", urlHelper.MakeAbsolute(urlHelper.ItemDisplayUrl(package), baseUrl)),
                new XElement(atomns + "title", package.TitlePart.Title, new XAttribute("type", "text")),
                new XElement(atomns + "summary", package.Summary, new XAttribute("type", "text")),
                new XElement(atomns + "updated", package.LatestVersionUtc.ToString("o")),
                new XElement(atomns + "author",
                    new XElement(atomns + "name", package.CommonPart.Owner.UserName)
                    ),
                screenshots,
                // edit-media
                // edit
                //new XElement(atomns + "category",
                //    new XAttribute("term", "Gallery.Infrastructure.FeedModels.PublishedPackage"),
                //    new XAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme")
                //    ),
                new XElement(atomns + "content",
                    new XAttribute("type", "application/zip"),
                    new XAttribute("src", urlHelper.MakeAbsolute(urlHelper.Action("Download", "PackageVersion", new { id = package.PackageId, version = package.LatestVersion, area = "Orchard.Gallery" }), baseUrl))
                    ),
                new XElement(mns + "properties",
                    new XElement(dns + "Id", package.PackageId),
                    new XElement(dns + "Version", package.LatestVersion),
                    new XElement(dns + "Title", package.TitlePart.Title),
                    new XElement(dns + "Authors", package.CommonPart.Owner.UserName),
                    new XElement(dns + "PackageType", package.ExtensionType),
                    new XElement(dns + "Summary", package.Summary),
                    new XElement(dns + "Description", package.BodyPart.Text),
                    new XElement(dns + "Copyright", "", new XAttribute(mns + "null", "true")),
                    new XElement(dns + "PackageHashAlgorithm", ""),
                    new XElement(dns + "PackageHash", ""),
                    new XElement(dns + "PackageSize", new XAttribute(mns + "type", "Edm.Int64"), "0"),
                    new XElement(dns + "Price", "0", new XAttribute(mns + "type", "Edm.Decimal")),
                    new XElement(dns + "RequireLicenseAcceptance", "false", new XAttribute(mns + "type", "Edm.Boolean")),
                    new XElement(dns + "IsLatestVersion", "true", new XAttribute(mns + "type", "Edm.Boolean")),
                    new XElement(dns + "VersionRating", "5", new XAttribute(mns + "type", "Edm.Double")),
                    new XElement(dns + "VersionRatingsCount", "0", new XAttribute(mns + "type", "Edm.Int32")),
                    new XElement(dns + "VersionDownloadCount", package.DownloadCount, new XAttribute(mns + "type", "Edm.Int32")),
                    new XElement(dns + "Created", package.CommonPart.CreatedUtc.Value.ToString("o"), new XAttribute(mns + "type", "Edm.DateTime")),
                    new XElement(dns + "LastUpdated", package.LatestVersionUtc.ToString("o"), new XAttribute(mns + "type", "Edm.DateTime")),
                    new XElement(dns + "Published", package.CommonPart.PublishedUtc.Value.ToString("o"), new XAttribute(mns + "type", "Edm.DateTime")),
                    new XElement(dns + "ExternalPackageUrl", "", new XAttribute(mns + "null", "true")),
                    new XElement(dns + "ProjectUrl", package.ProjectUrl),
                    new XElement(dns + "LicenseUrl", package.LicenseUrl, new XAttribute(mns + "null", "true")),
                    new XElement(dns + "IconUrl", iconUrl),
                    new XElement(dns + "Rating", "5", new XAttribute(mns + "type", "Edm.Double")),
                    new XElement(dns + "RatingsCount", "0", new XAttribute(mns + "type", "Edm.Int32")),
                    new XElement(dns + "DownloadCount", package.DownloadCount, new XAttribute(mns + "type", "Edm.Int32")),
                    new XElement(dns + "Categories", ""),
                    new XElement(dns + "Tags", new XAttribute(XNamespace.Xml + "space", "preserve"), String.Join(" ", package.TagsPart.CurrentTags.ToArray())),
                    new XElement(dns + "Dependencies", ""),
                    new XElement(dns + "ReportAbuseUrl", ""),
                    new XElement(dns + "GalleryDetailsUrl", "")
                    )
            );

            return element;
        }
예제 #54
0
        public override bool Equals(Object obj)
        {
            /**
             * In case two objects ARE Equal, but its not the same instance, this
             * implementation will always run through the whole
             * byte-array-comparison before returning true. If this will turn into a
             * performance issue, two possible approaches are available:<br>
             * a) Use the Checksum only and take the risk that two images might have
             * the same CRC32 sum, although they are not the same.<br>
             * b) Use a second (or third) Checksum algorithm to minimise the chance
             * that two images have the same Checksums but are not equal (e.g.
             * CRC32, MD5 and SHA-1 Checksums, Additionally compare the
             * data-byte-array lengths).
             */
            if (obj == this)
            {
                return(true);
            }

            if (obj == null)
            {
                return(false);
            }

            if (!(obj is XWPFPictureData))
            {
                return(false);
            }

            XWPFPictureData picData            = (XWPFPictureData)obj;
            PackagePart     foreignPackagePart = picData.GetPackagePart();
            PackagePart     ownPackagePart     = this.GetPackagePart();

            if ((foreignPackagePart != null && ownPackagePart == null) ||
                (foreignPackagePart == null && ownPackagePart != null))
            {
                return(false);
            }

            if (ownPackagePart != null)
            {
                OPCPackage foreignPackage = foreignPackagePart.Package;
                OPCPackage ownPackage     = ownPackagePart.Package;

                if ((foreignPackage != null && ownPackage == null) ||
                    (foreignPackage == null && ownPackage != null))
                {
                    return(false);
                }
                if (ownPackage != null)
                {
                    if (!ownPackage.Equals(foreignPackage))
                    {
                        return(false);
                    }
                }
            }

            long foreignChecksum = picData.Checksum;
            long localChecksum   = Checksum;

            if (!(localChecksum.Equals(foreignChecksum)))
            {
                return(false);
            }
            return(Arrays.Equals(this.Data, picData.Data));
        }
        public void ShouldLogMessageWhenPackagePartAlreadyExists()
        {
            PackagePart newPackagePart = new PackagePart { Record = new PackagePartRecord(), PackageID = "foo", PackageVersion = "1.0" };
            var contentItem = new ContentItem { ContentType = "Package" };
            contentItem.Weld(newPackagePart);

            PublishedPackage publishedPackage = new PublishedPackage { Id = newPackagePart.PackageID, Version = newPackagePart.PackageVersion };

            _mockedOdataContext.SetupGet(oc => oc.Packages).Returns(new[] { publishedPackage }.AsQueryable());
            _mockedContentManager.Setup(cm => cm.New(It.IsAny<string>())).Returns(contentItem);
            _mockedPackageService.Setup(ps => ps.PackageExists(newPackagePart.PackageID, newPackagePart.PackageVersion, It.IsAny<VersionOptions>()))
                .Returns(true);

            _creator.CreateNewPackagePart(new PackageLogEntry { PackageId = newPackagePart.PackageID, PackageVersion = newPackagePart.PackageVersion });

            _mockedLogger.Verify(l => l.Log(LogLevel.Information, null, It.Is<string>(s => s.Contains("already exists in the gallery")),
                It.IsAny<object[]>()), Times.Once());
        }
예제 #56
0
 public ZipPackageFile(PackagePart part)
     : base(UriUtility.GetPath(part.Uri))
 {
     Debug.Assert(part != null, "part should not be null");
     _streamFactory = () => part.GetStream();
 }
예제 #57
0
        public Stream GetStream(FileMode mode)
        {
            ThrowIfObjectDisposed();

            return(PackagePart.GetStream(mode));
        }
예제 #58
0
        private PackagePart EnsurePackagePartWithRelationshipType(string relType, string contentType, string uriStr, PackagePart parent)
        {
            PackagePart part = GetSinglePackagePartWithRelationshipType(relType, parent);

            if (part == null)
            {
                part = CreatePackagePart(relType, contentType, uriStr, parent);
            }
            return(part);
        }
예제 #59
0
        public Stream GetStream()
        {
            ThrowIfObjectDisposed();

            return(PackagePart.GetStream());
        }
예제 #60
0
 /**
  * Construct a SpreadsheetML chart from a namespace part.
  *
  * @param part the namespace part holding the chart data,
  * the content type must be <code>application/vnd.Openxmlformats-officedocument.Drawingml.chart+xml</code>
  * @param rel  the namespace relationship holding this chart,
  * the relationship type must be http://schemas.Openxmlformats.org/officeDocument/2006/relationships/chart
  */
 protected XSSFChart(PackagePart part, PackageRelationship rel)
     : base(part, rel)
 {
     chartSpace = ChartSpaceDocument.Parse(part.GetInputStream()).GetChartSpace();
     chart      = chartSpace.chart;
 }