Exemplo n.º 1
0
 //TODO: Clean this up
 private void LoadModInfo()
 {
     if (this.IsZip == true)
     {
         string entrypath;
         ZipFile zip = new ZipFile(this.Path);
         
         entrypath = "readme.txt";
         if (zip.ContainsEntry(entrypath))
         {
             MemoryStream stream = new MemoryStream();
             zip[entrypath].Extract(stream);
             stream.Position = 0;
             var sr = new StreamReader(stream);
             this.Text = sr.ReadToEnd();
         }
         entrypath = "picture.png";
         if (zip.ContainsEntry(entrypath))
         {
             MemoryStream stream = new MemoryStream();
             zip[entrypath].Extract(stream);
             //stream.Position = 0;
             this.Image = System.Drawing.Image.FromStream(stream);
         }
     }
     else
     {
         string filepath;
         //Look for mod description
         filepath = this.Path + "readme.txt";
         if (File.Exists(filepath))
         {
             this.Text = File.ReadAllText(filepath);
         }
         else
         {
             string[] files = Directory.GetFiles(this.Path, "*.txt");
             foreach (string fpath in files)
             {
                 if (File.Exists(fpath))
                 {
                     this.Text = File.ReadAllText(fpath);
                     break;
                 }
             }
         }
         //Look for mod picture
         //TODO: Look for .jpg and also any picture if 'picture.png' is not found.
         filepath = this.Path + "picture.png";
         if (File.Exists(filepath))
         {
             this.Image = System.Drawing.Image.FromFile(filepath);
         }
     }
 }
 protected override Stream GetFileStream(string file, string path)
 {
     ZipFile zip = new ZipFile(file + ".mod");
     if (!zip.ContainsEntry(path)) throw new ArgumentException("File " + path.ToString() + " Does not exist in mod!");
     ZipEntry entry = zip[path];
     return entry.OpenReader();
 }
Exemplo n.º 3
0
 private void LoadJPGTextures(ZipFile pk3)
 {
     foreach (Texture tex in Textures)
     {
         // The size of the new Texture2D object doesn't matter. It will be replaced (including its size) with the data from the .jpg texture that's getting pulled from the pk3 file.
         if (pk3.ContainsEntry(tex.Name + ".jpg"))
         {
             Texture2D readyTex = new Texture2D(4, 4);
             var entry = pk3 [tex.Name + ".jpg"];
             using (var stream = entry.OpenReader())
             {
                 var ms = new MemoryStream();
                 entry.Extract(ms);
                 readyTex.LoadImage(ms.GetBuffer());
             }
             
             readyTex.name = tex.Name;
             readyTex.filterMode = FilterMode.Trilinear;
             readyTex.Compress(true);
             
             if (readyTextures.ContainsKey(tex.Name))
             {
                 Debug.Log("Updating texture with name " + tex.Name);
                 readyTextures [tex.Name] = readyTex;
             } else
                 readyTextures.Add(tex.Name, readyTex);
         }
     }
 }
Exemplo n.º 4
0
        } // End UnZip

        /// <summary>
        /// Unzip a stream that represents a zip file and return the first entry as a stream
        /// </summary>
        public static Stream UnzipStream(Stream zipstream, out ZipFile zipFile, string entryName = null)
        {
            zipFile = ZipFile.Read(zipstream);

            try
            {
                Ionic.Zip.ZipEntry entry;
                if (string.IsNullOrEmpty(entryName))
                {
                    //Read the file entry into buffer:
                    entry = zipFile.Entries.FirstOrDefault();
                }
                else
                {
                    // Attempt to find our specific entry
                    if (!zipFile.ContainsEntry(entryName))
                    {
                        return(null);
                    }
                    entry = zipFile[entryName];
                }

                if (entry != null)
                {
                    return(entry.OpenReader());
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
            }

            return(null);
        } // End UnZip
Exemplo n.º 5
0
        ModInfo GetModInfoFromTapiZip(ZipFile zf)
        {
            if (zf.ContainsEntry("ModInfo.json"))
            {
                ZipEntry ze = zf["ModInfo.json"];

                using (MemoryStream ms = new MemoryStream())
                {
                    ze.Extract(ms);

                    StreamReader r = new StreamReader(ms);

                    ModInfo mi = new ModInfo(Compiler) { checkCircularRefs = false };

                    var err = mi.CreateAndValidate(new JsonFile(zf.Name, JsonMapper.ToObject(r.ReadToEnd())));

                    if (!Compiler.CreateOutput(err.ToList()).Succeeded)
                        return null;

                    return mi;
                }
            }

            if (zf.ContainsEntry("Mod.tapimod"))
                using (MemoryStream ms = new MemoryStream())
                {
                    return GetModInfoFromTapiMod(ms.ToArray());
                }

            return null;
        }
Exemplo n.º 6
0
 public static void AddPackageContents(string sourcePackage, string additionalPackage, string uniquPackageName1)
 {
     using (var zip = new ZipFile(sourcePackage))
     {
         using (var zip2 = new ZipFile(additionalPackage))
         {
             foreach (var entry in zip2)
             {
                 try
                 {
                     if (! zip.ContainsEntry(entry.FileName))
                     {
                         var entry1 = zip.AddEntry(entry.FileName, entry.OpenReader());
                         if (entry.FileName == "package.config")
                             entry1.FileName = uniquPackageName1 + ".config";
                         zip.Save();
                     }
                 }
                 catch (Exception e)
                 {
                     Console.WriteLine(e);
                 }
             }
             //zip.Save();
         }
     }
 }
 protected override bool ExistsInPath(string file, string path)
 {
     using(ZipFile zip = new ZipFile(file + ".mod"))
     {
         return zip.ContainsEntry(path);
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Given the target folder, it will unzip any zips, and then send folders with imsmanifest.xml into manifest parser.
        /// </summary>
        /// <param name="topDirectory"></param>
        /// <param name="reportFile"></param>
        public static void UnzipFilesWithManifest(string topDirectory)
        {
            string[] zipsList = Directory.GetFiles(topDirectory, "*.zip");
            string extractionDestination;

            // Extract zips --------------------------------------------------------------------------------
            if (zipsList.Length > 0)
            {
                Console.WriteLine("---------- EXTRACTING ZIPS           ----------\n");
                for (int i = 0; i < zipsList.Length; i++)
                {
                    ZipFile zipFolder = new ZipFile(zipsList[i]);
                    // Generate extact folder name
                    extractionDestination = zipFolder.Name.Replace(".zip", "");

                    // If that folder already exists, skip
                    if (!Directory.Exists(extractionDestination))
                    {
                        Console.WriteLine("About to extract  " + zipFolder.Name);
                        // If the zipFile doesn't have the manifest, don't extract. There won't be a manifest to parse
                        if (zipFolder.ContainsEntry("imsmanifest.xml"))
                        {
                            zipFolder.ExtractAll(extractionDestination);
                            Console.WriteLine("\tExtracted " + zipFolder.Name + "\n");
                        }
                        else
                        {
                            Console.WriteLine("\tManifest file was not found\n");
                        }
                    }
                }
                Console.WriteLine("---------- FINISHED EXTRACTING ZIPS  ----------\n\n");
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Create a new PebbleBundle from a .pwb file and parse its metadata.
        /// </summary>
        /// <param name="path">The relative or full path to the file.</param>
        public PebbleBundle(String path)
        {
            Stream jsonstream;
            Stream binstream;

            FullPath = Path.GetFullPath(path);
            Bundle = ZipFile.Read(FullPath);

            if (Bundle.ContainsEntry("manifest.json"))
            {
                jsonstream = Bundle["manifest.json"].OpenReader();
            }
            else
            {
                throw new ArgumentException("manifest.json not found in archive - not a Pebble bundle.");
            }

            var serializer = new DataContractJsonSerializer(typeof(BundleManifest));

            Manifest = serializer.ReadObject(jsonstream) as BundleManifest;
            jsonstream.Close();

            HasResources = (Manifest.Resources.Size != 0);

            if (Manifest.Type == "firmware")
            {
                BundleType = BundleTypes.Firmware;
            }
            else
            {
                BundleType = BundleTypes.Application;
                if (Bundle.ContainsEntry(Manifest.Application.Filename))
                {
                    binstream = Bundle[Manifest.Application.Filename].OpenReader();
                }
                else
                {
                    String format = "App file {0} not found in archive";
                    throw new ArgumentException(String.Format(format, Manifest.Application.Filename));
                }

                Application = Util.ReadStruct<ApplicationMetadata>(binstream);
                binstream.Close();
            }
        }
Exemplo n.º 10
0
        public virtual IEnumerable<LayoutSample> GetLayoutSamples(string engineName)
        {
            var itemTemplates = this.All(engineName);

            foreach (var item in itemTemplates)
            {
                using (ZipFile zipFile = new ZipFile(item.TemplateFile))
                {
                    var settingEntryName = PathResource.SettingFileName;
                    if (!zipFile.ContainsEntry(settingEntryName))
                    {
                        throw new KoobooException("The layout item template is invalid, setting.config is required.");
                    }
                    Layout layout = null;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        zipFile[settingEntryName].Extract(ms);
                        ms.Position = 0;
                        layout = (Layout)Kooboo.Runtime.Serialization.DataContractSerializationHelper.Deserialize(typeof(Layout), null, ms);
                    }
                    var templateEntryName = layout.TemplateFileName;
                    if (!zipFile.ContainsEntry(templateEntryName))
                    {
                        throw new KoobooException(string.Format("The layout item template is invalid.{0} is requried.", templateEntryName));
                    }
                    LayoutSample sample = new LayoutSample() { Name = item.TemplateName, ThumbnailVirtualPath = item.Thumbnail };
                    using (MemoryStream ms = new MemoryStream())
                    {
                        zipFile[templateEntryName].Extract(ms);
                        ms.Position = 0;
                        using (StreamReader sr = new StreamReader(ms))
                        {
                            sample.Template = sr.ReadToEnd();
                        }
                    }
                    yield return sample;
                }
            }
        }
Exemplo n.º 11
0
 public static byte[] ReadFileFromZip(ZipFile zip, string filename)
 {
     if (zip.ContainsEntry (filename)) {
         var entry = zip.FirstOrDefault (x => x.FileName == filename);
         if (entry != null) {
             using (var ms = new MemoryStream ()) {
                 entry.Extract (ms);
                 return ms.ToArray ();
             }
         }
     }
     return null;
 }
        public void TestZipDirectory()
        {
            //create three directories in our zip dir
            string zipDir = Path.Combine(TestContext.TestDeploymentDir, "zipDir");
            string zipInner1Dir = Path.Combine(zipDir, "testDir1");
            string zipInner2Dir = Path.Combine(zipDir, "testDir2");
            string zipInner3Dir = Path.Combine(zipDir, "testDir3");
            string zipInnerInner3Dir = Path.Combine(zipInner2Dir, "testDir3");
            string zipInnerInner4Dir = Path.Combine(zipInner2Dir, "testDir4");

            Directory.CreateDirectory(zipDir);
            Directory.CreateDirectory(zipInner1Dir);
            Directory.CreateDirectory(zipInner2Dir);
            Directory.CreateDirectory(zipInner3Dir);
            Directory.CreateDirectory(zipInnerInner3Dir);
            Directory.CreateDirectory(zipInnerInner4Dir);

            //zip but exclude some of the dirs
            IZip zip = new DotNetZipAdapter();
            using (MemoryStream ms = zip.ZipDirectory(zipDir, String.Format("{0};{1};{2}", "\\testDir1", "/testDir3", "/testDir2/testDir4")))
            {
                string zipPath = Path.Combine(TestContext.TestDir, "test.zip");
                ms.Position = 0;
                byte[] buff = new byte[ms.Length];
                ms.Read(buff, 0, buff.Length);
                File.WriteAllBytes(zipPath, buff);

                //make sure testDir2 and testDir2//testDir3 are only dir in zip file
                using (ZipFile z = new ZipFile(zipPath))
                {
                    Assert.IsTrue(z.ContainsEntry("testDir2/"));
                    Assert.IsTrue(z.ContainsEntry("testDir2/testDir3/"));
                    Assert.IsTrue(!z.ContainsEntry("testDir1/"));
                    Assert.IsTrue(!z.ContainsEntry("testDir3/"));
                    Assert.IsTrue(!z.ContainsEntry("testDir2/testDir4/"));
                }//end using
            }//end using
        }
Exemplo n.º 13
0
        public void WhenIProduceAPackageAndAskForAZipFile_IShouldRecieveAZipFile()
        {
            ClearFolders(_oldFolderLocation, _newFolderLocation, _patchFolderLocation);
            AddFileToFolder(_newFolderLocation, "addFile.txt");
            Directory.CreateDirectory(_oldFolderLocation);
            var patchFileLocation = _patchFolderLocation + "\\patch.zip";
            KaBlooeyEngine.CreatePatchIntoZip(_oldFolderLocation, _newFolderLocation, patchFileLocation);

            var result = File.Exists(patchFileLocation);
            Assert.AreEqual(true, result);

            using (Ionic.Zip.ZipFile file = new ZipFile(patchFileLocation))
            {
                Assert.IsTrue(file.ContainsEntry("addFile.txt.add"));
            }
        }
Exemplo n.º 14
0
 public static void LoadTerrainTextures()
 {
     // TODO: This only works on 1.4.7 and earlier
     Bitmap terrain;
     if (File.Exists("terrain.png"))
         terrain = (Bitmap)Image.FromFile("terrain.png");
     else
     {
         if (File.Exists(Path.Combine(DotMinecraft.GetDotMinecraftPath(), "bin", "minecraft.jar")))
         {
             using (var file = new ZipFile(Path.Combine(DotMinecraft.GetDotMinecraftPath(), "bin", "minecraft.jar")))
             {
                 if (file.ContainsEntry("terrain.png"))
                 {
                     var ms = new MemoryStream();
                     file["terrain.png"].Extract(ms);
                     ms.Seek(0, SeekOrigin.Begin);
                     terrain = (Bitmap)Image.FromStream(ms);
                 }
                 else
                     throw new FileNotFoundException("Missing terrain.png!");
             }
         }
         else
             throw new FileNotFoundException("Missing terrain.png!");
     }
     // Load into OpenGL
     TerrainId = GL.GenTexture();
     GL.BindTexture(TextureTarget.Texture2D, TerrainId);
     var data = terrain.LockBits(new Rectangle(0, 0, terrain.Width, terrain.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
     GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height,
         0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
     terrain.UnlockBits(data);
     // Disable mipmaps?
     GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
     GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
 }
Exemplo n.º 15
0
 private bool HasZipEntry(string filename)
 {
     using (var file = new ZipFile(_zipFile))
       {
     return file.ContainsEntry(filename);
       }
 }
Exemplo n.º 16
0
        private void AddToZip(string name, byte[] data)
        {
            using (var file = new ZipFile(_zipFile))
              {
            if (file.ContainsEntry(name))
            {
              file.UpdateEntry(name, data);
            }
            else
            {
              file.AddEntry(name, data);
            }

            file.Save();
              }
        }
        public void CreateZipFiles()
        {
            //Delete old zipfiles
            if (Directory.Exists(zipDirectory))
            {
                Directory.Delete(zipDirectory, true);
            }
            Directory.CreateDirectory(zipDirectory);

            //Create empty zipfiles
            using (ZipOutputStream zos = new ZipOutputStream(zipDirectory + "\\ClientFiles.zip"))
            { }
            using (ZipOutputStream zos = new ZipOutputStream(zipDirectory + "\\ServerFiles.zip"))
            { }

            //Create list of resourcepacks
            List <string> rpackList = new List <string>();

            using (FileStream fs = File.Open(cd + "\\resourcepack\\distribute.txt", FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    while (true)
                    {
                        string nextLine = sr.ReadLine();

                        if (nextLine != null)
                        {
                            rpackList.Add(nextLine);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            //Create client zipfile
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zipDirectory + "\\ClientFiles.zip"))
            {
                //Add modpack folders
                foreach (string folder in Directory.GetDirectories(cd + "\\modpack", "*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(folder))
                    {
                        zip.RemoveEntry(folder);
                    }
                    zip.AddDirectoryByName(folder.Replace(cd + "\\modpack", ""));
                }
                //Add resourcepacks
                foreach (string file in Directory.GetFiles(cd + "\\resourcepack", "*.zip", SearchOption.TopDirectoryOnly))
                {
                    if (rpackList.Contains(Path.GetFileName(file)))
                    {
                        if (zip.ContainsEntry(file))
                        {
                            zip.RemoveEntry(file);
                        }
                        zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\resourcepack", "resourcepacks"));
                    }
                }
                //Add modpack files
                foreach (string file in Directory.GetFiles(cd + "\\modpack", "*.*", SearchOption.AllDirectories))
                {
                    if ((Main.acces.includeOptionsBox.Checked || (!file.Contains("\\modpack\\options.txt") && !file.Contains("\\modpack\\optionsof.txt"))) && (Main.acces.includeDisabledBox.Checked || Path.GetExtension(file) != ".disabled") && file != cd + "\\modpack\\bin\\modpack.jar")
                    {
                        if (zip.ContainsEntry(file))
                        {
                            zip.RemoveEntry(file);
                        }
                        zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\modpack", ""));
                    }
                }

                //Add modpack.jar
                try
                {
                    string file      = cd + "\\plugins\\mergedjar\\modpack.jar";
                    string zipFolder = "bin";

                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, zipFolder);
                }
                catch
                { }
                //Add idfixminus.jar
                if (File.Exists(cd + "\\plugins\\idfixer\\idfixminus.jar"))
                {
                    string file      = cd + "\\plugins\\idfixer\\idfixminus.jar";
                    string zipFolder = "mods";

                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, zipFolder);
                }

                //Save zipfile
                bool succeed = false;
                while (!succeed)
                {
                    try
                    {
                        zip.Save();
                        succeed = true;
                    }
                    catch
                    { }
                }
            }

            //Create server zipfile
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zipDirectory + "\\ServerFiles.zip"))
            {
                //Add server folders
                foreach (string folder in Directory.GetDirectories(cd + "\\tests\\ServerBuild", "*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(folder))
                    {
                        zip.RemoveEntry(folder);
                    }
                    zip.AddDirectoryByName(folder.Replace(cd + "\\tests\\ServerBuild", ""));
                }
                //Add server files
                foreach (string file in Directory.GetFiles(cd + "\\tests\\ServerBuild", "*.*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\tests\\ServerBuild", ""));
                }

                //Save zipfile
                bool succeed = false;
                while (!succeed)
                {
                    try
                    {
                        zip.Save();
                        succeed = true;
                    }
                    catch
                    { }
                }
            }
        }
Exemplo n.º 18
0
        public static MemoryStream GeneratePatientBackup([NotNull] CerebelloEntitiesAccessFilterWrapper db,
                                                         [NotNull] Patient patient)
        {
            if (db == null) throw new ArgumentNullException("db");
            if (patient == null) throw new ArgumentNullException("patient");

            var zipMemoryStream = new MemoryStream();
            using (var patientZip = new ZipFile())
            {
                var storageManager = new WindowsAzureBlobStorageManager();

                // add the patient history as pdf
                var pdf = ReportController.ExportPatientsPdf(patient.Id, db, patient.Practice, patient.Doctor);
                patientZip.AddEntry(string.Format("{0} - Histórico.pdf", patient.Person.FullName), pdf);

                // if the person has a picture, add it to the backup
                if (patient.Person.PictureBlobName != null)
                {
                    var picture = storageManager.DownloadFileFromStorage(Constants.PERSON_PROFILE_PICTURE_CONTAINER_NAME, patient.Person.PictureBlobName);
                    patientZip.AddEntry(string.Format("{0} - Perfil.png", patient.Person.FullName), picture);
                }

                // if the person has files, add them to the backup
                var patientFiles = db.PatientFiles.Where(pf => pf.PatientId == patient.Id).ToList();
                if (patientFiles.Any())
                {
                    using (var patientFilesZip = new ZipFile())
                    {
                        var patientFilesZipMemoryStream = new MemoryStream();
                        foreach (var patientFile in patientFiles)
                        {
                            var fileStream = storageManager.DownloadFileFromStorage(
                                patientFile.FileMetadata.ContainerName, patientFile.FileMetadata.BlobName);
                            var fileName = patientFile.FileMetadata.SourceFileName;
                            for (var i = 2;; i++)
                            {
                                if (patientFilesZip.ContainsEntry(fileName))
                                {
                                    fileName = Path.GetFileNameWithoutExtension(fileName) + " " + i + Path.GetExtension(fileName);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            patientFilesZip.AddEntry(fileName, fileStream);
                        }

                        patientFilesZip.Save(patientFilesZipMemoryStream);
                        patientFilesZipMemoryStream.Seek(0, SeekOrigin.Begin);
                        patientZip.AddEntry(string.Format("{0} - Arquivos.zip", patient.Person.FullName), patientFilesZipMemoryStream);
                    }
                }

                patientZip.Save(zipMemoryStream);
            }

            zipMemoryStream.Seek(0, SeekOrigin.Begin);
            return zipMemoryStream;
        }
Exemplo n.º 19
0
 void AddNativeLibrariesFromAssemblies(ZipFile apk, string supportedAbis)
 {
     var abis = supportedAbis.Split (new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
     var res = new DirectoryAssemblyResolver (Console.WriteLine, loadDebugSymbols: false);
     foreach (var assembly in EmbeddedNativeLibraryAssemblies)
         res.Load (assembly.ItemSpec);
     foreach (var assemblyPath in EmbeddedNativeLibraryAssemblies) {
         var assembly = res.GetAssembly (assemblyPath.ItemSpec);
         foreach (var mod in assembly.Modules) {
             var ressozip = mod.Resources.FirstOrDefault (r => r.Name == "__AndroidNativeLibraries__.zip") as EmbeddedResource;
             if (ressozip == null)
                 continue;
             var data = ressozip.GetResourceData ();
             using (var ms = new MemoryStream (data)) {
                 using (var zip = ZipFile.Read (ms)) {
                     foreach (var e in zip.Entries.Where (x => abis.Any (a => x.FileName.Contains (a)))) {
                         if (e.IsDirectory)
                             continue;
                         var key = e.FileName.Replace ("native_library_imports", "lib");
                         if (apk.ContainsEntry (key)) {
                             Log.LogCodedWarning ("4301", "Apk already contains the item {0}; ignoring.", key);
                             continue;
                         }
                         using (var s = new MemoryStream ()) {
                             e.Extract (s);
                             apk.AddEntry (key, s.ToArray ());
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 20
0
    private static int GetFileFormatByZip(Ionic.Zip.ZipFile oZipFile)
    {
        if (oZipFile.ContainsEntry("[Content_Types].xml"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["[Content_Types].xml"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.UTF8Encoding.UTF8.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.ms-word.document.macroEnabled.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.ms-word.template.macroEnabledTemplate.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-excel.sheet.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-excel.template.macroEnabled.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLSX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.template.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.slideshow.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.template.macroEnabled.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPTX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPSX);
                }
            }
        }
        if (oZipFile.ContainsEntry("mimetype"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["mimetype"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.ASCIIEncoding.ASCII.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.text"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_ODT);
                }
                else if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.spreadsheet"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_SPREADSHEET_ODS);
                }
                else if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.presentation"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_ODP);
                }
                else if (-1 != sContent.IndexOf("application/epub+zip"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_EPUB);
                }
            }
        }
        if (oZipFile.ContainsEntry("_rels/.rels"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["_rels/.rels"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.ASCIIEncoding.ASCII.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("http://schemas.microsoft.com/xps/2005/06/fixedrepresentation"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS);
                }
            }
        }

        if (oZipFile.ContainsEntry("_rels/.rels/[0].piece"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS);
        }
        if (oZipFile.ContainsEntry("Editor.bin"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["Editor.bin"];
            int nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN;
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                int nSignatureLength = 4;
                if (oMemoryStream.Length >= nSignatureLength)
                {
                    byte[] aSignature = new byte[nSignatureLength];
                    oMemoryStream.Read(aSignature, 0, nSignatureLength);
                    string sSignature = System.Text.ASCIIEncoding.ASCII.GetString(aSignature);
                    switch (sSignature)
                    {
                    case "DOCY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_DOCY; break;

                    case "XLSY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_XLSY; break;

                    case "PPTY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_PPTY; break;
                    }
                }
            }
            if (FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN != nFormat)
            {
                return(nFormat);
            }
        }
        else if (oZipFile.ContainsEntry("Editor.xml"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_PRESENTATION);
        }
        else if (oZipFile.ContainsEntry("Editor.svg"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_DRAWING);
        }
        else if (oZipFile.ContainsEntry("Editor.html.arch"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_DOCUMENT);
        }
        return(FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN);
    }
Exemplo n.º 21
0
		public virtual void ExportAsWikiFiles(string filename)
		{
			if (string.IsNullOrEmpty(filename))
				throw new ArgumentNullException("filename");

			IEnumerable<PageViewModel> pages = _pageService.AllPages();
			char[] invalidChars = Path.GetInvalidFileNameChars();

			if (!Directory.Exists(ExportFolder))
				Directory.CreateDirectory(ExportFolder);

			string zipFullPath = Path.Combine(ExportFolder, filename);

			if (File.Exists(zipFullPath))
				File.Delete(zipFullPath);

			using (ZipFile zip = new ZipFile(zipFullPath))
			{
				int index = 0;
				List<string> filenames = new List<string>();

				foreach (PageViewModel summary in pages.OrderBy(p => p.Title))
				{
					// Double check for blank titles, as the API can add
					// pages with blanks titles even though the UI doesn't allow it.
					if (string.IsNullOrEmpty(summary.Title))
						summary.Title = "(No title -" + summary.Id + ")";

					string filePath = summary.Title;

					// Ensure the filename is unique as its title based.
					// Simply replace invalid path characters with a '-'
					foreach (char item in invalidChars)
					{
						filePath = filePath.Replace(item, '-');
					}

					if (filenames.Contains(filePath))
						filePath += (++index) + "";
					else
						index = 0;

					filenames.Add(filePath);

					filePath = Path.Combine(ExportFolder, filePath);
					filePath += ".wiki";
					string content = "Tags:" + summary.SpaceDelimitedTags() + "\r\n" + summary.Content;

					Console.WriteLine(filePath);
					File.WriteAllText(filePath, content);

					if (!zip.ContainsEntry(filePath))
						zip.AddFile(filePath, "");
				}

				zip.Save();
			}
		}
Exemplo n.º 22
0
        /// <summary>
        /// Reads one entry from the zip directory structure in the zip file.
        /// </summary>
        /// <param name="zf">
        /// The zipfile for which a directory entry will be read.  From this param, the
        /// method gets the ReadStream and the expected text encoding
        /// (ProvisionalAlternateEncoding) which is used if the entry is not marked
        /// UTF-8.
        /// </param>
        /// <returns>the entry read from the archive.</returns>
        internal static ZipEntry ReadDirEntry(ZipFile zf)
        {
            System.IO.Stream s = zf.ReadStream;
            System.Text.Encoding expectedEncoding = zf.ProvisionalAlternateEncoding;

            int signature = Ionic.Zip.SharedUtilities.ReadSignature(s);
            // return null if this is not a local file header signature
            if (IsNotValidZipDirEntrySig(signature))
            {
                s.Seek(-4, System.IO.SeekOrigin.Current);
                // workitem 10178
                Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(s);

                // Getting "not a ZipDirEntry signature" here is not always wrong or an
                // error.  This can happen when walking through a zipfile.  After the
                // last ZipDirEntry, we expect to read an
                // EndOfCentralDirectorySignature.  When we get this is how we know
                // we've reached the end of the central directory.
                if (signature != ZipConstants.EndOfCentralDirectorySignature &&
                    signature != ZipConstants.Zip64EndOfCentralDirectoryRecordSignature &&
                    signature != ZipConstants.ZipEntrySignature  // workitem 8299
                    )
                {
                    throw new BadReadException(String.Format("  ZipEntry::ReadDirEntry(): Bad signature (0x{0:X8}) at position 0x{1:X8}", signature, s.Position));
                }
                return null;
            }

            int bytesRead = 42 + 4;
            byte[] block = new byte[42];
            int n = s.Read(block, 0, block.Length);
            if (n != block.Length) return null;

            int i = 0;
            ZipEntry zde = new ZipEntry();
            zde.ProvisionalAlternateEncoding = expectedEncoding;
            zde._Source = ZipEntrySource.ZipFile;
            zde._container = new ZipContainer(zf);

            unchecked
            {
                zde._VersionMadeBy = (short)(block[i++] + block[i++] * 256);
                zde._VersionNeeded = (short)(block[i++] + block[i++] * 256);
                zde._BitField = (short)(block[i++] + block[i++] * 256);
                zde._CompressionMethod = (Int16)(block[i++] + block[i++] * 256);
                zde._TimeBlob = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
                zde._LastModified = Ionic.Zip.SharedUtilities.PackedToDateTime(zde._TimeBlob);
                zde._timestamp |= ZipEntryTimestamp.DOS;

                zde._Crc32 = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
                zde._CompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                zde._UncompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
            }

            // preserve
            zde._CompressionMethod_FromZipFile = zde._CompressionMethod;

            zde._filenameLength = (short)(block[i++] + block[i++] * 256);
            zde._extraFieldLength = (short)(block[i++] + block[i++] * 256);
            zde._commentLength = (short)(block[i++] + block[i++] * 256);
            zde._diskNumber = (UInt32)(block[i++] + block[i++] * 256);

            zde._InternalFileAttrs = (short)(block[i++] + block[i++] * 256);
            zde._ExternalFileAttrs = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;

            zde._RelativeOffsetOfLocalHeader = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);

            // workitem 7801
            zde.IsText = ((zde._InternalFileAttrs & 0x01) == 0x01);

            block = new byte[zde._filenameLength];
            n = s.Read(block, 0, block.Length);
            bytesRead += n;
            if ((zde._BitField & 0x0800) == 0x0800)
            {
                // UTF-8 is in use
                zde._FileNameInArchive = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
            }
            else
            {
                zde._FileNameInArchive = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
            }

            // workitem 10330
            // insure unique entry names
            while (zf.ContainsEntry(zde._FileNameInArchive))
            {
                zde._FileNameInArchive = CopyHelper.AppendCopyToFileName(zde._FileNameInArchive);
                zde._metadataChanged= true;
            }

            if (zde.AttributesIndicateDirectory)
                zde.MarkAsDirectory();  // may append a slash to filename if nec.
            // workitem 6898
            else if (zde._FileNameInArchive.EndsWith("/")) zde.MarkAsDirectory();

            zde._CompressedFileDataSize = zde._CompressedSize;
            if ((zde._BitField & 0x01) == 0x01)
            {
                zde._Encryption_FromZipFile = zde._Encryption = EncryptionAlgorithm.PkzipWeak; // this may change after processing the Extra field
                zde._sourceIsEncrypted = true;
            }

            if (zde._extraFieldLength > 0)
            {
                zde._InputUsesZip64 = (zde._CompressedSize == 0xFFFFFFFF ||
                      zde._UncompressedSize == 0xFFFFFFFF ||
                      zde._RelativeOffsetOfLocalHeader == 0xFFFFFFFF);

                // Console.WriteLine("  Input uses Z64?:      {0}", zde._InputUsesZip64);

                bytesRead += zde.ProcessExtraField(s, zde._extraFieldLength);
                zde._CompressedFileDataSize = zde._CompressedSize;
            }

            // we've processed the extra field, so we know the encryption method is set now.
            if (zde._Encryption == EncryptionAlgorithm.PkzipWeak)
            {
                // the "encryption header" of 12 bytes precedes the file data
                zde._CompressedFileDataSize -= 12;
            }
#if AESCRYPTO
            else if (zde.Encryption == EncryptionAlgorithm.WinZipAes128 ||
                        zde.Encryption == EncryptionAlgorithm.WinZipAes256)
            {
                zde._CompressedFileDataSize = zde.CompressedSize -
                    (ZipEntry.GetLengthOfCryptoHeaderBytes(zde.Encryption) + 10);
                zde._LengthOfTrailer = 10;
            }
#endif

            // tally the trailing descriptor
            if ((zde._BitField & 0x0008) == 0x0008)
            {
                // sig, CRC, Comp and Uncomp sizes
                if (zde._InputUsesZip64)
                    zde._LengthOfTrailer += 24;
                else
                    zde._LengthOfTrailer += 16;
            }

            if (zde._commentLength > 0)
            {
                block = new byte[zde._commentLength];
                n = s.Read(block, 0, block.Length);
                bytesRead += n;
                if ((zde._BitField & 0x0800) == 0x0800)
                {
                    // UTF-8 is in use
                    zde._Comment = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
                }
                else
                {
                    zde._Comment = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
                }
            }
            //zde._LengthOfDirEntry = bytesRead;
            return zde;
        }
Exemplo n.º 23
0
 protected SampleRepository(ZipFile archive)
 {
     this.archive = archive;
     if (archive.ContainsEntry ("index.xml"))
         index = ((ICollection<SampleDesc>)IndexSerializer.Deserialize (archive["index.xml"].OpenReader ())).ToDictionary (sd => sd.ID, sd => sd);
 }
Exemplo n.º 24
0
        /// <summary>
        /// Reads one entry from the zip directory structure in the zip file.
        /// </summary>
        /// <param name="zf">
        /// The zipfile for which a directory entry will be read.  From this param, the
        /// method gets the ReadStream and the expected text encoding
        /// (ProvisionalAlternateEncoding) which is used if the entry is not marked
        /// UTF-8.
        /// </param>
        /// <returns>the entry read from the archive.</returns>
        internal static ZipEntry ReadDirEntry(ZipFile zf)
        {
            System.IO.Stream     s = zf.ReadStream;
            System.Text.Encoding expectedEncoding = zf.ProvisionalAlternateEncoding;

            int signature = Ionic.Zip.SharedUtilities.ReadSignature(s);

            // return null if this is not a local file header signature
            if (IsNotValidZipDirEntrySig(signature))
            {
                s.Seek(-4, System.IO.SeekOrigin.Current);
                // workitem 10178
                Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(s);

                // Getting "not a ZipDirEntry signature" here is not always wrong or an
                // error.  This can happen when walking through a zipfile.  After the
                // last ZipDirEntry, we expect to read an
                // EndOfCentralDirectorySignature.  When we get this is how we know
                // we've reached the end of the central directory.
                if (signature != ZipConstants.EndOfCentralDirectorySignature &&
                    signature != ZipConstants.Zip64EndOfCentralDirectoryRecordSignature &&
                    signature != ZipConstants.ZipEntrySignature  // workitem 8299
                    )
                {
                    throw new BadReadException(String.Format("  ZipEntry::ReadDirEntry(): Bad signature (0x{0:X8}) at position 0x{1:X8}", signature, s.Position));
                }
                return(null);
            }

            int bytesRead = 42 + 4;

            byte[] block = new byte[42];
            int    n     = s.Read(block, 0, block.Length);

            if (n != block.Length)
            {
                return(null);
            }

            int      i   = 0;
            ZipEntry zde = new ZipEntry();

            zde.ProvisionalAlternateEncoding = expectedEncoding;
            zde._Source    = ZipEntrySource.ZipFile;
            zde._container = new ZipContainer(zf);

            unchecked
            {
                zde._VersionMadeBy     = (short)(block[i++] + block[i++] * 256);
                zde._VersionNeeded     = (short)(block[i++] + block[i++] * 256);
                zde._BitField          = (short)(block[i++] + block[i++] * 256);
                zde._CompressionMethod = (Int16)(block[i++] + block[i++] * 256);
                zde._TimeBlob          = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
                zde._LastModified      = Ionic.Zip.SharedUtilities.PackedToDateTime(zde._TimeBlob);
                zde._timestamp        |= ZipEntryTimestamp.DOS;

                zde._Crc32            = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
                zde._CompressedSize   = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                zde._UncompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
            }

            // preserve
            zde._CompressionMethod_FromZipFile = zde._CompressionMethod;

            zde._filenameLength   = (short)(block[i++] + block[i++] * 256);
            zde._extraFieldLength = (short)(block[i++] + block[i++] * 256);
            zde._commentLength    = (short)(block[i++] + block[i++] * 256);
            zde._diskNumber       = (UInt32)(block[i++] + block[i++] * 256);

            zde._InternalFileAttrs = (short)(block[i++] + block[i++] * 256);
            zde._ExternalFileAttrs = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;

            zde._RelativeOffsetOfLocalHeader = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);

            // workitem 7801
            zde.IsText = ((zde._InternalFileAttrs & 0x01) == 0x01);

            block      = new byte[zde._filenameLength];
            n          = s.Read(block, 0, block.Length);
            bytesRead += n;
            if ((zde._BitField & 0x0800) == 0x0800)
            {
                // UTF-8 is in use
                zde._FileNameInArchive = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
            }
            else
            {
                zde._FileNameInArchive = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
            }

            // workitem 10330
            // insure unique entry names
            while (zf.ContainsEntry(zde._FileNameInArchive))
            {
                zde._FileNameInArchive = CopyHelper.AppendCopyToFileName(zde._FileNameInArchive);
                zde._metadataChanged   = true;
            }

            if (zde.AttributesIndicateDirectory)
            {
                zde.MarkAsDirectory();  // may append a slash to filename if nec.
            }
            // workitem 6898
            else if (zde._FileNameInArchive.EndsWith("/"))
            {
                zde.MarkAsDirectory();
            }

            zde._CompressedFileDataSize = zde._CompressedSize;
            if ((zde._BitField & 0x01) == 0x01)
            {
                zde._Encryption_FromZipFile = zde._Encryption = EncryptionAlgorithm.PkzipWeak; // this may change after processing the Extra field
                zde._sourceIsEncrypted      = true;
            }

            if (zde._extraFieldLength > 0)
            {
                zde._InputUsesZip64 = (zde._CompressedSize == 0xFFFFFFFF ||
                                       zde._UncompressedSize == 0xFFFFFFFF ||
                                       zde._RelativeOffsetOfLocalHeader == 0xFFFFFFFF);

                // Console.WriteLine("  Input uses Z64?:      {0}", zde._InputUsesZip64);

                bytesRead += zde.ProcessExtraField(s, zde._extraFieldLength);
                zde._CompressedFileDataSize = zde._CompressedSize;
            }

            // we've processed the extra field, so we know the encryption method is set now.
            if (zde._Encryption == EncryptionAlgorithm.PkzipWeak)
            {
                // the "encryption header" of 12 bytes precedes the file data
                zde._CompressedFileDataSize -= 12;
            }
#if AESCRYPTO
            else if (zde.Encryption == EncryptionAlgorithm.WinZipAes128 ||
                     zde.Encryption == EncryptionAlgorithm.WinZipAes256)
            {
                zde._CompressedFileDataSize = zde.CompressedSize -
                                              (ZipEntry.GetLengthOfCryptoHeaderBytes(zde.Encryption) + 10);
                zde._LengthOfTrailer = 10;
            }
#endif

            // tally the trailing descriptor
            if ((zde._BitField & 0x0008) == 0x0008)
            {
                // sig, CRC, Comp and Uncomp sizes
                if (zde._InputUsesZip64)
                {
                    zde._LengthOfTrailer += 24;
                }
                else
                {
                    zde._LengthOfTrailer += 16;
                }
            }

            if (zde._commentLength > 0)
            {
                block      = new byte[zde._commentLength];
                n          = s.Read(block, 0, block.Length);
                bytesRead += n;
                if ((zde._BitField & 0x0800) == 0x0800)
                {
                    // UTF-8 is in use
                    zde._Comment = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
                }
                else
                {
                    zde._Comment = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
                }
            }
            //zde._LengthOfDirEntry = bytesRead;
            return(zde);
        }
        /// <summary>
        /// The set data received.
        /// </summary>
        /// <param name="data">
        /// The data.
        /// </param>
        public void SetReceivedZip(ZipFile zip)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (!zip.ContainsEntry("forms.txt"))
                {
                    string backupFolder = Path.Combine(Constants.ODKPath, "LMD Backups");
                    string nameOfLMD = string.Format("data_{0:yyyy-MM-dd}.lmd", DateTime.Now.Date);

                    if (!Directory.Exists(backupFolder))
                    {
                        Directory.CreateDirectory(backupFolder);
                    }

                    int counter = 2;
                    while (true)
                    {
                        if (File.Exists(Path.Combine(backupFolder, nameOfLMD)))
                        {
                            nameOfLMD = string.Format("data_{0:yyyy-MM-dd} ({1}).lmd", DateTime.Now.Date, counter);
                            counter++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    try
                    {
                        var filePathLMD = Path.Combine(backupFolder, nameOfLMD);
                        var fileStream = File.Create(filePathLMD);
                        fileStream.Close();

                        bool firstZip = true;

                        if (!Directory.Exists(Path.Combine(Constants.ODKPath, "Temp")))
                        {
                            Directory.CreateDirectory(Path.Combine(Constants.ODKPath, "Temp"));
                        }

                        var zipFilePath = Path.Combine(Constants.ODKPath, "Temp", nameOfLMD.Replace(".lmd", ".zip"));
                        zip.Save(zipFilePath);
                        var unzippedFolder = zipFilePath.Replace(".zip", string.Empty);
                        zip.ExtractAll(unzippedFolder);

                        // bool isForm = true;
                        using (StreamWriter writetext = new StreamWriter(filePathLMD))
                        {
                            var unzippedFiles = Directory.GetFiles(unzippedFolder, "*.xml", SearchOption.AllDirectories);
                            foreach (var filePathFromZip in unzippedFiles)
                            {
                                if (!firstZip)
                                {
                                    writetext.Write(Environment.NewLine + Environment.NewLine + "<LMD_delimiter>" + Environment.NewLine + Environment.NewLine);
                                }
                                else
                                {
                                    firstZip = false;
                                }

                                var fileString = File.ReadAllText(filePathFromZip);

                                writetext.Write(fileString);
                            }
                        }

                        string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        File.Copy(filePathLMD, Path.Combine(desktop, nameOfLMD));
                        //this.Status = String.Format("Forms are stored on the desktop as {0}.", nameOfLMD);
                        this.Status = String.Format("File \"{0}\" has been received from {1} and stored on the desktop!", nameOfLMD, _receiverBluetoothService.lastClientName);

                        File.Delete(zipFilePath);

                        string[] files = Directory.GetFiles(unzippedFolder, "*.*", SearchOption.AllDirectories);

                        // Display all the files.
                        foreach (string file in files)
                        {
                            File.Delete(file);
                        }

                        Directory.Delete(unzippedFolder, true);
                    }
                    catch (Exception ex)
                    {
                        this.AddExceptionToLog(ex);
                    }
                }
                else
                {
                    this.Status = "Laptop can only receive instances! Form transfer was rejected.";
                    zip.Dispose();
                    MessageBox.Show(this.Status, string.Empty, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }));
        }
Exemplo n.º 26
0
        private void DownloadAllZipped(int message_id, HttpContext context)
        {
            var mail_box_manager = new MailBoxManager(0);

            var attachments = mail_box_manager.GetMessageAttachments(TenantId, Username, message_id);

            if (attachments.Any())
            {
                using (var zip = new ZipFile())
                {
                    zip.CompressionLevel = CompressionLevel.Level3;
                    zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                    zip.AlternateEncoding = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);

                    foreach (var attachment in attachments)
                    {
                        using (var file = AttachmentManager.GetAttachmentStream(attachment))
                        {
                            var filename = file.FileName;

                            if (zip.ContainsEntry(filename))
                            {
                                var counter = 1;
                                var temp_name = filename;
                                while (zip.ContainsEntry(temp_name))
                                {
                                    temp_name = filename;
                                    var suffix = " (" + counter + ")";
                                    temp_name = 0 < temp_name.IndexOf('.')
                                                   ? temp_name.Insert(temp_name.LastIndexOf('.'), suffix)
                                                   : temp_name + suffix;

                                    counter++;
                                }
                                filename = temp_name;
                            }

                            zip.AddEntry(filename, file.FileStream.GetCorrectBuffer());
                        }
                    }

                    context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(ArchiveName));

                    zip.Save(context.Response.OutputStream);

                }

            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// This method generate the package as per the <c>PackageSize</c> declare.
        /// Currently <c>PackageSize</c> is 2 GB.
        /// </summary>
        /// <param name="inputFolderPath">Input folder Path.</param>
        /// <param name="outputFolderandFile">Output folder Path.</param>

        static void SplitZipFolder(string inputFolderPath, string outputFolderandFile, string threadId)
        {
            #region otherApproach

            #endregion

            int cnt = 1;
            m_packageSize = m_packageSize * 20;
            ArrayList htmlFile = new ArrayList();
            ArrayList ar       = GenerateFileList(inputFolderPath, out htmlFile); // generate file list



            // Output Zip file name.
            string outPath          = Path.Combine(outputFolderandFile, threadId + "-" + cnt + ".zip");
            long   HTMLstreamlenght = 0;

            using (ZipOutputStream oZipStream = CreateNewStream(htmlFile, outPath, out HTMLstreamlenght))
            {
                // Initialize the zip entry object.
                ZipEntry oZipEntry = new ZipEntry();

                // numbers of files in file list.
                var counter = ar.Count;
                try
                {
                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                    {
                        Array.Sort(ar.ToArray());            // Sort the file list array.
                        foreach (string Fil in ar.ToArray()) // for each file, generate a zip entry
                        {
                            if (!Fil.EndsWith(@"/"))         // if a file ends with '/' its a directory
                            {
                                if (!zip.ContainsEntry(Path.GetFileName(Fil.ToString())))
                                {
                                    oZipEntry = zip.AddEntry("Attachments/" + Path.GetFileName(Fil.ToString()), Fil);
                                    counter--;
                                    try
                                    {
                                        if (counter >= 0)
                                        {
                                            long      streamlenght = HTMLstreamlenght;
                                            const int BufferSize   = 4096;
                                            byte[]    obuffer      = new byte[BufferSize];
                                            if (oZipStream.Position + streamlenght < m_packageSize)
                                            {
                                                using (FileStream ostream = File.OpenRead(Fil))
                                                {
                                                    //ostream = File.OpenRead(Fil);
                                                    using (ZipOutputStream tempZStream = new ZipOutputStream(File.Create(Directory.GetCurrentDirectory() + "\\test.zip"), false))
                                                    {
                                                        tempZStream.PutNextEntry(oZipEntry.FileName);
                                                        int tempread;
                                                        while ((tempread = ostream.Read(obuffer, 0, obuffer.Length)) > 0)
                                                        {
                                                            tempZStream.Write(obuffer, 0, tempread);
                                                        }
                                                        streamlenght = tempZStream.Position;
                                                        tempZStream.Dispose();
                                                        tempZStream.Flush();
                                                        tempZStream.Close(); // close the zip stream.
                                                                             // ostream.Dispose();
                                                    }

                                                    File.Delete(Directory.GetCurrentDirectory() + "\\test.zip");
                                                }
                                            }

                                            if (oZipStream.Position + streamlenght > m_packageSize)
                                            {
                                                zip.RemoveEntry(oZipEntry);
                                                zip.Dispose();
                                                oZipStream.Dispose();
                                                oZipStream.Flush();
                                                oZipStream.Close();                                                                    // close the zip stream.
                                                cnt     = cnt + 1;
                                                outPath = Path.Combine(outputFolderandFile, threadId + "-" + cnt.ToString() + ".zip"); // create new output zip file when package size.
                                                using (ZipOutputStream oZipStream2 = CreateNewStream(htmlFile, outPath, out HTMLstreamlenght))
                                                {
                                                    oZipStream2.PutNextEntry(oZipEntry.FileName);
                                                    using (FileStream ostream = File.OpenRead(Fil))
                                                    {
                                                        int read;
                                                        while ((read = ostream.Read(obuffer, 0, obuffer.Length)) > 0)
                                                        {
                                                            oZipStream2.Write(obuffer, 0, read);
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                oZipStream.PutNextEntry(oZipEntry.FileName);
                                                using (FileStream ostream = File.OpenRead(Fil))
                                                {
                                                    int read;
                                                    while ((read = ostream.Read(obuffer, 0, obuffer.Length)) > 0)
                                                    {
                                                        oZipStream.Write(obuffer, 0, read);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Console.WriteLine("No more file existed in directory");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.ToString());
                                        zip.RemoveEntry(oZipEntry.FileName);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("File Existed {0} in Zip {1}", Path.GetFullPath(Fil.ToString()), outPath);
                                }
                            }
                        }
                        zip.Dispose();
                    }
                    oZipStream.Dispose();
                    oZipStream.Flush();
                    oZipStream.Close();// close stream
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    oZipStream.Dispose();
                    oZipStream.Flush();
                    oZipStream.Close();// close stream

                    Console.WriteLine("Remain Files{0}", counter);
                }
            }
        }
 StringLocalizationStorage LoadLanguageData(string mapFilename, ZipFile mapFile)
 {
     var sls = new StringLocalizationStorage();
     if (mapFile.ContainsEntry("strings.resx"))
         using (var s = mapFile["strings.resx"].OpenReader())
             sls.AddLanguage("en", s);
     foreach(var v in mapFile.SelectEntries("strings.*.resx"))
     {
         var lang = v.FileName.Substring("strings.".Length);
         lang = lang.Substring(0, lang.Length - ".resx".Length);
         using (var s = v.OpenReader())
             sls.AddLanguage(lang, s);
     }
     return sls;
 }
        public void MakeModpack()
        {
            String[] fileList = Directory.GetFiles(tmp, "*", SearchOption.AllDirectories);

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(mcFile)) {
                foreach (String file in fileList) {
                    String newFile = file.Substring(tmp.Length);
                    Console.WriteLine(newFile);
                    if (zip.ContainsEntry(newFile))
                        zip.RemoveEntry(newFile);
                    zip.AddFile(file, Path.GetDirectoryName(newFile));
                }
                zip.Save();
                MessageBox.Show("Done...");
            }
               /* using (ZipArchive zip = System.IO.Compression.ZipFile.Open(mcFile, ZipArchiveMode.Update)) {
                foreach (String file in fileList) {
                    var fileInZip = (from f in zip.Entries
                                     where f.Name == Path.GetFileName(file)
                                     select f).FirstOrDefault();
                    if (fileInZip != null)
                        fileInZip.Delete();
                    zip.CreateEntryFromFile(file, file.Remove(0, tmp.Length), CompressionLevel.Optimal);
                }
            }*/

            //ZipFile zip = new ZipFile(Path.Combine(path, ".minecraft" + Path.DirectorySeparatorChar, "bin" + Path.DirectorySeparatorChar, "minecraft.jar"));
            //zip.AddDirectory(tmp);
            //zip.Save(Path.Combine(path, ".minecraft" + Path.DirectorySeparatorChar, "bin" + Path.DirectorySeparatorChar, "minecraft.jar"));
        }
Exemplo n.º 30
0
        private bool IsSingleSkinInRoot(ZipFile zip)
        {
            if (
                ((zip.ContainsEntry("layout.Master")) || (zip.ContainsEntry("layout.master")))
                && (zip.ContainsEntry("theme.skin"))
                )
            {
                // these files exist in the root folder of the zip
                return true;
            }

            return false;
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="ARealmReversed" /> class.
        /// </summary>
        /// <param name="gameDirectory">Directory of the game installation.</param>
        /// <param name="storeFile">File used for storing definitions and history.</param>
        /// <param name="language">Initial language to use.</param>
        /// <param name="libraFile">Location of the Libra Eorzea database file, or <c>null</c> if it should not be used.</param>
        public ARealmReversed(DirectoryInfo gameDirectory, FileInfo storeFile, Language language, FileInfo libraFile)
        {
            _GameDirectory = gameDirectory;
            _Packs = new PackCollection(Path.Combine(gameDirectory.FullName, "game", "sqpack"));
            _GameData = new XivCollection(Packs, libraFile) {
                ActiveLanguage = language
            };

            _GameVersion = File.ReadAllText(Path.Combine(gameDirectory.FullName, "game", "ffxivgame.ver"));
            _StateFile = storeFile;

            using (var zipFile = new ZipFile(StateFile.FullName, ZipEncoding)) {
                if (zipFile.ContainsEntry(VersionFile)) {
                    RelationDefinition fsDef = null, zipDef = null;
                    DateTime fsMod = DateTime.MinValue, zipMod = DateTime.MinValue;
                    if (!TryGetDefinitionVersion(zipFile, GameVersion, out zipDef, out zipMod))
                        zipDef = ReadDefinition(zipFile, DefinitionFile,  out zipMod);
                    if (!TryGetDefinitionFromFileSystem(out fsDef, out fsMod))
                        fsDef = null;

                    if (fsDef != null && fsMod > zipMod) {
                        fsDef.Version = GameVersion;
                        _GameData.Definition = fsDef;
                        StoreDefinition(zipFile, fsDef, DefinitionFile);
                        zipFile.Save();
                    } else
                        _GameData.Definition = zipDef;
                } else
                    _GameData.Definition = Setup(zipFile);
            }

            _GameData.Definition.Compile();
        }
Exemplo n.º 32
0
        protected override void LoadContent()
        {
            const string terrainPath = "Content/terrain.png";

            if (File.Exists(terrainPath))
                _terrain = Texture2D.FromStream(GraphicsDevice, File.Open(terrainPath, FileMode.Open));
            else
            {
                if (File.Exists(Path.Combine(MinecraftUtilities.DotMinecraft, "bin", "minecraft.jar")))
                {
                    using (var file = new ZipFile(Path.Combine(MinecraftUtilities.DotMinecraft, "bin", "minecraft.jar")))
                    {
                        if (file.ContainsEntry("terrain.png"))
                        {
                            var ms = new MemoryStream();
                            file["terrain.png"].Extract(ms);
                            ms.Seek(0, SeekOrigin.Begin);
                            _terrain = Texture2D.FromStream(GraphicsDevice, ms);
                        }
                        else
                            throw new FileNotFoundException("Missing terrain.png!");
                    }
                }
                else
                    throw new FileNotFoundException("Missing terrain.png!");
            }

            InitializeEffect();
        }
        /// <summary>
        ///     Perform first-time setup on the archive.
        /// </summary>
        /// <param name="zip"><see cref="ZipFile" /> used for storage.</param>
        /// <returns>Returns the initial <see cref="RelationDefinition" /> object.</returns>
        private RelationDefinition Setup(ZipFile zip)
        {
            RelationDefinition fsDef = null, zipDef = null;
            DateTime fsMod = DateTime.MinValue, zipMod = DateTime.MinValue;

            if (!TryGetDefinitionFromFileSystem(out fsDef, out fsMod))
                fsDef = null;

            if (zip.ContainsEntry(DefinitionFile))
                zipDef = ReadDefinition(zip, DefinitionFile, out zipMod);

            if (fsDef == null && zipDef == null)
                throw new InvalidOperationException();

            RelationDefinition def;
            if (fsMod > zipMod)
                def = fsDef;
            else
                def = zipDef;

            if (def.Version != GameVersion)
                System.Diagnostics.Trace.WriteLine(string.Format("Definition and game version mismatch ({0} != {1})", def.Version, GameVersion));

            def.Version = GameVersion;
            StoreDefinition(zip, def, string.Format("{0}/{1}", def.Version, DefinitionFile));
            StoreDefinition(zip, def, DefinitionFile);
            StorePacks(zip);
            UpdateVersion(zip);

            zip.Save();

            return def;
        }
Exemplo n.º 34
0
        public void CompressFiles_zip(string destinationDirectory, string archiveName, string pwd, params string[] files)
        {
            try
            {
                if (archiveName == null || archiveName == string.Empty)
                    archiveName = DateTime.Now.ToString("dd_MM_yyyy");
                else
                    if (archiveName[0] == '#')
                        archiveName = System.String.Format("{0}_{1:dd_MM_yyyy}", archiveName.Substring(1), System.DateTime.Now);

                if (pwd == null || pwd == string.Empty)
                    pwd = Convert.ToString(int.Parse(DateTime.Now.ToString("ddMMyyyy")), 16).ToUpper();
                //DateTime.Now.ToString("C_dd_MM_yyyy");
                string pathZip = destinationDirectory + "\\" + archiveName + ".storage";

                using (ZipFile zip = new ZipFile(pathZip))
                {
                    //zip.AddFile("ReadMe.txt"); // unencrypted
                    //zip.
                    zip.Password = pwd;
                    zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                    string singleName = string.Empty;
                    //ZipEntry itemZ = new ZipEntry();
                    foreach (string item in files)
                    {
                        singleName = item;

                        if (zip.ContainsEntry(singleName))
                            zip.UpdateFile(singleName).Password = pwd;
                        else
                        {
                            //itemZ.Encryption = EncryptionAlgorithm.WinZipAes256;
                            //itemZ.Password = pwd;
                            //itemZ.FileName = item;

                            zip.AddFile(singleName).Password = pwd;

                            //zip.Entries.Add(itemZ);

                            //ZipEntry.itemZ = new ZipEntry();
                        }
                    }
                    //zip.AddFile().pa(files, destinationDirectory);
                    //zip.AddFile("2008_Annual_Report.pdf");
                    try
                    {
                        zip.Comment = string.Format("{0}", int.Parse(zip.Comment) + 1);
                    }
                    catch (Exception ex)
                    {
                        pdLogger.pdLogger.Logme(ex, System.Reflection.MethodInfo.GetCurrentMethod().Name);
                        zip.Comment = zip.Count.ToString();
                    }

                    zip.Save(pathZip);

                }

            }
            catch (Exception ex)
            {
                pdLogger.pdLogger.Logme(ex, System.Reflection.MethodInfo.GetCurrentMethod().Name);
            }
        }
        private bool TryGetDefinitionVersion(ZipFile zip, string version, out RelationDefinition definition, out DateTime lastMod)
        {
            var storedVersionEntry = zip[VersionFile];
            string storedVersion;
            using (var s = storedVersionEntry.OpenReader()) {
                using (var r = new StreamReader(s))
                    storedVersion = r.ReadToEnd();
            }

            if (storedVersion != version) {
                var existingDefPath = string.Format("{0}/{1}", version, DefinitionFile);
                if (zip.ContainsEntry(existingDefPath)) {
                    ZipCopy(zip, existingDefPath, DefinitionFile);
                    UpdateVersion(zip);
                    zip.Save();

                    definition = ReadDefinition(zip, DefinitionFile, out lastMod);
                    return true;
                }

                definition = null;
                lastMod = DateTime.MinValue;
                return false;
            }

            definition = ReadDefinition(zip, DefinitionFile, out lastMod);
            return true;
        }