Ejemplo n.º 1
0
        public PBIXUtils(string pbixSourceFileName, string pbixTargetFileName)
        {
            _originalFile = pbixSourceFileName;
            _modifiedFile = pbixTargetFileName;

            File.Copy(_originalFile, _modifiedFile, true);

            _pbixPackage = (ZipPackage)ZipPackage.Open(_modifiedFile, FileMode.Open);
            var enumerator = _pbixPackage.GetParts().GetEnumerator();

            if (enumerator == null)
            {
                return;
            }

            while (enumerator.MoveNext() && (_mashup == null || _model == null))
            {
                var currentPart = enumerator.Current as ZipPackagePart;
                if (currentPart == null)
                {
                    continue;
                }

                if (currentPart.Uri.OriginalString.Contains("/DataMashup"))
                {
                    _mashup = currentPart;
                }
                else if (currentPart.Uri.OriginalString.Contains("/DataModel"))
                {
                    _model = currentPart;
                }
            }
        }
Ejemplo n.º 2
0
 public static Stream ExtractStreamFromZip(string zipFilename, string fileToExtract)
 {
     if (IsValidFile(zipFilename))
     {
         try
         {
             using (ZipPackage _package = (ZipPackage)Package.Open(zipFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
             {
                 PackagePartCollection _packageParts = _package.GetParts();
                 foreach (PackagePart _part in _packageParts)
                 {
                     if (_part.Uri.OriginalString == '/' + fileToExtract)
                     {
                         MemoryStream _stream = new MemoryStream();
                         CopyStream(_part.GetStream(), _stream as Stream);
                         return(_stream);
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             Loggy.Logger.ErrorException("Loading stream from metadata.", ex);
         }
     }
     return(null);
 }
Ejemplo n.º 3
0
 /// <summary>
 /// CORE - here is where we open the file denoted by the MstrPath value
 /// </summary>
 private void openFile()
 {
     toolStripButton1.Enabled = false;
     toolStripButton2.Enabled = true;
     this.Text = "[" + new FileInfo(MstrPath).Name + "]";
     // open the package
     using (ZipPackage LobjZip = (ZipPackage)ZipPackage.Open(MstrPath, FileMode.Open, FileAccess.Read))
     {
         // setup the root node
         TreeNode LobjRoot = treeView1.Nodes.Add("/", "/");
         // read all the parts
         foreach (ZipPackagePart LobjPart in LobjZip.GetParts())
         {
             // build a path string and...
             int    LintLen  = LobjPart.Uri.OriginalString.LastIndexOf("/");
             string LstrKey  = LobjPart.Uri.OriginalString;
             string LstrPath = LstrKey.Substring(0, LintLen);
             string LstrName = LstrKey.Substring(LintLen + 1);
             // set the parent, then
             TreeNode LobjParent = LobjRoot;
             if (LstrPath.Length != 0)
             {
                 LobjParent = FindClosestNode(LstrPath);
             }
             // add the node to the tree control
             LobjParent.Nodes.Add(LstrKey, LstrName);
         }
     }
     MobjPreviousNode = treeView1.Nodes[0];
     treeView1.Nodes[0].Expand();
 }
Ejemplo n.º 4
0
        }// end:CopyStream()

        private static void ExtractPackage(object p)
        {
            int errors = 0;

            using (ZipPackage zip = (ZipPackage)ZipPackage.Open(File.OpenRead("MCForge.zip"))) {
                PackagePartCollection pc = zip.GetParts();
                foreach (ZipPackagePart item in pc)
                {
                    try {
                        CopyStream(item.GetStream(), File.Create("./" + Uri.UnescapeDataString(item.Uri.ToString())));
                    } catch {
                        try {
                            Directory.CreateDirectory("./" + item.Uri.ToString().Substring(0, item.Uri.ToString().LastIndexOfAny("\\/".ToCharArray())));
                            CopyStream(item.GetStream(), File.Create("./" + Uri.UnescapeDataString(item.Uri.ToString())));
                        } catch (IOException e) {
                            Server.ErrorLog(e);
                            Server.s.Log("Caught ignoreable Error.  See log for more details.  Will continue with rest of files.");
                            errors++;
                        }
                    }
                    // To make life easier, we reload settings now, to maker it less likely to need restart
                    Command.all.Find("server").Use(null, "reload");        //Reload, as console
                    if (item.Uri.ToString().ToLower().Contains("sql.sql")) // If it's in there, they backed it up, meaning they want it restored
                    {
                        Database.fillDatabase(item.GetStream());
                    }
                }
            }
            Player.SendMessage((Player)p, "Server restored" + (errors > 0 ? " with errors.  May be a partial restore" : "") + ".  Restart is reccommended, though not required.");
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Reads a package zip file containing specified content and resource files.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool ExtractPackage(string packageName, string outputFolder, bool force = false)
        {
            CDFMonitor.LogOutputHandler("ReadPackage:processing package:" + packageName);

            try
            {
                if (!FileManager.FileExists(packageName))
                {
                    return(false);
                }

                // create subfolder for package files based on package name
                outputFolder = string.Format("{0}\\{1}", outputFolder, Path.GetFileNameWithoutExtension(packageName));

                if (FileManager.CheckPath(outputFolder))
                {
                    if (force)
                    {
                        FileManager.DeleteFolder(outputFolder);
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler("ReadPackage:output folder exists and no force. returning:" + packageName);
                        return(false);
                    }
                }

                if (!FileManager.CheckPath(outputFolder, true))
                {
                    return(false);
                }

                // Read the Package
                using (ZipPackage package = (ZipPackage)ZipPackage.Open(packageName, FileMode.Open))
                {
                    CDFMonitor.LogOutputHandler("ReadPackage:package open. retrieving parts");
                    foreach (PackagePart pP in package.GetParts())
                    {
                        DecompressStream(pP.GetStream(FileMode.Open, FileAccess.Read),
                                         string.Format("{0}\\{1}", outputFolder, pP.Uri.ToString().TrimStart('/')));
                    }
                }

                if (Directory.GetFiles(outputFolder).Length > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Status = e.ToString();
                CDFMonitor.LogOutputHandler("ReadPackage:exception:" + Status);
                return(false);
            }
        }
Ejemplo n.º 6
0
        public static void UnzipFiles(string zipLocation, string directory)
        {
            ZipPackage zipFile = ZipPackage.Open(zipLocation, FileMode.Open) as ZipPackage;

            foreach (ZipPackagePart part in zipFile.GetParts())
            {
                using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
                {
                    FileStream targetFile = File.OpenWrite(Path.Combine(directory, part.Uri.OriginalString.TrimStart('/')));
                    source.CopyTo(targetFile);
                    targetFile.Close();
                }
            }
        }
Ejemplo n.º 7
0
        public void TestTidyStreamOnInvalidFile()
        {
            // Spreadsheet has a good mix of alternate file types
            POIDataSamples files = POIDataSamples.GetSpreadSheetInstance();

            FileInfo[] notValidF = new FileInfo[] {
                files.GetFileInfo("SampleSS.ods"), files.GetFileInfo("SampleSS.txt")
            };
            Stream[] notValidS = new Stream[] {
                files.OpenResourceAsStream("SampleSS.ods"), files.OpenResourceAsStream("SampleSS.txt")
            };
            foreach (FileInfo notValid in notValidF)
            {
                ZipPackage pkg = new ZipPackage(notValid, PackageAccess.READ);
                Assert.IsNotNull(pkg.ZipArchive);
                Assert.IsFalse(pkg.ZipArchive.IsClosed);
                try
                {
                    pkg.GetParts();
                    Assert.Fail("Shouldn't work");
                }
                catch (ODFNotOfficeXmlFileException e)
                {
                }
                catch (NotOfficeXmlFileException ne) { }
                pkg.Close();

                Assert.IsNotNull(pkg.ZipArchive);
                Assert.IsTrue(pkg.ZipArchive.IsClosed);
            }
            foreach (InputStream notValid in notValidS)
            {
                ZipPackage pkg = new ZipPackage(notValid, PackageAccess.READ);
                Assert.IsNotNull(pkg.ZipArchive);
                Assert.IsFalse(pkg.ZipArchive.IsClosed);
                try
                {
                    pkg.GetParts();
                    Assert.Fail("Shouldn't work");
                }
                catch (ODFNotOfficeXmlFileException e)
                {
                }
                catch (NotOfficeXmlFileException ne) { }
                pkg.Close();

                Assert.IsNotNull(pkg.ZipArchive);
                Assert.IsTrue(pkg.ZipArchive.IsClosed);
            }
        }
Ejemplo n.º 8
0
        public void ReplaceKnownVariable(string variable, string newValue)
        {
            string     packagePartsTempLocation = Path.GetTempFileName();
            ZipPackage partsPackage             = GetPackageParts(packagePartsTempLocation);

            var parts      = partsPackage.GetParts();
            var enumerator = parts.GetEnumerator();

            ZipPackagePart mCodePart = null;

            while (enumerator.MoveNext())
            {
                if (enumerator.Current.Uri.OriginalString.Contains("/Formulas/Section1.m"))
                {
                    mCodePart = (ZipPackagePart)enumerator.Current;
                    break;
                }
            }

            string theMCode;

            using (StreamReader mCodeReader = new StreamReader(mCodePart.GetStream()))
            {
                theMCode = mCodeReader.ReadToEnd();
            }

            string pattern      = "^shared\\s*" + variable + "\\s*=\\s*\"\\S*\"";
            Regex  r            = new Regex(pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase);
            string updatedMCode = r.Replace(theMCode, string.Format(CultureInfo.InvariantCulture, "shared {0} = \"{1}\"", variable, newValue));

            byte[] updateMCodeBytes = Encoding.UTF8.GetBytes(updatedMCode);
            mCodePart.GetStream().Write(updateMCodeBytes, 0, updateMCodeBytes.Length);
            mCodePart.GetStream().SetLength(updateMCodeBytes.Length);

            mCodePart.GetStream().Flush();
            partsPackage.Close();

            FileInfo fi = new FileInfo(packagePartsTempLocation);

            _packagePartsLength = Convert.ToUInt32(fi.Length);
            _packageParts       = File.ReadAllBytes(packagePartsTempLocation);

            File.Delete(packagePartsTempLocation);
        }
Ejemplo n.º 9
0
 public static bool HasStream(string zipFilename, string partName)
 {
     if (IsValidFile(zipFilename))
     {
         using (ZipPackage _package = (ZipPackage)Package.Open(zipFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
         {
             PackagePartCollection _packageParts = _package.GetParts();
             foreach (PackagePart _part in _packageParts)
             {
                 if (_part.Uri.OriginalString == '/' + partName)
                 {
                     Stream _st = _part.GetStream();
                     return(_st != null && _st.Length != 0);
                 }
             }
         }
     }
     return(false);
 }
Ejemplo n.º 10
0
        public static void ExtractPackage(Player p)
        {
            int errors = 0;

            using (FileStream src = File.OpenRead(path))
                using (ZipPackage zip = (ZipPackage)ZipPackage.Open(src))
                {
                    PackagePartCollection parts = zip.GetParts();
                    foreach (ZipPackagePart item in parts)
                    {
                        ExtractItem(item, ref errors);
                        if (item.Uri.ToString().ToLower().Contains("sql.sql"))
                        {
                            // If it's in there, they backed it up, meaning they want it restored
                            Backup.ReplaceDatabase(item.GetStream());
                        }
                    }
                }

            // To make life easier, we reload settings now, to maker it less likely to need restart
            Command.all.Find("server").Use(null, "reload"); // Reload, as console
            Player.Message(p, "Server restored" + (errors > 0 ? " with errors.  May be a partial restore" : "") + ".  Restart is reccommended, though not required.");
        }
Ejemplo n.º 11
0
        public string getEPCFIleText(String epcPathFile, String partFileName)
        {
            String xmlcontent = "";

            using (ZipPackage package = (ZipPackage)Package.Open(epcPathFile, FileMode.Open, FileAccess.Read))
            {
                PackagePartCollection packageParts = package.GetParts();
                foreach (PackagePart packagepart in packageParts)
                {
                    if (packagepart.Uri.ToString().CompareTo(partFileName) == 0)
                    {
                        Stream stream = null;
                        lock (locker)
                        {
                            try
                            {
                                stream = packagepart.GetStream(FileMode.Open, FileAccess.Read);
                                using (StreamReader reader = new StreamReader(stream))
                                {
                                    xmlcontent = reader.ReadToEnd();
                                }
                            }catch (Exception e)
                            {
                                throw e;
                            }
                            finally
                            {
                                stream.Close();
                            }
                        }
                        return(xmlcontent);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 12
0
        public List <string> DownloadAndUncompress(ReleaseInfo releaseInfo)
        {
            if (ArchiveDownloadUpdate != null)
            {
                ArchiveDownloadUpdate(this, new ArchiveDownloadEventArgs(releaseInfo, ArchiveDownloadStatus.DOWNLOADING));
            }
            //
            string destinationFolder = Path.Combine(updateFolder, "files");
            string archiveName       = Path.Combine(updateFolder, "archives", "hg_update_" + releaseInfo.Version.Replace(" ", "_").Replace(".", "_") + ".zip");

            if (!Directory.Exists(Path.GetDirectoryName(archiveName)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(archiveName));
            }
            using (var client = new WebClient())
            {
                client.Headers.Add("user-agent", "HomeGenieUpdater/1.0 (compatible; MSIE 7.0; Windows NT 6.0)");
                try
                {
                    client.DownloadFile(releaseInfo.DownloadUrl, archiveName);
                }
                catch (Exception)
                {
                    if (ArchiveDownloadUpdate != null)
                    {
                        ArchiveDownloadUpdate(this, new ArchiveDownloadEventArgs(releaseInfo, ArchiveDownloadStatus.ERROR));
                    }
                    return(null);
                    //                throw;
                }
                finally
                {
                    client.Dispose();
                }
            }
            // Unarchive (unzip)
            if (ArchiveDownloadUpdate != null)
            {
                ArchiveDownloadUpdate(this, new ArchiveDownloadEventArgs(releaseInfo, ArchiveDownloadStatus.DECOMPRESSING));
            }

            bool errorOccurred = false;
            var  files         = new List <string>();

            try
            {
                using (ZipPackage package = (ZipPackage)Package.Open(archiveName, FileMode.Open, FileAccess.Read))
                {
                    foreach (PackagePart part in package.GetParts())
                    {
                        string target = Path.Combine(destinationFolder, part.Uri.OriginalString.Substring(1)).TrimStart(Directory.GetDirectoryRoot(Directory.GetCurrentDirectory()).ToArray()).TrimStart('/');
                        if (!Directory.Exists(Path.GetDirectoryName(target)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(target));
                        }

                        if (File.Exists(target))
                        {
                            File.Delete(target);
                        }

                        using (Stream source = part.GetStream(
                                   FileMode.Open, FileAccess.Read))
                            using (Stream destination = File.OpenWrite(target))
                            {
                                byte[] buffer = new byte[4096];
                                int    read;
                                while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    destination.Write(buffer, 0, read);
                                }
                            }
                        files.Add(target);
                        //Console.WriteLine("Deflated {0}", target);
                    }
                }
            }
            catch (Exception)
            {
                errorOccurred = true;
            }

            if (ArchiveDownloadUpdate != null)
            {
                if (errorOccurred)
                {
                    ArchiveDownloadUpdate(this, new ArchiveDownloadEventArgs(releaseInfo, ArchiveDownloadStatus.ERROR));
                }
                else
                {
                    ArchiveDownloadUpdate(this, new ArchiveDownloadEventArgs(releaseInfo, ArchiveDownloadStatus.COMPLETED));
                }
            }

            return(files);
        }
Ejemplo n.º 13
0
        // read file property in core.xml, find out the creator, datatime...
        // read [content_types].xml, find out the total file contains in the zip.
        // read _rels folder, find out the files relationship, find out the child of objects.
        // .rels contains define the ocreproperties.
        public EPCDataView readEPCFile(String epcPathFile)
        {
            // must has [content_Types].xml
            // /_rels/.rels must contain at least the metadata/core-properties and target. which resqml example doesnt' following.
            // core properties should contains creator, created, version description, id, title
            Dictionary <string, EPCObject> TopObjectList = new Dictionary <string, EPCObject>();
            List <EPCObject> listObjects = new List <EPCObject>();
            EPCCoreProperty  epcCore     = new EPCCoreProperty();

            List <KeyValuePair <String, EPCObject> > parentChild = new List <KeyValuePair <String, EPCObject> >();

            try
            {
                using (ZipPackage package = (ZipPackage)Package.Open(epcPathFile, FileMode.Open, FileAccess.Read))
                {
                    PackageRelationshipCollection packageRels = package.GetRelationships();
                    //package Rels must contains id "CoreProperties" property. getTargetUri directory.
                    String sourceURI = "";
                    String coreURI   = getCorePropertyURI(packageRels, ref sourceURI);
                    PackagePartCollection packageParts = package.GetParts();
                    foreach (PackagePart packagepart in packageParts)
                    {
                        // match the coreURI.
                        // find the coreProperty
                        if ((packagepart.Uri != null) && (packagepart.Uri.Equals(sourceURI + coreURI)))
                        {
                            epcCore.Creator     = packagepart.Package.PackageProperties.Creator;
                            epcCore.Created     = packagepart.Package.PackageProperties.Created;
                            epcCore.Version     = packagepart.Package.PackageProperties.Version;
                            epcCore.Description = packagepart.Package.PackageProperties.Description;
                            epcCore.Identifier  = packagepart.Package.PackageProperties.Identifier;
                            epcCore.Keywords    = packagepart.Package.PackageProperties.Keywords;
                            epcCore.Title       = packagepart.Package.PackageProperties.Title;
                        }
                        else
                        {
                            // create each epcobject for package part
                            if (isPart(packagepart))
                            {
                                EPCObject epcObject      = new EPCObject();
                                String    epcContentType = "";
                                String    version        = "";
                                String    epcObjectType  = "";
                                EPCPartValidator.parseContentType(packagepart.ContentType, ref epcContentType, ref version, ref epcObjectType);
                                epcObject.EpcContentType = epcContentType;
                                epcObject.EPCObjectType  = epcObjectType;
                                epcObject.SchemaVersion  = version;
                                epcObject.PackageFile    = epcPathFile;
                                epcObject.EpcFileName    = this.getfilename(packagepart.Uri.ToString());
                                epcObject.Uuid           = this.getuuid(packagepart.Uri.ToString());
                                epcObject.Uri            = packagepart.Uri;
                                listObjects.Add(epcObject);
                                //get rest relationship items
                                PackageRelationshipCollection partRels = null;
                                try
                                {
                                    if (packagepart != null)
                                    {
                                        partRels = packagepart.GetRelationships();
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("warning : " + e.Message);
                                }
                                if (partRels != null)
                                {
                                    // create pair key for relationships parent and child
                                    foreach (PackageRelationship partsRel in partRels)
                                    {
                                        EPCRelationshipType epcrelType = EPCPartValidator.getRelationshipType(partsRel.RelationshipType);
                                        // conver the target and source into the parent and child table.
                                        if ((epcrelType == EPCRelationshipType.destinationObject) ||
                                            (epcrelType == EPCRelationshipType.mlToExternalPartProxy) ||
                                            (epcrelType == EPCRelationshipType.destinationMedia) ||
                                            (epcrelType == EPCRelationshipType.externalResource) ||
                                            (epcrelType == EPCRelationshipType.chunkedPart)
                                            )
                                        {
                                            string name = getfilename(packagepart.Uri.ToString());
                                            //string childname =  getfilename(partsRel.TargetUri.ToString());
                                            EPCObject obj = new EPCObject();
                                            obj.TargetMode  = partsRel.TargetMode;;
                                            obj.EpcFileName = partsRel.TargetUri.ToString();
                                            if ((obj.TargetMode == TargetMode.External) && (obj.EpcFileName.EndsWith(".h5")))
                                            {
                                                obj.HDF5 = true;
                                                epcObject.EpcFileName = obj.EpcFileName;
                                                epcObject.HDF5        = true;
                                            }
                                            KeyValuePair <string, EPCObject> pair = new KeyValuePair <string, EPCObject>(name, obj);
                                            if (!isDuplicated(parentChild, pair))
                                            {
                                                parentChild.Add(pair);
                                            }
                                            //else
                                            //Console.WriteLine("source already add in. skip ...");
                                        }
                                        if ((epcrelType == EPCRelationshipType.sourceObject) ||
                                            (epcrelType == EPCRelationshipType.extenalPartProxyToMI) ||
                                            (epcrelType == EPCRelationshipType.sourceMedia))
                                        {
                                            string    name      = getfilename(partsRel.TargetUri.ToString());
                                            string    childname = getfilename(packagepart.Uri.ToString());
                                            EPCObject obj       = new EPCObject();
                                            obj.TargetMode  = partsRel.TargetMode;;
                                            obj.EpcFileName = childname;
                                            KeyValuePair <string, EPCObject> pair = new KeyValuePair <string, EPCObject>(name, obj);
                                            if (!isDuplicated(parentChild, pair))
                                            {
                                                parentChild.Add(pair);
                                            }
                                            //else
                                            //Console.WriteLine("source already add in. skip ...");
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //sort the hierachy from the pair
                    listObjects.Sort(new EPCObjectComparer());
                    TopObjectList = sortHierarchy(parentChild, listObjects);
                    // assign to dataviewer.
                    EPCDataView dataviewer = new EPCDataView();
                    dataviewer.TopObjectList   = TopObjectList;
                    dataviewer.ListObjects     = listObjects;
                    dataviewer.EpcCoreProperty = epcCore;
                    return(dataviewer);
                }
            }catch (Exception e)
            {
                throw new Exception(String.Format("the file is not validate EPC file : {0} ", e.Message));
            }
        }