public void Synchronize(IConfiguration configuration, ZipWriter zip, string fileName, string configKey)
        {
            var databaseName = configuration.GetString(configKey + "database");
            var itemPath = configuration.GetString(configKey + "path");
            var fieldsToWrite = configuration.GetString(configKey + "fields").Split(Constants.Comma, StringSplitOptions.RemoveEmptyEntries).Select(f => f.Trim().ToLowerInvariant()).ToList();

            var database = Factory.GetDatabase(databaseName);

            using (new SecurityDisabler())
            {
                var item = database.GetItem(itemPath);
                if (item == null)
                {
                    return;
                }

                var writer = new StringWriter();
                var output = new XmlTextWriter(writer)
                {
                    Formatting = Formatting.Indented
                };

                WriteItem(output, item, fieldsToWrite, true);

                zip.AddEntry(fileName, Encoding.UTF8.GetBytes(writer.ToString()));
            }
        }
        public void Synchronize(IConfiguration configuration, ZipWriter zip, string fileName, string configKey)
        {
            var databaseName = configuration.GetString(configKey + "database");
            var schemaNamespace = configuration.GetString(configKey + "namespace");

            Synchronize(zip, fileName, databaseName, schemaNamespace);
        }
        public ActionResult Execute(IAppService app)
        {
            TempFolder.EnsureFolder();

            var fileName = FileUtil.MapPath(TempFolder.GetFilename("Pathfinder.Resources.zip"));

            using (var zip = new ZipWriter(fileName))
            {
                foreach (var pair in app.Configuration.GetSubKeys("sync-website:files"))
                {
                    var configKey = "sync-website:files:" + pair.Key + ":";
                    var syncFileName = app.Configuration.GetString(configKey + "file");

                    foreach (var synchronizer in Synchronizers)
                    {
                        if (synchronizer.CanSynchronize(app.Configuration, syncFileName))
                        {
                            synchronizer.Synchronize(app.Configuration, zip, syncFileName, configKey);
                        }
                    }
                }
            }

            return new FilePathResult(fileName, "application/zip");
        }
        public ActionResult Execute(IAppService app)
        {
            TempFolder.EnsureFolder();

            var tempDirectory = Path.Combine(FileUtil.MapPath(TempFolder.Folder), "Pathfinder.Exports");
            if (Directory.Exists(tempDirectory))
            {
                FileUtil.DeleteDirectory(tempDirectory, true);
            }

            Directory.CreateDirectory(tempDirectory);

            var exportFileName = Path.Combine(FileUtil.MapPath(tempDirectory), "Pathfinder.Exports.zip");
            using (var zip = new ZipWriter(exportFileName))
            {
                foreach (var index in app.Configuration.GetSubKeys("write-website-exports"))
                {
                    var entryName = app.Configuration.GetString("write-website-exports:" + index.Key + ":filename");
                    var fileKey = "write-website-exports:" + index.Key + ":";

                    var fileName = Path.Combine(tempDirectory, PathHelper.NormalizeFilePath(entryName).TrimStart('\\'));

                    Directory.CreateDirectory(Path.GetDirectoryName(fileName) ?? string.Empty);

                    WriteFile(app.Configuration, tempDirectory, fileName, fileKey);

                    zip.AddEntry(entryName, fileName);
                }
            }

            return new FilePathResult(exportFileName, "application/zip");
        }
Beispiel #5
0
        /// <summary>
        /// 按文件名创建压缩文件
        /// </summary>
        /// <param name="mode">系统打开文件的方式</param>
        /// <param name="method">压缩方式</param>
        /// <param name="name">压缩文件名</param>
        public ZipFile(string name, byte method, FileMode mode)
        {
            this.zipName = name;

            this.baseStream = new FileStream(this.zipName, mode);
            this.thisWriter = new ZipWriter(baseStream);
            this.thisWriter.Method = method;

            this.zipEntries = new List<ZipEntry>();            
        }
Beispiel #6
0
 protected override void SaveTo(Stream stream, WriterOptions options,
                                IEnumerable <ZipArchiveEntry> oldEntries,
                                IEnumerable <ZipArchiveEntry> newEntries)
 {
     using (var writer = new ZipWriter(stream, new ZipWriterOptions(options)))
     {
         foreach (var entry in oldEntries.Concat(newEntries)
                  .Where(x => !x.IsDirectory))
         {
             using (var entryStream = entry.OpenEntryStream())
             {
                 writer.Write(entry.Key, entryStream, entry.LastModifiedTime);
             }
         }
     }
 }
Beispiel #7
0
        /// <summary>
        /// Compress (ZIP) an unencrypted FAES File.
        /// </summary>
        /// <param name="unencryptedFile">Unencrypted FAES File</param>
        /// <returns>Path of the unencrypted, ZIP compressed file</returns>
        public string CompressFAESFile(FAES_File unencryptedFile)
        {
            FileAES_IntUtilities.CreateEncryptionFilePath(unencryptedFile, "ZIP", out string tempRawPath, out _, out string tempOutputPath);

            ZipWriterOptions wo = new ZipWriterOptions(CompressionType.Deflate)
            {
                DeflateCompressionLevel = _compressLevel
            };

            using (Stream stream = File.OpenWrite(tempOutputPath))
                using (var writer = new ZipWriter(stream, wo))
                {
                    writer.WriteAll(tempRawPath, "*", SearchOption.AllDirectories);
                }
            return(tempOutputPath);
        }
Beispiel #8
0
 protected override void SaveTo(Stream stream, CompressionInfo compressionInfo,
                                IEnumerable <ZipArchiveEntry> oldEntries,
                                IEnumerable <ZipArchiveEntry> newEntries)
 {
     using (var writer = new ZipWriter(stream, compressionInfo, string.Empty))
     {
         foreach (var entry in oldEntries.Concat(newEntries)
                  .Where(x => !x.IsDirectory))
         {
             using (var entryStream = entry.OpenEntryStream())
             {
                 writer.Write(entry.Key, entryStream, entry.LastModifiedTime, string.Empty);
             }
         }
     }
 }
Beispiel #9
0
        public static string CreateZip(string outDir, string name, string version, long size)
        {
            var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));

            Directory.CreateDirectory(tempDir);
            try
            {
                var outfile = Path.Combine(outDir, $"{name}.{version}.zip");

                using (var fs = File.OpenWrite(outfile))
                    using (var zip = new ZipWriter(fs, new ZipWriterOptions(CompressionType.Deflate)))
                    {
                        var rnd = new Random();

                        void Write(int fileSize)
                        {
                            var contents = new byte[fileSize];

                            while (size > 0)
                            {
                                rnd.NextBytes(contents);
                                using (var s = zip.WriteToStream(Guid.NewGuid().ToString("N"), new ZipWriterEntryOptions()))
                                    s.Write(contents, 0, contents.Length);
                                size -= fileSize;
                            }
                        }

                        Write(10_000_000);
                        Write(1_000_000);
                        Write(100_000);
                        Write(10_000);
                        Write(1_000);
                        Write(100);
                        Write(10);
                        Write(1);
                    }

                return(outfile);
            }
            finally
            {
                Directory.Delete(tempDir, true);
            }
        }
Beispiel #10
0
        public void Zip_LZMA_Encrypt_Write()
        {
            ResetScratch();
            using (Stream stream = File.OpenWrite(Path.Combine(SCRATCH2_FILES_PATH, "Zip.lzma.noEmptyDirs.zip"))) {
                using (ZipWriter writer = ZipWriter.Open(stream, new CompressionInfo()
                {
                    Type = CompressionType.LZMA
                }, null, "test")) {
                    writer.WriteAll(ORIGINAL_FILES_PATH, "*", SearchOption.AllDirectories);
                }
                Assert.False(stream.CanWrite);
            }

            using (Stream stream = File.OpenRead(Path.Combine(SCRATCH2_FILES_PATH, "Zip.lzma.noEmptyDirs.zip"))) {
                using (var reader = ZipReader.Open(stream, "test", Options.None)) {
                    Assert.Equal("LZMA with pkware encryption.", Assert.Throws <NotSupportedException>(() => reader.WriteAllToDirectory(SCRATCH_FILES_PATH, ExtractOptions.ExtractFullPath)).Message);
                }
                Assert.False(stream.CanRead);
            }
        }
Beispiel #11
0
        public void Zip_WithPassword_Unzip_Without()
        {
            ResetScratch();
            using (Stream stream = File.OpenWrite(Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.noEmptyDirs.zip"))) {
                using (ZipWriter writer = ZipWriter.Open(stream, new CompressionInfo()
                {
                    Type = CompressionType.Deflate
                }, null, "test")) {
                    writer.WriteAll(ORIGINAL_FILES_PATH, "*", SearchOption.AllDirectories);
                }
                Assert.False(stream.CanWrite);
            }

            using (Stream stream = File.OpenRead(Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.noEmptyDirs.zip"))) {
                using (var reader = ZipReader.Open(stream, null, Options.None)) {
                    Assert.Equal("No password supplied for encrypted zip.", Assert.Throws <CryptographicException>(() => reader.WriteAllToDirectory(SCRATCH_FILES_PATH, ExtractOptions.ExtractFullPath)).Message);
                }
                Assert.False(stream.CanRead);
            }
        }
Beispiel #12
0
        public void Zip_WithoutPassword_Unzip_With()
        {
            ResetScratch();
            using (Stream stream = File.OpenWrite(Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.noEmptyDirs.zip"))) {
                using (ZipWriter writer = ZipWriter.Open(stream, new CompressionInfo()
                {
                    Type = CompressionType.Deflate
                }, null)) {
                    writer.WriteAll(ORIGINAL_FILES_PATH, "*", SearchOption.AllDirectories);
                }
                Assert.False(stream.CanWrite);
            }

            using (Stream stream = File.OpenRead(Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.noEmptyDirs.zip"))) {
                using (var reader = ZipReader.Open(stream, "test", Options.None)) {
                    reader.WriteAllToDirectory(SCRATCH_FILES_PATH, ExtractOptions.ExtractFullPath);
                }
                Assert.False(stream.CanRead);
            }
            VerifyFiles();
        }
 /// <summary>
 /// Finalizes the specified identifier.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="exportPath">The export path.</param>
 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
 public bool Finalize(long id, string exportPath)
 {
     if (queue.TryRemove(id, out var value))
     {
         // Need to do this manually as SharpCompress doesn't raise events
         using var stream = new System.IO.FileInfo(exportPath).Open(FileMode.Create, FileAccess.Write);
         using var writer = new ZipWriter(stream, new ZipWriterOptions(CompressionType.Deflate));
         foreach (var item in value.Entries.Where(p => !p.IsDirectory))
         {
             using var entryStream = item.OpenEntryStream();
             writer.Write(item.Key, entryStream, item.LastModifiedTime);
             if (ProcessedFile != null)
             {
                 ProcessedFile?.Invoke(this, EventArgs.Empty);
             }
         }
         value.Dispose();
         return(true);
     }
     return(false);
 }
Beispiel #14
0
        protected void WriteWithPassword(CompressionType compressionType, string password, string archive)
        {
            ResetScratch();
            using (Stream stream = File.OpenWrite(Path.Combine(SCRATCH2_FILES_PATH, archive))) {
                using (ZipWriter writer = ZipWriter.Open(stream, new CompressionInfo()
                {
                    Type = compressionType
                }, null, password)) {
                    writer.WriteAll(ORIGINAL_FILES_PATH, "*", SearchOption.AllDirectories);
                }
                Assert.False(stream.CanWrite);
            }

            using (Stream stream = File.OpenRead(Path.Combine(SCRATCH2_FILES_PATH, archive))) {
                using (var reader = ZipReader.Open(stream, "test", Options.None)) {
                    reader.WriteAllToDirectory(SCRATCH_FILES_PATH, ExtractOptions.ExtractFullPath);
                }
                Assert.False(stream.CanRead);
            }
            VerifyFiles();
        }
Beispiel #15
0
        public static void Add(string zipFileName, string[] entryPatterns)
        {
            string currentDirectory = Directory.GetCurrentDirectory();

            Console.WriteLine("Creating {0}", zipFileName);

            ZipWriter writer = new ZipWriter(zipFileName);

            // buffer to hold temp bytes
            byte[] buffer = new byte[4096];
            int    byteCount;

            // add files to archive
            foreach (string pattern in entryPatterns)
            {
                foreach (string path in Directory.GetFiles(currentDirectory, pattern))
                {
                    string fileName = Path.GetFileName(path);
                    Console.Write("Adding {0}", fileName);

                    ZipEntry entry = new ZipEntry(fileName);
                    entry.ModifiedTime = File.GetLastWriteTime(fileName);
                    entry.Comment      = "local file comment";

                    writer.AddEntry(entry);

                    FileStream reader = File.OpenRead(entry.Name);
                    while ((byteCount = reader.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        Console.Write(".");
                        writer.Write(buffer, 0, byteCount);
                    }
                    reader.Close();
                    Console.WriteLine();
                }
            }

            writer.Close();
        }
Beispiel #16
0
        public void Zip_With_Empty()
        {
            ResetScratch();
            using (Stream objStream = File.OpenWrite(Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.zip"))) {
                using (ZipWriter objWriter = ZipWriter.Open(objStream, new CompressionInfo()
                {
                    Type = CompressionType.Deflate
                }, null)) {
                    foreach (string strItem in Directory.EnumerateFileSystemEntries(ORIGINAL_FILES_WITH_EMPTY_PATH, "*.*", SearchOption.AllDirectories))
                    {
                        if (Directory.Exists(strItem))
                        {
                            objWriter.WriteDirectoryEntry(strItem.Substring(ORIGINAL_FILES_WITH_EMPTY_PATH.Length), DateTime.UtcNow, null);
                        }
                        else if (File.Exists(strItem))
                        {
                            using (FileStream objReadStream = File.OpenRead(strItem)) {
                                using (Stream objWriteStream = objWriter.WriteToStream(strItem.Substring(ORIGINAL_FILES_WITH_EMPTY_PATH.Length), DateTime.UtcNow, null)) {
                                    objReadStream.TransferTo(objWriteStream);
                                }
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException($@"Unable to validate '{strItem}' path");
                        }
                    }
                }
                Assert.False(objStream.CanWrite);
            }

            using (Stream stream = File.OpenRead(Path.Combine(SCRATCH2_FILES_PATH, "Zip.deflate.zip"))) {
                using (var reader = ZipReader.Open(stream, null, Options.None)) {
                    reader.WriteAllToDirectory(SCRATCH_FILES_PATH, ExtractOptions.ExtractFullPath);
                }
                Assert.False(stream.CanRead);
            }
            VerifyDirectoryTree(ORIGINAL_FILES_WITH_EMPTY_PATH);
        }
Beispiel #17
0
        public override void Emit(IEmitContext context, IProject project)
        {
            var packageFileName = Configuration.GetString(Constants.Configuration.Output.Update.FileName, "package");

            if (!packageFileName.EndsWith(".update"))
            {
                packageFileName += ".update";
            }

            var outputDirectory = PathHelper.Combine(project.ProjectDirectory, Configuration.GetString(Constants.Configuration.Output.Directory));
            var fileName        = Path.Combine(outputDirectory, packageFileName);

            FileSystem.CreateDirectoryFromFileName(fileName);

            using (Zip = new ZipWriter(fileName))
            {
                base.Emit(context, project);

                EmitVersion();
                EmitMetaData();
            }

            context.OutputFiles.Add(Factory.OutputFile(fileName));
        }
Beispiel #18
0
        public static void ReadFolder(WebsiteInfo websiteInfo, DirectoryInfo cDir, ZipWriter writer)
        {
            var mainDir = websiteInfo.WebsiteFolder;
            var dirs    = cDir.GetDirectories();

            foreach (var dir in dirs)
            {
                if (websiteInfo.BackupExclude.FolderName.Contains(dir.Name))
                {
                    continue;
                }
                ReadFolder(websiteInfo, dir, writer);
            }
            var files = cDir.GetFiles();

            foreach (var file in files)
            {
                bool Ignore = false;
                foreach (var item in websiteInfo.BackupExclude.FileName)
                {
                    var re = "^" + item.Replace(".", "\\.").Replace("*", ".*") + "$";
                    if (Regex.IsMatch(file.Name, re, RegexOptions.IgnoreCase))
                    {
                        Ignore = true;
                    }
                }
                if (Ignore)
                {
                    continue;
                }

                var filepath = file.FullName.Substring(mainDir.Length).TrimStart(@"\/".ToArray());

                writer.Write(filepath, File.Open(file.FullName, FileMode.Open), null);
            }
        }
Beispiel #19
0
 protected override void Render(Image image, Drawable drawable)
 {
     var writer = new ZipWriter(image);
       writer.CreateFxz();
 }
        public void Synchronize(IConfiguration configuration, ZipWriter zip, string fileName, string configKey)
        {
            var databaseName = configuration.Get(configKey + "database");

            Synchronize(zip, fileName, databaseName);
        }
        // TODO: throw an exception if "target" attribute not set
        public override void WriteString(string text)
        {
            Node elt = (Node)elements.Peek();

            if (!elt.Ns.Equals(ZIP_POST_PROCESS_NAMESPACE))
            {
                if (delegateWriter != null)
                {
                    delegateWriter.WriteString(text);
                }
            }
            else
            {
                // Pick up the target attribute
                if (attributes.Count > 0)
                {
                    Node attr = (Node)attributes.Peek();
                    if (attr.Ns.Equals(ZIP_POST_PROCESS_NAMESPACE))
                    {
                        switch (elt.Name)
                        {
                        case ARCHIVE_ELEMENT:
                            // Prevent nested archive creation
                            if (processingState == ProcessingState.None && attr.Name.Equals("target"))
                            {
                                Debug.WriteLine("creating archive : " + text);

                                // 输出包的路径放在式样单中间文档元素<archive Target="包路径名">中了,
                                // 从中提取即可,当然也可以直接传递过来
                                zipOutputStream = ZipFactory.CreateArchive(text);
                                processingState = ProcessingState.EntryWaiting;
                                binaries        = new Hashtable();
                            }
                            break;

                        case PART_ELEMENT:
                            // Prevent nested entry creation
                            if (processingState == ProcessingState.EntryWaiting && attr.Name.Equals("target"))
                            {
                                Debug.WriteLine("creating new part : " + text);

                                //此处的text是entry的target属性的值,也就是文件的路径
                                zipOutputStream.AddEntry(text);
                                delegateWriter  = XmlWriter.Create(zipOutputStream, delegateSettings);
                                processingState = ProcessingState.EntryStarted;
                                delegateWriter.WriteStartDocument();
                            }
                            break;

                        case COPY_ELEMENT:
                            if (processingState != ProcessingState.None)
                            {
                                if (attr.Name.Equals("source"))
                                {
                                    // binarySource是存放base64数据的标识符值
                                    // <uof:其他对象 uof:locID="u0036"
                                    //      uof:attrList="标识符 内嵌 公共类型 私有类型"
                                    //      uof:标识符="OBJ00002" uof:内嵌="false" uof:公共类型="png">
                                    // 即OBJ00002,该标识符唯一确定一个其他对象,进而得到其中的base64数据
                                    binarySource += text;
                                    Debug.WriteLine("copy source=" + binarySource);
                                }
                                if (attr.Name.Equals("target"))
                                {
                                    // binaryTarget存放二进制图片在OOX包中的位置
                                    binaryTarget += text;
                                    Debug.WriteLine("copy target=" + binaryTarget);
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
Beispiel #22
0
 public MediaExporter(string file)
 {
     File      = file;
     ZipWriter = new ZipWriter(file);
 }
        private void Done()
        {
            string savePath = GetSavePath();

            if (string.IsNullOrWhiteSpace(savePath))
            {
                return;
            }

            //Change acbFile saveFormat if needed (undoable action)
            if (acbFile.SaveFormat != SaveFormat.MusicPackage)
            {
                UndoManager.Instance.AddUndo(new UndoableProperty <ACB_File>(nameof(acbFile.SaveFormat), acbFile, acbFile.SaveFormat, SaveFormat.MusicPackage, "Save Format"));
                acbFile.SaveFormat = SaveFormat.MusicPackage;
            }

            if ((int)acbFile.MusicPackageType != (MusicPackageType))
            {
                acbFile.MusicPackageType = (MusicPackageType)MusicPackageType;
            }

            //Create MusicPackage
            byte[] musicPackageBytes = acbFile.SaveMusicPackageToBytes();
            string musicPackagePath  = $"CAR_BGM{ACB_File.MUSIC_PACKAGE_EXTENSION}";

            //Create InstallerXml
            InstallerXml installerXml = new InstallerXml();

            installerXml.Name               = ModName;
            installerXml.Author             = ModAuthor;
            installerXml.VersionString      = ModVersion;
            installerXml.InstallOptionSteps = new List <InstallStep>();
            installerXml.InstallFiles       = new List <FilePath>();

            if (!string.IsNullOrWhiteSpace(ModDescription))
            {
                InstallStep installStep = new InstallStep();
                installStep.Name     = "Info";
                installStep.Message  = ModDescription;
                installStep.StepType = InstallStep.StepTypes.Message;
                installerXml.InstallOptionSteps.Add(installStep);
            }

            FilePath file = new FilePath();

            file.SourcePath = musicPackagePath;
            installerXml.InstallFiles.Add(file);


            YAXSerializer serializer = new YAXSerializer(typeof(InstallerXml));
            string        strXml     = serializer.Serialize(installerXml);

            byte[] xmlBytes = Encoding.UTF8.GetBytes(strXml);

            //Create installinfo zip
            using (var stream = File.Create(savePath))
            {
                using (var zip = new ZipArchive(stream, ZipArchiveMode.Create))
                {
                    ZipWriter zipWriter = new ZipWriter(zip);
                    zipWriter.AddFile("InstallerXml.xml", xmlBytes, CompressionLevel.Optimal, true);
                    zipWriter.AddFile("data/" + musicPackagePath, musicPackageBytes, CompressionLevel.Optimal, true);
                }
            }

            Success         = true;
            InstallInfoPath = savePath;
            Close();
        }
 public MediaExporter(string file)
 {
     File = file;
     ZipWriter = new ZipWriter(file);
 }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            //clear session
            Session.Clear();

            btnDownload.Visible = false;

            //get selected folder
            var itemId = new ID(ddMediaFolders.SelectedValue);

            var db = Database.GetDatabase(ddDataBase.SelectedValue.ToLower());

            var selectedFolder = db.Items.GetItem(itemId);


            //set folder to export file
            var exportfolderName = Settings.DataFolder + "/MediaEssentials/ExportMedia/" + selectedFolder.Name;

            _exportFileNameWithExtension = selectedFolder.Name + ".zip";

            FileUtil.CreateFolder(FileUtil.MapPath(exportfolderName));


            //map file path
            _filePath = FileUtil.MapPath(FileUtil.MakePath(exportfolderName, _exportFileNameWithExtension, '/'));

            var mediaLibraryItem = db.GetItem(MediaLibraryUtils.MediaLibraryId);

            var allMediaItems = _mediaLibrary.GetMediaItems(db, selectedFolder, mediaLibraryItem,
                                                            chkIncludeSubFolders.Checked, chkIncludeSystemFolder.Checked);


            //get total of images exported excluding the pre-defined templates below
            var excludedTemplates = new List <string>
            {
                TemplateIDs.MediaFolder.ToString(),
                TemplateIDs.MainSection.ToString(),
                TemplateIDs.Node.ToString()
            };

            var items = allMediaItems.ToArray();

            var totalImagesExported = items
                                      .Select(i => excludedTemplates.FirstOrDefault(x => x.Contains(i.Template.ID.ToString())))
                                      .Count(match => match == null);


            var output = new StringBuilder();

            if (totalImagesExported == 0)
            {
                output.Clear();
                output.AppendLine("There is no media to export within the options set.");

                //output of last execution
                lbOutput.Text = output.ToString().Replace(Environment.NewLine, "<br />");

                return;
            }



            //fill in output
            output.Clear();

            output.AppendLine("Total of Images Exported: " + totalImagesExported);

            output.AppendLine("File Location on Server: " + exportfolderName);

            output.AppendLine();
            output.AppendLine("---- Media Items Exported ----");
            output.AppendLine();

            var templates = items.GroupBy(x => x.TemplateID);


            foreach (IGrouping <Sitecore.Data.ID, Item> item in templates)
            {
                if (item.Key == TemplateIDs.MediaFolder ||
                    item.Key == TemplateIDs.MainSection ||
                    item.Key == TemplateIDs.Node)
                {
                    continue;
                }

                foreach (var i in item)
                {
                    output.AppendLine("Item ID: " + i.ID);
                    output.AppendLine("Item Name: " + i.Name);
                    output.AppendLine("Item Path: " + i.Paths.Path);
                    output.AppendLine();
                }
            }


            ZipWriter = new ZipWriter(_filePath);

            foreach (var i in items)
            {
                if (!chkIncludeSystemFolder.Checked && i.Paths.Path.ToLower()
                    .Contains(mediaLibraryItem.Paths.Path.ToLower() + "/system"))
                {
                    continue;
                }

                ProcessMediaItems(i);
            }

            ZipWriter.Dispose();


            Session["filePath"] = _filePath;
            Session["exportFileNameWithExtension"] = _exportFileNameWithExtension;

            btnDownload.Visible = true;

            //output of last execution
            lbOutput.Text = output.ToString().Replace(Environment.NewLine, "<br />");
        }
Beispiel #26
0
        /// <summary>
        /// Delegates <c>WriteEndElement</c> calls when the element's prefix does not
        /// match a zip command.
        /// Otherwise, close the archive or flush the delegate writer.
        /// </summary>
        public override void WriteEndElement()
        {
            Node elt = (Node)elements.Pop();

            if (!elt.Ns.Equals(ZIP_POST_PROCESS_NAMESPACE) && !elt.Ns.Equals(PIC_POST_PROCESS_NAMESPACE) && !elt.Ns.Equals(OLE_POST_PROCESS_NAMESPACE))
            {
                logger.Debug("delegate - </" + elt.Name + ">");
                if (delegateWriter != null)
                {
                    delegateWriter.WriteEndElement();
                }
            }
            else
            {
                switch (elt.Name)
                {
                case ARCHIVE_ELEMENT:    //archive
                    if (zipOutputStream != null)
                    {
                        logger.Info("[closing archive]");
                        logger.Info("Copying binary files!");
                        CopyBinaryData();
                        zipOutputStream.Close();
                        zipOutputStream = null;
                    }
                    if (processingState == ProcessingState.EntryWaiting)
                    {
                        processingState = ProcessingState.None;
                    }
                    break;

                case PART_ELEMENT:    //entry
                    if (delegateWriter != null)
                    {
                        logger.Info("[end part]");
                        delegateWriter.WriteEndDocument();
                        delegateWriter.Flush();
                        delegateWriter.Close();
                        delegateWriter = null;
                    }
                    if (processingState == ProcessingState.EntryStarted)
                    {
                        processingState = ProcessingState.EntryWaiting;
                    }
                    break;

                case OLE_DRAW:
                case OLE_DRAWRELS:
                case OLE_EMBEDDING:  //ole
                case PIC_ELEMENT:    //picture
                    if (binarySource != null)
                    {
                        logger.Info("add picture: target=" + binarySource);
                        if (!binaries.Contains(binarySource))
                        {
                            binaries.Add(binarySource);
                        }
                        binarySource = "";
                    }
                    break;
                }
            }
        }
Beispiel #27
0
        public void securityfun(string file_parentid, string file_comorsec)
        {
            StringBuilder sb    = new StringBuilder();
            SqlConnection oConn = new SqlConnection(pathUrl("DSN"));
            SqlCommand    oCmd  = new SqlCommand();

            oCmd.Connection = oConn;
            sb.Append(@"SELECT * FROM sfts_file WHERE file_parentid = @file_parentid AND file_comorsec= @file_comorsec ");
            oCmd.CommandText = sb.ToString();
            oCmd.Parameters.AddWithValue("@file_parentid", file_parentid);
            oCmd.Parameters.AddWithValue("@file_comorsec", file_comorsec);
            SqlDataAdapter oda = new SqlDataAdapter(oCmd);
            DataTable      dt  = new DataTable();

            oda.Fill(dt);

            string pasw          = GenAESCodePass(file_parentid);//解壓縮密碼
            int    fileTotalSize = 0;

            using (Stream zipFileStream = new FileStream(pathUrl("Zippath") + dt.Rows[0]["file_encryptfileName"].ToString() + ".zip", FileMode.Create, FileAccess.Write))
            {
                ZipWriter zipWriter = new ZipWriter(zipFileStream);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //把sfts_file的狀態更新(0.5處理中)
                    Update_sfts_fileOnGoing(dt.Rows[i]["file_id"].ToString(), "0.5");

                    ZipItemLocalHeader localHeader;
                    //密件
                    localHeader = new ZipItemLocalHeader(
                        dt.Rows[i]["file_origiFileName"].ToString() + dt.Rows[i]["file_exten"].ToString(),
                        CompressionMethod.Deflated64,
                        CompressionLevel.Highest,
                        EncryptionMethod.WinZipAes,
                        pasw);

                    zipWriter.WriteItemLocalHeader(localHeader);


                    using (Stream sourceStream = new FileStream(pathUrl("path") + dt.Rows[i]["file_encryptfileName"].ToString() + dt.Rows[i]["file_exten"].ToString(), FileMode.Open, FileAccess.Read))
                    {
                        zipWriter.WriteItemData(sourceStream);
                    }

                    fileTotalSize += Convert.ToInt32(dt.Rows[i]["file_size"].ToString());
                }
                zipWriter.CloseZipFile();
                zipWriter.Dispose();
            }


            //把sft_afile新增
            INSERT_sfts_afile(dt.Rows[0]["file_parentid"].ToString(), dt.Rows[0]["file_comorsec"].ToString(), pasw,
                              "", dt.Rows[0]["file_encryptfileName"].ToString(), fileTotalSize, dt.Rows[0]["file_stat"].ToString(), ".zip");

            //把sfts_file的狀態更新
            Update_sfts_file(file_parentid, file_comorsec, "1");


            oda.Dispose();
            oConn.Close();
            oConn.Dispose();
            oCmd.Dispose();
        }
Beispiel #28
0
        public void commonORnonforwardfun(string file_parentid, string file_comorsec)
        {
            StringBuilder sb    = new StringBuilder();
            SqlConnection oConn = new SqlConnection(pathUrl("DSN"));
            SqlCommand    oCmd  = new SqlCommand();

            oCmd.Connection = oConn;
            sb.Append(@"SELECT * FROM sfts_file WHERE file_parentid = @file_parentid AND file_comorsec= @file_comorsec ");
            oCmd.CommandText = sb.ToString();
            oCmd.Parameters.AddWithValue("@file_parentid", file_parentid);
            oCmd.Parameters.AddWithValue("@file_comorsec", file_comorsec);
            SqlDataAdapter oda = new SqlDataAdapter(oCmd);
            DataTable      dt  = new DataTable();

            oda.Fill(dt);

            Random ram     = new Random();
            int    numb    = ram.Next(9999);
            string zipNmae = DateTime.Now.ToString("yyyyMMddHHmmss") + numb.ToString();

            //一般檔案 還需要壓縮成一個檔案 裡面放所有的檔案 但是不需要解壓縮密碼
            using (Stream zipFileStream = new FileStream(pathUrl("Zippath") + zipNmae + ".zip", FileMode.Create, FileAccess.Write))
            {
                int       fileSize  = 0;
                ZipWriter zipWriter = new ZipWriter(zipFileStream);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //把sfts_file的狀態更新(0.5處理中)
                    Update_sfts_fileOnGoing(dt.Rows[i]["file_id"].ToString(), "0.5");

                    ZipItemLocalHeader localHeader;
                    //一般
                    localHeader = new ZipItemLocalHeader(
                        dt.Rows[i]["file_origiFileName"].ToString() + dt.Rows[i]["file_exten"].ToString(),
                        CompressionMethod.Deflated64,
                        CompressionLevel.Highest
                        );

                    zipWriter.WriteItemLocalHeader(localHeader);

                    using (Stream sourceStream = new FileStream(pathUrl("path") + dt.Rows[i]["file_encryptfileName"].ToString() + dt.Rows[i]["file_exten"].ToString(), FileMode.Open, FileAccess.Read))
                    {
                        zipWriter.WriteItemData(sourceStream);
                    }
                    fileSize += Convert.ToInt32(dt.Rows[i]["file_size"].ToString());
                }
                zipWriter.CloseZipFile();
                zipWriter.Dispose();

                //把所有壓成一包的壓縮檔資料塞一筆到afile內 差別只在於此筆資料 file_origiFileName="" and afile_encrypt="N"(方便在撈的時候餵給GridView不要被撈到)
                INSERT_sfts_afile(dt.Rows[0]["file_parentid"].ToString(), dt.Rows[0]["file_comorsec"].ToString(), "N",
                                  "", zipNmae, fileSize, dt.Rows[0]["file_stat"].ToString(), ".zip");
            }


            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //不管怎樣 還是把所有資料二話不說複製一份到sfts_afile裡面 方便處裡
                INSERT_sfts_afile(dt.Rows[i]["file_parentid"].ToString(), dt.Rows[i]["file_comorsec"].ToString(), dt.Rows[i]["file_encrypt"].ToString(),
                                  dt.Rows[i]["file_origiFileName"].ToString(), dt.Rows[i]["file_encryptfileName"].ToString(), Convert.ToInt32(dt.Rows[i]["file_size"].ToString()), dt.Rows[i]["file_stat"].ToString(), dt.Rows[i]["file_exten"].ToString());
            }

            //把sfts_file的狀態更新
            Update_sfts_file(file_parentid, file_comorsec, "1");


            oda.Dispose();
            oConn.Close();
            oConn.Dispose();
            oCmd.Dispose();
        }
Beispiel #29
0
        override protected void Render(Image image, Drawable drawable)
        {
            var writer = new ZipWriter(image);

            writer.CreateFxz();
        }
Beispiel #30
0
        // TODO: throw an exception if "target" attribute not set
        public override void WriteString(string text)
        {
            Node elt = (Node)elements.Peek();

            if (!elt.Ns.Equals(ZIP_POST_PROCESS_NAMESPACE) && !elt.Ns.Equals(PIC_POST_PROCESS_NAMESPACE) && !elt.Ns.Equals(OLE_POST_PROCESS_NAMESPACE))
            {
                if (delegateWriter != null)
                {
                    delegateWriter.WriteString(text);
                }
            }
            else
            {
                // Pick up the target attribute
                if (attributes.Count > 0)
                {
                    Node attr = (Node)attributes.Peek();
                    if (attr.Ns.Equals(ZIP_POST_PROCESS_NAMESPACE) || attr.Ns.Equals(PIC_POST_PROCESS_NAMESPACE) || attr.Ns.Equals(OLE_POST_PROCESS_NAMESPACE))
                    {
                        switch (elt.Name)
                        {
                        case ARCHIVE_ELEMENT:    //archive
                            // Prevent nested archive creation
                            if (processingState == ProcessingState.None && attr.Name.Equals("target"))
                            {
                                logger.Info("creating archive : " + text);

                                // 输出包的路径放在式样单中间文档元素<archive Target="包路径名">中了,
                                // 从中提取即可,当然也可以直接传递过来
                                zipOutputStream = ZipFactory.CreateArchive(text);
                                processingState = ProcessingState.EntryWaiting;
                            }
                            break;

                        case PART_ELEMENT:    //entry
                            // Prevent nested entry creation
                            if (processingState == ProcessingState.EntryWaiting && attr.Name.Equals("target"))
                            {
                                logger.Info("creating new part : " + text);

                                //此处的text是entry的target属性的值,也就是文件的路径
                                zipOutputStream.AddEntry(text);
                                delegateWriter  = XmlWriter.Create(zipOutputStream, delegateSettings);
                                processingState = ProcessingState.EntryStarted;
                                delegateWriter.WriteStartDocument();
                            }
                            break;

                        case OLE_DRAW:
                        case OLE_DRAWRELS:
                        case OLE_EMBEDDING:  //ole
                        case PIC_ELEMENT:    //picture
                            if (processingState != ProcessingState.None)
                            {
                                if (attr.Name.Equals("target"))
                                {
                                    binarySource += text;
                                    logger.Info("picture: target=" + binarySource);
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }