Exemplo n.º 1
11
        private void button1_Click(object sender, EventArgs e)
        {
            if (Game.ship.id == null)
            {
                throw new InvalidDataException("**** Error! ****\n You have not set a ship ID! Please set one before exporting!!");
            }
            string outputFolder = Path.Combine(Application.StartupPath, Game.ship.id);
            Directory.CreateDirectory(outputFolder);
            Directory.CreateDirectory(Path.Combine(outputFolder, "img"));
            Directory.CreateDirectory(Path.Combine(outputFolder, "img\\ship"));
            Directory.CreateDirectory(Path.Combine(outputFolder, "data"));

            Game.game.ExportLayoutTxt(Path.Combine(outputFolder, "data\\" + Game.ship.layout + ".txt"));
            Game.game.ExportLayoutXML(Path.Combine(outputFolder, "data\\" + Game.ship.layout + ".xml"));
            Game.game.ExportBlueprintXML(Path.Combine(outputFolder, "data\\" + "blueprints.xml.append"), append: true);

            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Path.Combine(outputFolder, Game.ship.name + string.Format("-{0:yyyy-MM-dd_hh-mm-ss}", DateTime.Now) + ".ftl"));
            if (Directory.Exists(Path.Combine(outputFolder, "img")))
                zip.AddDirectory(Path.Combine(outputFolder, "img"), "\\img");
            if (Directory.Exists(Path.Combine(outputFolder, "data")))
                zip.AddDirectory(Path.Combine(outputFolder, "data"), "\\data");

            if (Directory.Exists(Path.Combine(outputFolder, "audio")))
                zip.AddDirectory(Path.Combine(outputFolder, "audio"), "\\audio");

            zip.Save();

            System.Diagnostics.Process.Start(outputFolder);
        }
    public ActionResult Test(long id)
    {
      List<string> list = dataProvider.GeneralRepository.Temp_CreateSpreadsheets(id);
      if (list.Count() == 0) return View("Index");
      string folder = String.Format("{0:yyyyMMdd}", DateTime.Now);
      System.IO.FileInfo fi;
      Response.BufferOutput = true;
      Response.Clear();
      Response.ContentType = "application/zip";
      Response.AddHeader("content-disposition", "attachment; filename=" + folder + ".zip");

      using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
      {
        foreach (string path in list)
        {
          fi = new System.IO.FileInfo(path);
          if (!fi.Exists) continue;
          zip.AddFile(path, folder);
        }
        zip.Save(Response.OutputStream);
      }
      System.Threading.Thread.Sleep(10000);
      Response.End();
      foreach (string path in list)
      {
        fi = new System.IO.FileInfo(path);
        if (!fi.Exists) continue;
        fi.Delete();
      }
      return RedirectToRoute("Index");
    }
Exemplo n.º 3
1
		public void ZipDirectory(string zipFilePath, string directoryPathToCompress, string directoryPathInArchive)
		{
			Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipFilePath);
			zf.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
			zf.AddDirectory(directoryPathToCompress, directoryPathInArchive);
			zf.AddProgress += delegate(object sender, Ionic.Zip.AddProgressEventArgs e)
			{
				Console.WriteLine("\tAdding " + e.CurrentEntry.FileName);
			};
			zf.Save();
		}
Exemplo n.º 4
1
        public static bool CreateZipArchiv(string[] files, string zipArchiv)
        {
            var zipFile = new Ionic.Zip.ZipFile(zipArchiv);

            foreach (var file in files)
            {
                if (File.GetAttributes(file).HasFlag(FileAttributes.Directory))
                {
                    zipFile.AddDirectory(file,new DirectoryInfo(file).Name);
                }
                else
                {
                    zipFile.AddFile(file,String.Empty);
                }
                zipFile.Save();
            }
            return true;
        }
Exemplo n.º 5
1
        public static void CreateZipResponse(List<string> ZipFileList, HttpResponse Response, string ZipFileName, string TempFolder)
        {
            Response.Clear();

            Response.ContentType = "application/octet-stream"; // "application/zip";

            Response.AddHeader("content-disposition", "filename=\"" + ZipFileName + ".zip\"");
            try
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (string fileName in ZipFileList)
                    {
                        string path = fileName.Contains("Modules\\" + ZipFileName + "\\")
                                          ? fileName.Substring(fileName.LastIndexOf(ZipFileName + "\\"),
                                                               fileName.Substring(
                                                                   fileName.LastIndexOf(ZipFileName + "\\")).LastIndexOf
                                                                   ("\\"))
                                          : ZipFileName;

                        zip.AddFile(fileName, path);
                    }

                    zip.Save(Response.OutputStream);

                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Response.End();
            }
        }
Exemplo n.º 6
1
        protected override string GenerateCommandLineCommands()
        {
            var cmd = new CommandLineBuilder ();

            if (!UseProguard) {
                // Add the JavaOptions if they are not null
                // These could be any of the additional options
                if (!string.IsNullOrEmpty (JavaOptions)) {
                    cmd.AppendSwitch (JavaOptions);
                }

                // Add the specific -XmxN to override the default heap size for the JVM
                // N can be in the form of Nm or NGB (e.g 100m or 1GB )
                cmd.AppendSwitchIfNotNull ("-Xmx", JavaMaximumHeapSize);

                cmd.AppendSwitchIfNotNull ("-jar ", Path.Combine (ProguardJarPath));
            }

            if (!ClassesOutputDirectory.EndsWith (Path.DirectorySeparatorChar.ToString ()))
                ClassesOutputDirectory += Path.DirectorySeparatorChar;
            var classesFullPath = Path.GetFullPath (ClassesOutputDirectory);

            if (File.Exists (ProguardJarInput))
                File.Delete (ProguardJarInput);
            var zip = new Ionic.Zip.ZipFile (ProguardJarInput, new System.Text.UTF8Encoding (false));
            foreach (var file in Directory.GetFiles (classesFullPath, "*", SearchOption.AllDirectories))
                zip.AddFile (file, Path.GetDirectoryName (file.Substring (classesFullPath.Length)));
            zip.Save ();
            zip.Dispose ();

            var acwLines = File.ReadAllLines (AcwMapFile);
            using (var appcfg = File.CreateText (ProguardGeneratedApplicationConfiguration))
                for (int i = 0; i + 3 < acwLines.Length; i += 4)
                    try {
                        var java = acwLines [i + 3].Substring (acwLines [i + 3].IndexOf (';') + 1);
                        appcfg.WriteLine ("-keep class " + java + " { *; }");
                    } catch {
                        // skip invalid lines
                    }

            var injars = new List<string> ();
            var libjars = new List<string> ();
            injars.Add (ProguardJarInput);
            if (JavaLibrariesToEmbed != null)
                foreach (var jarfile in JavaLibrariesToEmbed)
                    injars.Add (jarfile.ItemSpec);

            using (var xamcfg = File.Create (ProguardCommonXamarinConfiguration))
                GetType ().Assembly.GetManifestResourceStream ("proguard_xamarin.cfg").CopyTo (xamcfg);

            var configs = ProguardConfigurationFiles
                .Replace ("{sdk.dir}", Path.GetDirectoryName (Path.GetDirectoryName (ProguardHome)) + Path.DirectorySeparatorChar)
                .Replace ("{intermediate.common.xamarin}", ProguardCommonXamarinConfiguration)
                .Replace ("{intermediate.references}", ProguardGeneratedReferenceConfiguration)
                .Replace ("{intermediate.application}", ProguardGeneratedApplicationConfiguration)
                .Replace ("{project}", string.Empty) // current directory anyways.
                .Split (';')
                .Select (s => s.Trim ())
                .Where (s => !string.IsNullOrWhiteSpace (s));

            foreach (var file in configs) {
                if (File.Exists (file))
                    cmd.AppendSwitchIfNotNull ("-include ", file);
                else
                    Log.LogWarning ("Proguard configuration file '{0}' was not found.", file);
            }

            libjars.Add (JavaPlatformJarPath);
            if (ExternalJavaLibraries != null)
                foreach (var jarfile in ExternalJavaLibraries.Select (p => p.ItemSpec))
                    libjars.Add (jarfile);

            cmd.AppendSwitch ("\"-injars");
            cmd.AppendSwitch (string.Join (Path.PathSeparator.ToString (), injars.Distinct ().Select (s => '\'' + s + '\''))+"\"");

            cmd.AppendSwitch ("\"-libraryjars");
            cmd.AppendSwitch (string.Join (Path.PathSeparator.ToString (), libjars.Distinct ().Select (s => '\'' + s + '\''))+"\"");

            cmd.AppendSwitch ("-outjars");
            cmd.AppendSwitch ('"' + ProguardJarOutput + '"');

            if (EnableLogging) {
                cmd.AppendSwitchIfNotNull ("-dump ", DumpOutput);
                cmd.AppendSwitchIfNotNull ("-printseeds ", PrintSeedsOutput);
                cmd.AppendSwitchIfNotNull ("-printusage ", PrintUsageOutput);
                cmd.AppendSwitchIfNotNull ("-printmapping ", PrintMappingOutput);
            }

            return cmd.ToString ();
        }
Exemplo n.º 7
0
		public static byte[] SerializeVoxelAreaData (VoxelArea v) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
			
			writer.Write (v.width);
			writer.Write (v.depth);
			writer.Write (v.linkedSpans.Length);
			
			for (int i=0;i<v.linkedSpans.Length;i++) {
				writer.Write(v.linkedSpans[i].area);
				writer.Write(v.linkedSpans[i].bottom);
				writer.Write(v.linkedSpans[i].next);
				writer.Write(v.linkedSpans[i].top);
			}
			
			//writer.Close();
			writer.Flush();
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			stream.Position = 0;
			zip.AddEntry ("data",stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			zip.Save(stream2);
			byte[] bytes = stream2.ToArray();
			stream.Close();
			stream2.Close();
			return bytes;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Exemplo n.º 8
0
 /// <summary>
 /// 压缩文件(传递参数源文件路径和压缩后的文件路径)
 /// </summary>
 /// <param name="srcPath">源文件全路径</param>
 /// <param name="destPath">保存为Zip包的目录</param>
 public static void ZipFileInfo(string srcPath, string destPath)
 {
     using (var zip = new ZipFile())
     {
         Ionic.Zip.ZipEntry zipEntry = zip.AddFile(srcPath, @"\");
         zipEntry.Comment = "Added by Cheeso's CreateZip utility.";
         zip.Comment = $"This zip archive was created by the CreateZip example application on machine '{Dns.GetHostName()}'";
         zip.Save(destPath);
     }
 }
Exemplo n.º 9
0
 public void Error_AddFile_NonExistentFile()
 {
     string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_NonExistentFile.zip");
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileToCreate))
     {
         zip.AddFile("ThisFileDoesNotExist.txt");
         zip.Comment = "This is a Comment On the Archive";
         zip.Save();
     }
 }
Exemplo n.º 10
0
 /// <summary>
 /// 压缩目录下的所有文件
 /// </summary>
 /// <param name="filePath">源文件根目录</param>
 /// <param name="savePath">保存为Zip包的目录</param>
 public static void ZipDirFileInfo(string filePath, string savePath)
 {
     using (var zip = new ZipFile())
     {
         //读取文件夹下面的所有文件
         string[] fileNames = Directory.GetFiles(filePath);
         foreach (string fileName in fileNames)
         {
             Ionic.Zip.ZipEntry zipEntry = zip.AddFile(fileName, @"\");
             zipEntry.Comment = "Added by Cheeso's CreateZip utility.";
         }
         zip.Comment = $"This zip archive was created by the CreateZip example application on machine '{Dns.GetHostName()}'";
         zip.Save(savePath);
     }
 }
Exemplo n.º 11
0
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = "application/zip";
            response.AppendHeader("content-disposition", "attachment; filename=" + FileName);

            using (var zipFile = new Ionic.Zip.ZipFile())
            {
                foreach (var e in this.Entries)
                {
                    zipFile.AddEntry(e.FileName, e.BytesStream);
                }
                zipFile.Save(response.OutputStream);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// 压缩一个文件返回流信息
        /// </summary>
        /// <param name="filePath">源文件服务器路径</param>
        /// <param name="fileName">压缩文件名</param>
        /// <returns></returns>
        public static byte[] ZipFileOneInfo(string filePath, string fileName)
        {
            using (var zipFile = new ZipFile(Encoding.UTF8))
            {
                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    zipFile.AddEntry(fileName, fileStream);
                    using (var memoryStream = new MemoryStream())
                    {
                        zipFile.Save(memoryStream);
                        return memoryStream.ToArray();
                    }

                }
            }
        }
Exemplo n.º 13
0
 public ActionResult Test2(long id)
 {
   System.IO.FileInfo fi = new System.IO.FileInfo(dataProvider.GeneralRepository.Temp_CreateSpreadsheetW(id));
   string folder = System.IO.Path.GetFileNameWithoutExtension(fi.FullName);
   if (!fi.Exists) return RedirectToRoute("Index");
   Response.Clear();
   Response.ContentType = "application/zip";
   Response.AddHeader("content-disposition", "attachment; filename=" + folder + ".zip");
   using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
   {
     zip.AddFile(fi.FullName, folder);
     zip.Save(Response.OutputStream);
   }
   System.Threading.Thread.Sleep(30000);
   Response.End();
   fi.Delete();
   return View("Index");
 }
Exemplo n.º 14
0
        public static void DownloadFiles(List<string> archives, HttpContext httpContext)
        {
            if (archives.Count == 0)
                return;
            FileAttributes attr1 = System.IO.File.GetAttributes(archives[0]);
            if (archives.Count == 1 && ((attr1 & FileAttributes.Directory) != FileAttributes.Directory))
            {
                string filename = Path.GetFileName(archives[0]);
                httpContext.Response.Buffer = true;
                httpContext.Response.Clear();
                httpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
                httpContext.Response.ContentType = "application/octet-stream";
                httpContext.Response.WriteFile(archives[0]);
            }
            else
            {
                string zipName = String.Format("archive-{0}.zip",
                                      DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                httpContext.Response.Buffer = true;
                httpContext.Response.Clear();
                httpContext.Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                httpContext.Response.ContentType = "application/zip";
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (string path in archives)
                    {
                        try
                        {
                            FileAttributes attr = System.IO.File.GetAttributes(path);

                            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                                zip.AddDirectory(path, Path.GetFileNameWithoutExtension(path));
                            else
                                zip.AddFile(path, "");
                        }
                        catch (Exception)
                        {
                        }
                    }
                    zip.Save(httpContext.Response.OutputStream);
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Do a simple zip of the given directory
        /// </summary>
        /// <param name="sourceDirPath"></param>
        /// <param name="targetZipPath"></param>
        /// <returns>True if succeeds</returns>
        public static bool zipChangeSetDir(string sourceDirPath, string targetZipPath)
        {
            try
            {
                if (string.IsNullOrEmpty(targetZipPath) || !Directory.Exists(sourceDirPath) || string.IsNullOrEmpty(sourceDirPath))
                    return false;

                createDirForFile(targetZipPath);

                using (Ionic.Zip.ZipFile zfile = new Ionic.Zip.ZipFile())
                {
                    zfile.AddDirectory(sourceDirPath);
                    //zfile.AddDirectory(sourceDirPath + "\\new");
                    zfile.Save(targetZipPath);
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemplo n.º 16
0
 private void OverwriteEpub(string file, string tempFile)
 {
     File.Delete(file);
     using (var zip = new Ionic.Zip.ZipFile())
     {
         var mime = zip.AddEntry("mimetype", "application/epub+zip", Encoding.ASCII);
         zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Never;
         mime.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
         mime.CompressionMethod = Ionic.Zip.CompressionMethod.None;
         var metaDir = Path.Combine(tempFile, "META-INF");
         var meta = zip.AddDirectory(metaDir, "META-INF");
         meta.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
         var contentDir = Path.Combine(tempFile, "OEBPS");
         var content = zip.AddDirectory(contentDir, "OEBPS");
         content.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
         zip.Save(file);
     }
     directory.Delete(tempFile, true);
 }
Exemplo n.º 17
0
        /// <summary>
        /// Build the input directory to an output binary package file using the BinarySerializer.
        /// </summary>
        public static void BuildDirectory(string directoryName, string outputFileName, Action <string, int, int> onProgress = null, Action <string, Exception> onError = null)
        {
            directoryName  = Path.GetFullPath(directoryName);
            outputFileName = Path.GetFullPath(outputFileName);

            var outputDirectory = outputFileName + "-" + Guid.NewGuid().ToString("N").ToUpper();

            Directory.CreateDirectory(outputDirectory);

            try
            {
                var files = Directory.EnumerateFiles(directoryName, "*.*", SearchOption.AllDirectories).Except(
                    IgnoredFileNamePatterns.SelectMany(x => Directory.EnumerateFiles(directoryName, x, SearchOption.AllDirectories))).ToArray();

                for (int i = 0; i < files.Length; i++)
                {
                    var file = Path.GetFullPath(files[i]);

                    if (onProgress != null)
                    {
                        onProgress(file, i, files.Length);
                    }

                    try
                    {
                        BuildFile(file, Path.Combine(outputDirectory, Extensions.MakeRelativePath(directoryName, file)));
                    }
                    catch (Exception e)
                    {
                        if (onError != null)
                        {
                            onError(file, e);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                if (onProgress != null)
                {
                    onProgress("", files.Length, files.Length);
                }

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

                using (var archive = new Ionic.Zip.ZipFile(outputFileName, Encoding.UTF8))
                {
                    archive.CompressionMethod = Ionic.Zip.CompressionMethod.Deflate;
                    archive.AddDirectory(outputDirectory);
                    archive.Save();
                }
            }
            catch
            {
                Directory.Delete(outputDirectory, true);
                throw;
            }
            finally
            {
                Directory.Delete(outputDirectory, true);
            }
        }
Exemplo n.º 18
0
        public override void ExecuteBuild()
        {
            // Parse the target list
            string[] Targets = ParseParamValues("Target");
            if (Targets.Length == 0)
            {
                throw new AutomationException("No targets specified (eg. -Target=\"UE4Editor Win64 Development\")");
            }

            // Parse the archive path
            string ArchivePath = ParseParamValue("Archive");

            if (ArchivePath != null && (!ArchivePath.StartsWith("//") || ArchivePath.Sum(x => (x == '/')? 1 : 0) < 4))
            {
                throw new AutomationException("Archive path is not a valid depot filename");
            }

            // Parse the stream name
            string StreamName = ParseParamValue("Stream");

            if (StreamName == null && ArchivePath != null)
            {
                StreamName = ArchivePath.Substring(0, ArchivePath.IndexOf('/', ArchivePath.IndexOf('/', 2) + 1));
            }

            // Prepare the build agenda
            UE4Build.BuildAgenda Agenda = new UE4Build.BuildAgenda();
            foreach (string Target in Targets)
            {
                string[] Tokens = Target.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                UnrealTargetConfiguration Configuration = UnrealTargetConfiguration.Unknown;
                UnrealTargetPlatform      Platform;
                if (Tokens.Length < 3 || !UnrealTargetPlatform.TryParse(Tokens[1], out Platform) || !Enum.TryParse(Tokens[2], true, out Configuration))
                {
                    throw new AutomationException("Invalid target '{0}' - expected <TargetName> <Platform> <Configuration>");
                }

                Agenda.AddTarget(Tokens[0], Platform, Configuration, InAddArgs: String.Join(" ", Tokens.Skip(3)));
            }

            // Build everything
            UE4Build Builder = new UE4Build(this);

            Builder.Build(Agenda, InUpdateVersionFiles: ArchivePath != null);

            // Include the build products for UAT and UBT if required
            if (ParseParam("WithUAT"))
            {
                Builder.AddUATFilesToBuildProducts();
            }
            if (ParseParam("WithUBT"))
            {
                Builder.AddUBTFilesToBuildProducts();
            }

            // Archive the build products
            if (ArchivePath != null)
            {
                // Create an output folder
                string OutputFolder = Path.Combine(CommandUtils.CmdEnv.LocalRoot, "ArchiveForUGS");
                Directory.CreateDirectory(OutputFolder);

                // Create a temp folder for storing stripped PDB files
                string SymbolsFolder = Path.Combine(OutputFolder, "Symbols");
                Directory.CreateDirectory(SymbolsFolder);

                // Get the Windows toolchain
                Platform WindowsTargetPlatform = Platform.GetPlatform(UnrealTargetPlatform.Win64);

                // Figure out all the files for the archive
                string ZipFileName = Path.Combine(OutputFolder, "Archive.zip");
                using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile())
                {
                    Zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always;
                    foreach (string BuildProduct in Builder.BuildProductFiles)
                    {
                        if (!File.Exists(BuildProduct))
                        {
                            throw new AutomationException("Missing build product: {0}", BuildProduct);
                        }
                        if (BuildProduct.EndsWith(".pdb", StringComparison.InvariantCultureIgnoreCase))
                        {
                            string StrippedFileName = CommandUtils.MakeRerootedFilePath(BuildProduct, CommandUtils.CmdEnv.LocalRoot, SymbolsFolder);
                            Directory.CreateDirectory(Path.GetDirectoryName(StrippedFileName));
                            WindowsTargetPlatform.StripSymbols(new FileReference(BuildProduct), new FileReference(StrippedFileName));
                            Zip.AddFile(StrippedFileName, Path.GetDirectoryName(CommandUtils.StripBaseDirectory(StrippedFileName, SymbolsFolder)));
                        }
                        else
                        {
                            Zip.AddFile(BuildProduct, Path.GetDirectoryName(CommandUtils.StripBaseDirectory(BuildProduct, CommandUtils.CmdEnv.LocalRoot)));
                        }
                    }
                    // Create the zip file
                    Console.WriteLine("Writing {0}...", ZipFileName);
                    Zip.Save(ZipFileName);
                }

                // Submit it to Perforce if required
                if (CommandUtils.AllowSubmit)
                {
                    // Delete any existing clientspec for submitting
                    string ClientName = Environment.MachineName + "_BuildForUGS";

                    // Create a brand new one
                    P4ClientInfo Client = new P4ClientInfo();
                    Client.Owner    = CommandUtils.P4Env.User;
                    Client.Host     = Environment.MachineName;
                    Client.Stream   = StreamName;
                    Client.RootPath = Path.Combine(OutputFolder, "Perforce");
                    Client.Name     = ClientName;
                    Client.Options  = P4ClientOption.NoAllWrite | P4ClientOption.NoClobber | P4ClientOption.NoCompress | P4ClientOption.Unlocked | P4ClientOption.NoModTime | P4ClientOption.RmDir;
                    Client.LineEnd  = P4LineEnd.Local;
                    P4.CreateClient(Client, AllowSpew: false);

                    // Create a new P4 connection for this workspace
                    P4Connection SubmitP4 = new P4Connection(Client.Owner, Client.Name, P4Env.ServerAndPort);
                    SubmitP4.Revert("-k //...");

                    // Figure out where the zip file has to go in Perforce
                    P4WhereRecord WhereZipFile = SubmitP4.Where(ArchivePath, false).FirstOrDefault(x => !x.bUnmap && x.Path != null);
                    if (WhereZipFile == null)
                    {
                        throw new AutomationException("Couldn't locate {0} in this workspace");
                    }

                    // Get the latest version of it
                    int NewCL = SubmitP4.CreateChange(Description: String.Format("[CL {0}] Updated binaries", P4Env.Changelist));
                    SubmitP4.Sync(String.Format("-k \"{0}\"", ArchivePath), AllowSpew: false);
                    CommandUtils.CopyFile(ZipFileName, WhereZipFile.Path);
                    SubmitP4.Add(NewCL, String.Format("\"{0}\"", ArchivePath));
                    SubmitP4.Edit(NewCL, String.Format("\"{0}\"", ArchivePath));

                    // Submit it
                    int SubmittedCL;
                    SubmitP4.Submit(NewCL, out SubmittedCL);
                    if (SubmittedCL <= 0)
                    {
                        throw new AutomationException("Submit failed.");
                    }
                    Console.WriteLine("Submitted in changelist {0}", SubmittedCL);
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// 解析指定压缩存档
        /// </summary>
        /// <param name="path">压缩存档路径</param>
        /// <returns></returns>
        public static SaveData Parse(string path)
        {
            SaveData ans = null;

            if (!path.EndsWith(".zip"))
            {
                if (File.Exists(Path.Combine(path, "date.json")))
                {
                    var content = File.ReadAllText(Path.Combine(path, "date.json"));
                    ans = JsonConvert.DeserializeObject(content, typeof(SaveData)) as SaveData;
                }
                else if (!File.Exists(Path.Combine(path, "TW_Save_Date_0.twV0")) &&
                         !File.Exists(Path.Combine(path, "TW_Save_Date_0.tw")))
                {
                    throw new System.Exception(path);
                }
                else
                {
                    string file     = null;
                    bool   rijndeal = true;
                    if (File.Exists(Path.Combine(path, "TW_Save_Date_0.twV0")))
                    {
                        file     = Path.Combine(path, "TW_Save_Date_0.twV0");
                        rijndeal = false;
                    }
                    else
                    {
                        file     = Path.Combine(path, "TW_Save_Date_0.tw");
                        rijndeal = true;
                    }
                    DateFile.SaveDate date = null;
                    try
                    {
                        date = typeof(SaveDateFile)
                               .GetMethod("GetData", BindingFlags.Public | BindingFlags.Instance)
                               .Invoke(SaveDateFile.instance,
                                       new object[] { file, typeof(DateFile.SaveDate), rijndeal })
                               as DateFile.SaveDate;
                    }
                    catch (AmbiguousMatchException)
                    {
                        date = typeof(SaveDateFile)
                               .GetMethod("GetData", BindingFlags.Public | BindingFlags.Instance)
                               .Invoke(SaveDateFile.instance,
                                       new object[] { file, typeof(DateFile.SaveDate) })
                               as DateFile.SaveDate;
                    }
                    ans = new SaveData(date._mainActorName, date._year, date._samsara,
                                       date._dayTrun, date._playerSeatName, date._playTime);
                    File.WriteAllText(Path.Combine(path, "date.json"),
                                      JsonConvert.SerializeObject(ans));
                }
            }
            else
            {
                using (var zip = new Ionic.Zip.ZipFile(path))
                {
                    if (zip.ContainsEntry("date.json"))
                    {
                        using (var stream = new MemoryStream())
                        {
                            zip.SelectEntries("date.json").First().Extract(stream);
                            stream.Seek(0, SeekOrigin.Begin);
                            using (var reader = new StreamReader(stream))
                            {
                                var serializer = JsonSerializer.Create();
                                ans = serializer.Deserialize(reader,
                                                             typeof(SaveData)) as SaveData;
                            }
                        }
                    }
                    else if (!zip.ContainsEntry("TW_Save_Date_0.twV0") &&
                             !zip.ContainsEntry("TW_Save_Date_0.tw"))
                    {
                        throw new System.Exception(path); // 错误存档
                    }
                    else // 不含加速文件
                    {
                        var tmp = Path.Combine(
                            System.Environment.GetEnvironmentVariable("TEMP"),
                            "SaveDate.tw");

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

                        bool rijndeal = true;
                        using (var stream = File.OpenWrite(tmp))
                        {
                            if (zip.ContainsEntry("TW_Save_Date_0.twV0"))
                            {
                                zip.SelectEntries("TW_Save_Date_0.twV0").First().Extract(stream);
                                rijndeal = false;
                            }
                            else if (zip.ContainsEntry("TW_Save_Date_0.tw"))
                            {
                                zip.SelectEntries("TW_Save_Date_0.tw").First().Extract(stream);
                                rijndeal = true;
                            }
                        }
                        DateFile.SaveDate date = null;
                        try
                        {
                            date = typeof(SaveDateFile)
                                   .GetMethod("GetData", BindingFlags.Public | BindingFlags.Instance)
                                   .Invoke(SaveDateFile.instance,
                                           new object[] { tmp, typeof(DateFile.SaveDate), rijndeal })
                                   as DateFile.SaveDate;
                        }
                        catch (AmbiguousMatchException)
                        {
                            date = typeof(SaveDateFile)
                                   .GetMethod("GetData", BindingFlags.Public | BindingFlags.Instance)
                                   .Invoke(SaveDateFile.instance,
                                           new object[] { tmp, typeof(DateFile.SaveDate) })
                                   as DateFile.SaveDate;
                        }
                        ans = new SaveData(date._mainActorName, date._year, date._samsara,
                                           date._dayTrun, date._playerSeatName, date._playTime);
                        //  添加加速文件
                        zip.AddEntry("date.json", JsonConvert.SerializeObject(ans));
                        zip.Save();
                    }
                }
            }
            return(ans);
        }
		public override void ExecuteBuild()
		{
			// Parse the target list
			string[] Targets = ParseParamValues("Target");
			if(Targets.Length == 0)
			{
				throw new AutomationException("No targets specified (eg. -Target=\"UE4Editor Win64 Development\")");
			}

			// Parse the archive path
			string ArchivePath = ParseParamValue("Archive");
			if(ArchivePath != null && (!ArchivePath.StartsWith("//") || ArchivePath.Sum(x => (x == '/')? 1 : 0) < 4))
			{
				throw new AutomationException("Archive path is not a valid depot filename");
			}

			// Prepare the build agenda
			UE4Build.BuildAgenda Agenda = new UE4Build.BuildAgenda();
			foreach(string Target in Targets)
			{
				string[] Tokens = Target.Split(new char[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries);

				UnrealTargetPlatform Platform;
				UnrealTargetConfiguration Configuration;
				if(Tokens.Length < 3 || !Enum.TryParse(Tokens[1], true, out Platform) || !Enum.TryParse(Tokens[2], true, out Configuration))
				{
					throw new AutomationException("Invalid target '{0}' - expected <TargetName> <Platform> <Configuration>");
				}

				Agenda.AddTarget(Tokens[0], Platform, Configuration, InAddArgs: String.Join(" ", Tokens.Skip(3)));
			}

			// Build everything
			UE4Build Builder = new UE4Build(this);
			Builder.Build(Agenda, InUpdateVersionFiles: ArchivePath != null);

			// Include the build products for UAT and UBT if required
			if(ParseParam("WithUAT"))
			{
				Builder.AddUATFilesToBuildProducts();
			}
			if(ParseParam("WithUBT"))
			{
				Builder.AddUBTFilesToBuildProducts();
			}

			// Archive the build products
			if(ArchivePath != null)
			{
				// Create an output folder
				string OutputFolder = Path.Combine(CommandUtils.CmdEnv.LocalRoot, "ArchiveForUGS");
				Directory.CreateDirectory(OutputFolder);

				// Create a temp folder for storing stripped PDB files
				string SymbolsFolder = Path.Combine(OutputFolder, "Symbols");
				Directory.CreateDirectory(SymbolsFolder);

				// Get the Windows toolchain
				UEToolChain WindowsToolChain = UEBuildPlatform.GetBuildPlatform(UnrealTargetPlatform.Win64).CreateContext(null).CreateToolChain(CPPTargetPlatform.Win64);

				// Figure out all the files for the archive
				Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile();
				Zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always;
				foreach(string BuildProduct in Builder.BuildProductFiles)
				{
					if(!File.Exists(BuildProduct))
					{
						throw new AutomationException("Missing build product: {0}", BuildProduct);
					}
					if(BuildProduct.EndsWith(".pdb", StringComparison.InvariantCultureIgnoreCase))
					{
						string StrippedFileName = CommandUtils.MakeRerootedFilePath(BuildProduct, CommandUtils.CmdEnv.LocalRoot, SymbolsFolder);
						Directory.CreateDirectory(Path.GetDirectoryName(StrippedFileName));
						WindowsToolChain.StripSymbols(BuildProduct, StrippedFileName);
						Zip.AddFile(StrippedFileName, Path.GetDirectoryName(CommandUtils.StripBaseDirectory(StrippedFileName, SymbolsFolder)));
					}
					else
					{
						Zip.AddFile(BuildProduct, Path.GetDirectoryName(CommandUtils.StripBaseDirectory(BuildProduct, CommandUtils.CmdEnv.LocalRoot)));
					}
				}
				// Create the zip file
				string ZipFileName = Path.Combine(OutputFolder, "Archive.zip");
				Console.WriteLine("Writing {0}...", ZipFileName);
				Zip.Save(ZipFileName);

				// Submit it to Perforce if required
				if(CommandUtils.AllowSubmit)
				{
					// Delete any existing clientspec for submitting
					string ClientName = Environment.MachineName + "_BuildForUGS";

					// Create a brand new one
					P4ClientInfo Client = new P4ClientInfo();
					Client.Owner = CommandUtils.P4Env.User;
					Client.Host = Environment.MachineName;
					Client.Stream = ArchivePath.Substring(0, ArchivePath.IndexOf('/', ArchivePath.IndexOf('/', 2) + 1));
					Client.RootPath = Path.Combine(OutputFolder, "Perforce");
					Client.Name = ClientName;
					Client.Options = P4ClientOption.NoAllWrite | P4ClientOption.NoClobber | P4ClientOption.NoCompress | P4ClientOption.Unlocked | P4ClientOption.NoModTime | P4ClientOption.RmDir;
					Client.LineEnd = P4LineEnd.Local;
					P4.CreateClient(Client, AllowSpew: false);

					// Create a new P4 connection for this workspace
					P4Connection SubmitP4 = new P4Connection(Client.Owner, Client.Name, P4Env.P4Port);
					SubmitP4.Revert("-k //...");

					// Figure out where the zip file has to go in Perforce
					P4WhereRecord WhereZipFile = SubmitP4.Where(ArchivePath, false).FirstOrDefault(x => !x.bUnmap && x.Path != null);
					if(WhereZipFile == null)
					{
						throw new AutomationException("Couldn't locate {0} in this workspace");
					}

					// Get the latest version of it
					int NewCL = SubmitP4.CreateChange(Description: String.Format("[CL {0}] Updated binaries", P4Env.Changelist));
					SubmitP4.Sync(String.Format("-k \"{0}\"", ArchivePath), AllowSpew:false);
					CommandUtils.CopyFile(ZipFileName, WhereZipFile.Path);
					SubmitP4.Add(NewCL, String.Format("\"{0}\"", ArchivePath));
					SubmitP4.Edit(NewCL, String.Format("\"{0}\"", ArchivePath));

					// Submit it
					int SubmittedCL;
					SubmitP4.Submit(NewCL, out SubmittedCL);
					if(SubmittedCL <= 0)
					{
						throw new AutomationException("Submit failed.");
					}
					Console.WriteLine("Submitted in changelist {0}", SubmittedCL);
				}
			}
		}
Exemplo n.º 21
0
 void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     progressBar1.Value = 100;
     viewModel.IsRunning = false;
     if (Backup.OutputBackupFilePath != "")
     {
         var zip = new Ionic.Zip.ZipFile();
         zip.UseUnicodeAsNecessary = true;
         //zip.AlternateEncoding = Encoding.UTF8;
         //zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.AsNecessary;
         zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
         zip.AddDirectory(Backup.TempFolderPath, null);
         zip.Save(Backup.OutputBackupFilePath);
         //zip.Dispose();
     }
 }
Exemplo n.º 22
0
        protected void btnExportarProyecto_Click(object sender, EventArgs e)
        {
            try
            {
                string nombre_proyecto = "";

                if (txtnombreproyecto.Value.Length >= 15)
                    nombre_proyecto = txtnombreproyecto.Value.Substring(0, 15);
                else
                    nombre_proyecto = txtnombreproyecto.Value;

                var proyecto_info = (from p in new ESM.Model.ESMBDDataContext().Proyectos
                                     where p.Id == proyecto_id
                                     select p).Single();

                string path = Server.MapPath("~/Files/Proyectos/");

                if (Directory.Exists(path + nombre_proyecto))
                {
                    if (!Directory.Exists(path + nombre_proyecto + "/Actas"))
                        Directory.CreateDirectory(path + nombre_proyecto + "/Actas");
                    if (!Directory.Exists(path + nombre_proyecto + "/Programacion"))
                        Directory.CreateDirectory(path + nombre_proyecto + "/Programacion");
                    if (!Directory.Exists(path + nombre_proyecto + "/M.S.E"))
                        Directory.CreateDirectory(path + nombre_proyecto + "/M.S.E");

                    string path_files = path + nombre_proyecto + @"\Programacion\MarcoLogico.xls";
                    string path_files_arbol_problemas = path + nombre_proyecto + @"\Programacion\ArbolProblemas.xls";
                    string path_files_arbol_objetivos = path + nombre_proyecto + @"\Programacion\ArbolObjetivos.xls";
                    string path_files_plan_accion = path + nombre_proyecto + @"\Programacion\PlanAccion.xls";

                    string html_marcologico = generateMarcoLogico(proyecto_id);
                    string html_arbolproblemas = generateArbolProblemasOrg();
                    string html_arbolobjetivos = generateArbolObjetivosOrg();
                    string html_planaccion = generatePlanOperativo(proyecto_id);

                    if (!File.Exists(path_files))
                    {
                        StreamWriter objFile = new StreamWriter(path_files, true, Encoding.UTF8);
                        objFile.Write(html_marcologico);
                        objFile.Flush();
                        objFile.Close();
                    }
                    else
                    {
                        File.Delete(path_files);

                        StreamWriter objFile = new StreamWriter(path_files, true, Encoding.UTF8);
                        objFile.Write(html_marcologico);
                        objFile.Flush();
                        objFile.Close();
                    }

                    if (!File.Exists(path_files_arbol_problemas))
                    {
                        StreamWriter objFile = new StreamWriter(path_files_arbol_problemas, true, Encoding.UTF8);
                        objFile.Write(html_arbolproblemas);
                        objFile.Flush();
                        objFile.Close();
                    }
                    else
                    {
                        File.Delete(path_files_arbol_problemas);

                        StreamWriter objFile = new StreamWriter(path_files_arbol_problemas, true, Encoding.UTF8);
                        objFile.Write(html_arbolproblemas);
                        objFile.Flush();
                        objFile.Close();
                    }

                    if (!File.Exists(path_files_arbol_objetivos))
                    {
                        StreamWriter objFile = new StreamWriter(path_files_arbol_objetivos, true, Encoding.UTF8);
                        objFile.Write(html_arbolobjetivos);
                        objFile.Flush();
                        objFile.Close();
                    }
                    else
                    {
                        File.Delete(path_files_arbol_objetivos);

                        StreamWriter objFile = new StreamWriter(path_files_arbol_objetivos, true, Encoding.UTF8);
                        objFile.Write(html_arbolobjetivos);
                        objFile.Flush();
                        objFile.Close();
                    }
                    if (!File.Exists(path_files_plan_accion))
                    {
                        StreamWriter objFile = new StreamWriter(path_files_plan_accion, true, Encoding.UTF8);
                        html_planaccion = "<h1>PLAN DE ACCIÓN " + proyecto_info.Proyecto1 + "</h1>" + html_planaccion;
                        objFile.Write(html_planaccion);
                        objFile.Flush();
                        objFile.Close();
                    }
                    else
                    {
                        File.Delete(path_files_plan_accion);

                        StreamWriter objFile = new StreamWriter(path_files_plan_accion, true, Encoding.UTF8);
                        html_planaccion = "<h1>PLAN DE ACCIÓN " + proyecto_info.Proyecto1 + "</h1>" + html_planaccion;
                        objFile.Write(html_planaccion);
                        objFile.Flush();
                        objFile.Close();
                    }
                }
                else
                {
                    Directory.CreateDirectory(path + "/" + nombre_proyecto);

                    if (!Directory.Exists(path + nombre_proyecto + "/Actas"))
                        Directory.CreateDirectory(path + nombre_proyecto + "/Actas");
                    if (!Directory.Exists(path + nombre_proyecto + "/Programacion"))
                        Directory.CreateDirectory(path + nombre_proyecto + "/Programacion");
                    if (!Directory.Exists(path + nombre_proyecto + "/M.S.E"))
                        Directory.CreateDirectory(path + nombre_proyecto + "/M.S.E");

                    string path_files = path + nombre_proyecto + @"\Programacion\MarcoLogico.xls";
                    string path_files_arbol_problemas = path + nombre_proyecto + @"\Programacion\ArbolProblemas.xls";
                    string path_files_arbol_objetivos = path + nombre_proyecto + @"\Programacion\ArbolObjetivos.xls";
                    string path_files_plan_accion = path + nombre_proyecto + @"\Programacion\PlanAccion.xls";

                    string html_marcologico = generateMarcoLogico(proyecto_id);
                    string html_arbolproblemas = generateArbolProblemasOrg();
                    string html_arbolobjetivos = generateArbolObjetivosOrg();
                    string html_planaccion = generatePlanOperativo(proyecto_id);

                    if (!File.Exists(path_files))
                    {
                        StreamWriter objFile = new StreamWriter(path_files, true, Encoding.UTF8);
                        objFile.Write(html_marcologico);
                        objFile.Flush();
                        objFile.Close();
                    }
                    else
                    {
                        File.Delete(path_files);

                        StreamWriter objFile = new StreamWriter(path_files, true, Encoding.UTF8);
                        objFile.Write(html_marcologico);
                        objFile.Flush();
                        objFile.Close();
                    }

                    if (!File.Exists(path_files_arbol_problemas))
                    {
                        StreamWriter objFile = new StreamWriter(path_files_arbol_problemas, true, Encoding.UTF8);
                        objFile.Write(html_arbolproblemas);
                        objFile.Flush();
                        objFile.Close();
                    }
                    else
                    {
                        File.Delete(path_files_arbol_problemas);

                        StreamWriter objFile = new StreamWriter(path_files_arbol_problemas, true, Encoding.UTF8);
                        objFile.Write(html_arbolproblemas);
                        objFile.Flush();
                        objFile.Close();
                    }

                    if (!File.Exists(path_files_arbol_objetivos))
                    {
                        StreamWriter objFile = new StreamWriter(path_files_arbol_objetivos, true, Encoding.UTF8);
                        objFile.Write(html_arbolobjetivos);
                        objFile.Flush();
                        objFile.Close();
                    }
                    else
                    {
                        File.Delete(path_files_arbol_objetivos);

                        StreamWriter objFile = new StreamWriter(path_files_arbol_objetivos, true, Encoding.UTF8);
                        objFile.Write(html_arbolobjetivos);
                        objFile.Flush();
                        objFile.Close();
                    }

                    if (!File.Exists(path_files_plan_accion))
                    {
                        StreamWriter objFile = new StreamWriter(path_files_plan_accion, true, Encoding.UTF8);
                        html_planaccion = "<h1>PLAN DE ACCIÓN " + proyecto_info.Proyecto1 + "</h1>" + html_planaccion;
                        objFile.Write(html_planaccion);
                        objFile.Flush();
                        objFile.Close();
                    }
                    else
                    {
                        File.Delete(path_files_plan_accion);

                        StreamWriter objFile = new StreamWriter(path_files_plan_accion, true, Encoding.UTF8);
                        html_planaccion = "<h1>PLAN DE ACCIÓN " + proyecto_info.Proyecto1 + "</h1>" + html_planaccion;
                        objFile.Write(html_planaccion);
                        objFile.Flush();
                        objFile.Close();
                    }
                }

                if (!File.Exists(path + nombre_proyecto + ".zip"))
                {
                    using (var zip = new Ionic.Zip.ZipFile())
                    {
                        zip.AddDirectory(path + "/" + nombre_proyecto);
                        zip.Save(path + nombre_proyecto + ".zip");
                    }
                }
                else
                {
                    File.Delete(path + nombre_proyecto + ".zip");

                    using (var zip = new Ionic.Zip.ZipFile())
                    {
                        zip.AddDirectory(path + "/" + nombre_proyecto);
                        zip.Save(path + nombre_proyecto + ".zip");
                    }
                }

                Response.Redirect("/Files/Proyectos/" + nombre_proyecto + ".zip");
            }
            catch (Exception) { /*Error*/}
        }
Exemplo n.º 23
0
        protected void ButtonDownload_Click(object sender, EventArgs e)
        {
            string[] paths = HiddenFieldDownload.Value.Split('|');
            if (paths.Length > 0 && !String.IsNullOrEmpty(paths[0]))
            {
                byte[] downloadFile = null;
                string downloadFileName = String.Empty;
                if (paths.Length == 1 && ((File.GetAttributes(Request.MapPath(paths[0])) & FileAttributes.Directory) != FileAttributes.Directory))
                {
                    //Single path
                    string path = Request.MapPath(paths[0]);
                    downloadFile = File.ReadAllBytes(path);
                    downloadFileName = new FileInfo(path).Name;
                }
                else
                {
                    //Multiple paths
                    List<FileInfo> fileInfos = new List<FileInfo>();
                    List<DirectoryInfo> emptyDirectoryInfos = new List<DirectoryInfo>();

                    foreach (string relativePath in paths)
                    {
                        string path = Request.MapPath(relativePath);
                        FileAttributes attr = File.GetAttributes(path);
                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            DirectoryInfo di = new DirectoryInfo(path);
                            //All the files recursively within a directory
                            FileInfo[] pathFileInfos = di.GetFiles("*", SearchOption.AllDirectories);
                            if (pathFileInfos.Length > 0)
                            {
                                fileInfos.AddRange(pathFileInfos);
                            }
                            else
                            {
                                emptyDirectoryInfos.Add(di);
                            }
                            //All the folders recursively within a directory
                            DirectoryInfo[] pathDirectoryInfos = di.GetDirectories("*", SearchOption.AllDirectories);
                            foreach (DirectoryInfo pathDirectoryInfo in pathDirectoryInfos)
                            {
                                if (pathDirectoryInfo.GetFiles().Length == 0)
                                {
                                    emptyDirectoryInfos.Add(pathDirectoryInfo);
                                }
                            }
                        }
                        else
                        {
                            fileInfos.Add(new FileInfo(path));
                        }
                    }

                    //Needed for constructing the directory hierarchy by the DotNetZip requirements
                    string currentFolder = Request.MapPath(RadFileExplorerAlbum.CurrentFolder);
                    string zipFileName = Path.Combine(Path.GetTempPath(), String.Format("{0}.zip", new Guid()));

                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileName))
                    {
                        foreach (FileInfo fileInfo in fileInfos)
                        {
                            zip.AddFile(fileInfo.FullName, !fileInfo.Directory.FullName.Equals(currentFolder, StringComparison.InvariantCultureIgnoreCase) ? fileInfo.Directory.FullName.Substring(currentFolder.Length + 1) : String.Empty);
                        }
                        foreach (DirectoryInfo directoryInfo in emptyDirectoryInfos)
                        {
                            zip.AddDirectoryByName(
            directoryInfo.FullName.Substring(currentFolder.Length + 1));
                        }

                        zip.TempFileFolder = Path.GetTempPath();
                        zip.Save();
                    }

                    downloadFile = File.ReadAllBytes(zipFileName);
                    File.Delete(zipFileName);
                    downloadFileName = "Combined.zip";
                }

                Response.Clear();
                Response.AppendHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", downloadFileName));
                Response.ContentType = String.Format("application/{0}", downloadFileName);
                Response.BinaryWrite(downloadFile);
                Response.End();
            }
        }
Exemplo n.º 24
0
		/// <summary>
		/// Zips a set of files (that must be rooted at the given RootDir) to a set of zip files in the given OutputDir. The files will be prefixed with the given basename.
		/// </summary>
		/// <param name="InputFiles">Fully qualified list of files to zip (must be rooted at RootDir).</param>
		/// <param name="RootDir">Root Directory where all files will be extracted.</param>
		/// <param name="OutputDir">Location to place the set of zip files created.</param>
		/// <param name="StagingDir">Location to create zip files before copying them to the OutputDir. If the OutputDir is on a remote file share, staging may be more efficient. Use null to avoid using a staging copy.</param>
		/// <param name="ZipBaseName">The basename of the set of zip files.</param>
		/// <returns>Some metrics about the zip process.</returns>
		/// <remarks>
		/// This function tries to zip the files in parallel as fast as it can. It makes no guarantees about how many zip files will be created or which files will be in which zip,
		/// but it does try to reasonably balance the file sizes.
		/// </remarks>
		private static FileInfo[] ParallelZipFiles(FileInfo[] InputFiles, DirectoryReference RootDir, DirectoryReference OutputDir, DirectoryReference StagingDir, string ZipBaseName)
		{
			// First get the sizes of all the files. We won't parallelize if there isn't enough data to keep the number of zips down.
			var FilesInfo = InputFiles
				.Select(InputFile => new { File = new FileReference(InputFile), FileSize = InputFile.Length })
				.ToList();

			// Profiling results show that we can zip 100MB quite fast and it is not worth parallelizing that case and creating a bunch of zips that are relatively small.
			const long MinFileSizeToZipInParallel = 1024 * 1024 * 100L;
			var bZipInParallel = FilesInfo.Sum(FileInfo => FileInfo.FileSize) >= MinFileSizeToZipInParallel;

			// order the files in descending order so our threads pick up the biggest ones first.
			// We want to end with the smaller files to more effectively fill in the gaps
			var FilesToZip = new ConcurrentQueue<FileReference>(FilesInfo.OrderByDescending(FileInfo => FileInfo.FileSize).Select(FileInfo => FileInfo.File));

			// We deliberately avoid Parallel.ForEach here because profiles have shown that dynamic partitioning creates
			// too many zip files, and they can be of too varying size, creating uneven work when unzipping later,
			// as ZipFile cannot unzip files in parallel from a single archive.
			// We can safely assume the build system will not be doing more important things at the same time, so we simply use all our logical cores,
			// which has shown to be optimal via profiling, and limits the number of resulting zip files to the number of logical cores.
			// 
			// Sadly, mono implementation of System.IO.Compression is really poor (as of 2015/Aug), causing OOM when parallel zipping a large set of files.
			// However, Ionic is MUCH slower than .NET's native implementation (2x+ slower in our build farm), so we stick to the faster solution on PC.
			// The code duplication in the threadprocs is unfortunate here, and hopefully we can settle on .NET's implementation on both platforms eventually.
			List<Thread> ZipThreads;

			ConcurrentBag<FileInfo> ZipFiles = new ConcurrentBag<FileInfo>();

			DirectoryReference ZipDir = StagingDir ?? OutputDir;
			if (Utils.IsRunningOnMono)
			{
				ZipThreads = (
					from CoreNum in Enumerable.Range(0, bZipInParallel ? Environment.ProcessorCount : 1)
					let ZipFileName = FileReference.Combine(ZipDir, string.Format("{0}{1}.zip", ZipBaseName, bZipInParallel ? "-" + CoreNum.ToString("00") : ""))
					select new Thread(() =>
					{
						// don't create the zip unless we have at least one file to add
						FileReference File;
						if (FilesToZip.TryDequeue(out File))
						{
							// Create one zip per thread using the given basename
							using (var ZipArchive = new Ionic.Zip.ZipFile(ZipFileName.FullName) { CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed })
							{

								// pull from the queue until we are out of files.
								do
								{
									// use fastest compression. In our best case we are CPU bound, so this is a good tradeoff,
									// cutting overall time by 2/3 while only modestly increasing the compression ratio (22.7% -> 23.8% for RootEditor PDBs).
									// This is in cases of a super hot cache, so the operation was largely CPU bound.
									ZipArchive.AddFile(File.FullName, CommandUtils.ConvertSeparators(PathSeparator.Slash, File.Directory.MakeRelativeTo(RootDir)));
								} while (FilesToZip.TryDequeue(out File));
								ZipArchive.Save();
							}
							// if we are using a staging dir, copy to the final location and delete the staged copy.
							FileInfo ZipFile = new FileInfo(ZipFileName.FullName);
							if (StagingDir != null)
							{
								FileInfo NewZipFile = ZipFile.CopyTo(CommandUtils.MakeRerootedFilePath(ZipFile.FullName, StagingDir.FullName, OutputDir.FullName));
								ZipFile.Delete();
								ZipFile = NewZipFile;
							}
							ZipFiles.Add(ZipFile);
						}
					})).ToList();
			}
			else
			{
				ZipThreads = (
					from CoreNum in Enumerable.Range(0, bZipInParallel ? Environment.ProcessorCount : 1)
					let ZipFileName = FileReference.Combine(ZipDir, string.Format("{0}{1}.zip", ZipBaseName, bZipInParallel ? "-" + CoreNum.ToString("00") : ""))
					select new Thread(() =>
					{
						// don't create the zip unless we have at least one file to add
						FileReference File;
						if (FilesToZip.TryDequeue(out File))
						{
							// Create one zip per thread using the given basename
							using (var ZipArchive = System.IO.Compression.ZipFile.Open(ZipFileName.FullName, System.IO.Compression.ZipArchiveMode.Create))
							{

								// pull from the queue until we are out of files.
								do
								{
									// use fastest compression. In our best case we are CPU bound, so this is a good tradeoff,
									// cutting overall time by 2/3 while only modestly increasing the compression ratio (22.7% -> 23.8% for RootEditor PDBs).
									// This is in cases of a super hot cache, so the operation was largely CPU bound.
									// Also, sadly, mono appears to have a bug where nothing you can do will properly set the LastWriteTime on the created entry,
									// so we have to ignore timestamps on files extracted from a zip, since it may have been created on a Mac.
									ZipFileExtensions.CreateEntryFromFile(ZipArchive, File.FullName, CommandUtils.ConvertSeparators(PathSeparator.Slash, File.MakeRelativeTo(RootDir)), System.IO.Compression.CompressionLevel.Fastest);
								} while (FilesToZip.TryDequeue(out File));
							}
							// if we are using a staging dir, copy to the final location and delete the staged copy.
							FileInfo ZipFile = new FileInfo(ZipFileName.FullName);
							if (StagingDir != null)
							{
								FileInfo NewZipFile = ZipFile.CopyTo(CommandUtils.MakeRerootedFilePath(ZipFile.FullName, StagingDir.FullName, OutputDir.FullName));
								ZipFile.Delete();
								ZipFile = NewZipFile;
							}
							ZipFiles.Add(ZipFile);
						}
					})).ToList();
			}
			ZipThreads.ForEach(thread => thread.Start());
			ZipThreads.ForEach(thread => thread.Join());
			
			return ZipFiles.OrderBy(x => x.Name).ToArray();
		}
        public ActionResult export_templates_to_zip(Int32 id = 0, string returnUrl = "")
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get all the custom theme templates
            List<CustomThemeTemplate> templates = CustomThemeTemplate.GetAllPostsByCustomThemeId(id, "user_file_name", "ASC");

            // Create the zip file variable
            Ionic.Zip.ZipFile zipFile = null;

            // Create a output stream
            MemoryStream outputStream = new MemoryStream();

            // Create the file stream result
            FileStreamResult fileStreamResult = null;

            try
            {
                // Create a new zip file
                zipFile = new Ionic.Zip.ZipFile(System.Text.Encoding.UTF8);

                // Loop all the templates
                for (int i = 0; i < templates.Count; i++)
                {
                    // Get the stream
                    byte[] streamData = System.Text.Encoding.UTF8.GetBytes(templates[i].user_file_content);

                    // Add the zip file
                    zipFile.AddEntry(templates[i].user_file_name, streamData);
                }

                // Save the zip file
                zipFile.Save(outputStream);

                // Go to the beginning of the output stream
                outputStream.Seek(0, SeekOrigin.Begin);

                // Create the file stream result
                fileStreamResult = new FileStreamResult(outputStream, "application/zip") { FileDownloadName = "custom-templates.zip" };

            }
            catch (Exception exception)
            {
                string exceptionMessage = "";
                exceptionMessage = exception.Message;
            }
            finally
            {
                // Close streams
                if (zipFile != null)
                {
                    zipFile.Dispose();
                }
            }

            // Return the zip file
            return fileStreamResult;

        } // End of the export_templates_to_zip method
Exemplo n.º 26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // -----------------------------------------------------------------------------------
            string strIdentificadores = ALCSA.FWK.Web.Sitio.ExtraerValorQueryString(Request, "ids");
            string strRutaIndicada    = ALCSA.FWK.Web.Sitio.ExtraerValorQueryString(Request, "ruta");
            string strNombreIdDoc     = ALCSA.FWK.Web.Sitio.ExtraerValorQueryString(Request, "nom_id_doc");
            string strTipoIdDoc       = ALCSA.FWK.Web.Sitio.ExtraerValorQueryString(Request, "tipo_id_doc");

            // -----------------------------------------------------------------------------------
            string[] arrFormatosIdentificadores = ALCSA.FWK.Web.Sitio.ExtraerValorQueryString(Request, "for_dat").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            int      intIdDocumento             = ALCSA.FWK.Web.Sitio.ExtraerValorQueryStringComoEntero(Request, "id_doc");
            int      intIdDocumentoParametro    = 0;

            // -----------------------------------------------------------------------------------
            if (string.IsNullOrEmpty(strRutaIndicada))
            {
                return;
            }
            // -----------------------------------------------------------------------------------
            string strRutaTemporal = Server.MapPath("Temporal");

            if (!strRutaTemporal.EndsWith("\\"))
            {
                strRutaTemporal = string.Format("{0}\\", strRutaTemporal);
            }
            strRutaTemporal = string.Format("{0}{1:ddMMyyyyhhmmssfffff}_{2}\\", strRutaTemporal, DateTime.Now, new Random().Next(10000, 999999));
            // -----------------------------------------------------------------------------------
            if (!System.IO.Directory.Exists(strRutaTemporal))
            {
                System.IO.Directory.CreateDirectory(strRutaTemporal);
            }
            // -----------------------------------------------------------------------------------
            if (string.IsNullOrWhiteSpace(strTipoIdDoc))
            {
                strTipoIdDoc = CodigoBarra.INICIAL_CODIGO_DOCUMENTO_FISICO;
            }

            if (intIdDocumento.Equals(0))
            {
                intIdDocumento = ALCSA.FWK.Web.Sitio.ExtraerValorQueryStringComoEntero(Request, "id");
            }
            // -----------------------------------------------------------------------------------
            // Multiples archivos
            if (!string.IsNullOrWhiteSpace(strIdentificadores))
            {
                string[] arrIdentificadores = strIdentificadores.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries), arrSubIdentificadores = null;

                foreach (string strIdentificador in arrIdentificadores)
                {
                    arrSubIdentificadores   = strIdentificador.Split(new char[] { ',' });
                    intIdDocumentoParametro = intIdDocumento;

                    int           intIndiceParametro = 0;
                    string        strNombreParametro = string.Empty;
                    StringBuilder strbParametros     = new StringBuilder();

                    while (intIndiceParametro < arrSubIdentificadores.Length)
                    {
                        strNombreParametro = arrFormatosIdentificadores.Length > intIndiceParametro ? arrFormatosIdentificadores[intIndiceParametro] : string.Format("par_{0}", intIndiceParametro);

                        strbParametros.AppendFormat("&{0}={1}", strNombreParametro, arrSubIdentificadores[intIndiceParametro]);

                        if (intIdDocumentoParametro == 0 && strNombreParametro == strNombreIdDoc)
                        {
                            intIdDocumentoParametro = ALCSA.FWK.Texto.ConvertirTextoEnEntero(arrSubIdentificadores[intIndiceParametro]);
                        }

                        intIndiceParametro++;
                    }

                    GenerarDocumento(strRutaIndicada, strbParametros.ToString(), strRutaTemporal, intIdDocumentoParametro, strTipoIdDoc);
                }
            }
            else
            {
                StringBuilder strbTexto = new StringBuilder();
                foreach (string strLlave in Request.QueryString.AllKeys)
                {
                    if (strLlave != "ids" && strLlave != "ruta" && strLlave != "for_dat")
                    {
                        intIdDocumentoParametro = intIdDocumento;
                        strbTexto.AppendFormat("&{0}={1}", strLlave, Request.QueryString[strLlave]);

                        if (intIdDocumentoParametro == 0 && strLlave == strNombreIdDoc)
                        {
                            intIdDocumentoParametro = ALCSA.FWK.Texto.ConvertirTextoEnEntero(Request.QueryString[strLlave]);
                        }
                    }
                }

                GenerarDocumento(strRutaIndicada, strbTexto.ToString(), strRutaTemporal, intIdDocumentoParametro, strTipoIdDoc);
            }
            // -----------------------------------------------------------------------------------
            string[] arrArchivos = System.IO.Directory.GetFiles(strRutaTemporal);
            if (arrArchivos.Length.Equals(1))
            {
                DescargarArchivo(System.IO.File.ReadAllBytes(arrArchivos[0]), "archivo_doc.docx", "application/msword", System.Text.Encoding.ASCII);
                return;
            }
            // -----------------------------------------------------------------------------------
            // COMPRIMIR TODOS LOS ARCHIVOS
            string strNombreZip = string.Format("{0}Documentos_{1}.zip", strRutaTemporal, new Random().Next(10000, 999999));

            using (Ionic.Zip.ZipFile objArchivoZip = new Ionic.Zip.ZipFile())
            {
                foreach (string strArchivo in arrArchivos)
                {
                    objArchivoZip.AddFile(strArchivo, string.Empty);
                }
                objArchivoZip.Save(strNombreZip);
            }

            // DESCARGAR
            DescargarArchivo(System.IO.File.ReadAllBytes(strNombreZip), "Documentos.zip", "application/msword", System.Text.Encoding.ASCII);
            // -----------------------------------------------------------------------------------
        }
        public ActionResult export_images_to_zip(string returnUrl = "")
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Create the zip file variable
            Ionic.Zip.ZipFile zipFile = null;

            // Create the directory string
            string imagesDirectory = "/Content/images/user_design/";

            // Create a output stream
            MemoryStream outputStream = new MemoryStream();

            // Create the file stream result
            FileStreamResult fileStreamResult = null;

            try
            {
                // Create a new zip file
                zipFile = new Ionic.Zip.ZipFile(System.Text.Encoding.UTF8);

                // Get all the file names
                string[] imageUrlList = System.IO.Directory.GetFiles(Server.MapPath(imagesDirectory));

                // Add all the images to the zip file
                for (int i = 0; i < imageUrlList.Length; i++)
                {
                    zipFile.AddFile(imageUrlList[i], "");
                }

                // Save the zip file
                zipFile.Save(outputStream);

                // Go to the beginning of the output stream
                outputStream.Seek(0, SeekOrigin.Begin);

                // Create the file stream result
                fileStreamResult = new FileStreamResult(outputStream, "application/zip") { FileDownloadName = "user-images.zip" };

            }
            catch (Exception exception)
            {
                string exceptionMessage = "";
                exceptionMessage = exception.Message;
            }
            finally
            {
                // Close streams
                if (zipFile != null)
                {
                    zipFile.Dispose();
                }
            }

            // Return the zip file
            return fileStreamResult;

        } // End of the export_images_to_zip method
Exemplo n.º 28
0
        public async Task ProcessBuildAsync(string solutionName, string sourceKey, string sourceBucket, string destinationBucket)
        {
            var tempPath = Path.Combine(Path.GetTempPath(), solutionName.Replace(".", ""));

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

            DeleteDirectoryContents(tempPath);

            using var zipUtil = new ZipUtilities();
            var archive = await zipUtil.GetZipArchiveAsync(sourceBucket, sourceKey);

            foreach (var entry in archive.Entries.Distinct())
            {
                if (entry.Name.Length <= 0)
                {
                    continue;
                }
                if (entry.FullName.ToLower().Contains("/runtimes/"))
                {
                    var runtimesPath = entry.FullName.Split("/runtimes/")[1];
                    var fullPath     = Path.Combine(tempPath, "runtimes", runtimesPath);

                    var directoryName = Path.GetDirectoryName(fullPath);
                    if (!Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    entry.ExtractToFile(fullPath);
                }
                else
                {
                    entry.ExtractToFile(Path.Combine(tempPath, entry.Name));
                }
            }

            var version = await zipUtil.GetVersionFromBuildInfoAsync(sourceBucket, sourceKey);

            foreach (var template in Directory.EnumerateFiles(tempPath, "*.template"))
            {
                InjectVersionIntoTemplate(template, version);
            }

            var zipFileName = $"{solutionName}.{version}.zip";
            var zipFullname = Path.Combine(tempPath, zipFileName);

            using Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
            zip.AddDirectory(tempPath);
            zip.Save(zipFullname);

            using var s3Client = new AmazonS3Client(RegionEndpoint.USEast1);
            await s3Client.PutObjectAsync(new PutObjectRequest
            {
                BucketName = destinationBucket,
                Key        = $"{solutionName}/{version}/{zipFileName}",
                FilePath   = zipFullname
            });
        }
Exemplo n.º 29
0
        /// <summary>
        /// Removes Rich signatures from all executable files inside XAP
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        static bool RemoveSignaturesFromXap(string path)
        {
            /* cleaning up Temp folder */
            string tempFolder = Path.Combine(Path.GetTempPath(), "RemoveRS");
            if (!Directory.Exists(tempFolder))
                Directory.CreateDirectory(tempFolder);
            string xapExtractionPath = Path.Combine(tempFolder, path.GetHashCode().ToString());
            if (Directory.Exists(xapExtractionPath))
                Directory.Delete(xapExtractionPath, true);
            Directory.CreateDirectory(xapExtractionPath);

            /* actual removing */
            var zip = new Ionic.Zip.ZipFile(path);
            if (zip["/WMAppPRHeader.xml"] == null)
            {
                bool anythingChanged = false;
                bool resign = (zip["/AccountManager.dll"] != null) && (zip["/ComXapHandlerACM.dll"] != null);
                zip.ExtractAll(xapExtractionPath);
                var files = Directory.GetFiles(xapExtractionPath, "*.dll", SearchOption.AllDirectories);
                foreach (var file in files)
                {
                    if (file.ToLower().EndsWith(".dll"))
                    {
                        anythingChanged |= RemoveSignature(file);
                        if (resign)
                            Sign(file);
                    }

                }
                files = Directory.GetFiles(xapExtractionPath, "*.exe", SearchOption.AllDirectories);
                foreach (var file in files)
                {
                    if (file.ToLower().EndsWith(".exe"))
                    {
                        anythingChanged |= RemoveSignature(file);
                        if (resign)
                            Sign(file);
                    }
                }
                zip.Dispose();
                if (anythingChanged)
                {
                    zip = new Ionic.Zip.ZipFile();
                    zip.AddDirectory(xapExtractionPath);
                    zip.Save(path);
                }
                return true;
            }
            else
            {
                zip.Dispose();
                zip = null;
            }
            return false;
        }
Exemplo n.º 30
0
        public override bool Execute()
        {
            Log.LogMessage( MessageImportance.Low, "Packing M-Files Application." );

            // Gather all the JavaScript files
            var scripts = new List<string>();
            scripts.AddRange( SourceFiles );

            // Gather all reference files.
            // For now we do not support project or zip references so this step doesn't require anything special.
            var referenceFiles = References ?? new string[] { };

            Log.LogMessage( MessageImportance.Low, "Resolving references." );

            // Make sure the referenced files exist.
            var missingFiles = referenceFiles.Where( r => !File.Exists( r ) ).ToList();
            foreach( var missingFile in missingFiles )
                Log.LogError( "Referenced file '{0}' does not exist.", missingFile );
            if( missingFiles.Count > 0 )
                return false;

            // Resolve references by filename.
            var referencesByName = referenceFiles.GroupBy( f => Path.GetFileName( f ) );

            // Resolve the final filenames.
            var finalReferences = new Dictionary<string, string>();
            foreach( var nameGroup in referencesByName )
            {
                var fileName = nameGroup.Key;
                var files = nameGroup.ToList();

                if( fileName.ToLower() == "appdef.xml" ) continue;
                if( fileName.ToLower() == "_package.js" ) continue;

                for( int i = 0; i < files.Count; i++ )
                {
                    // If there are more than one file with the same name, use a $i as postfix for it.
                    string postfix = "";
                    if( files.Count > 1 )
                        postfix = "$" + i;

                    string finalFileName =
                        Path.GetFileNameWithoutExtension( fileName ) +
                        postfix +
                        Path.GetExtension( fileName );

                    finalReferences[ files[ i ] ] = finalFileName;
                }

            }

            // Generate the package definition.
            var appdef = new ApplicationDefinition();
            appdef.Guid = this.Guid.Replace("{", "").Replace("}", "");
            appdef.Name = this.Name;
            var appfiles = new List<ApplicationFile>();
            appfiles.Add( new ApplicationFile { Name = "_package.js" } );
            foreach( var environment in new[] { "vaultcore", "vaultui", "shellui" } )
            {
                var module = new ApplicationModule { Environment = environment };
                appdef.Modules.Add( module );
                module.Files = appfiles;
            }

            // Build the zip file.

            // Add the local scripts.
            if( File.Exists( OutputFile ) )
                File.Delete( OutputFile );
            var outputZip = new Ionic.Zip.ZipFile( OutputFile );
            foreach( var file in SourceFiles )
            {
                outputZip.AddFile( file );
                appfiles.Add( new ApplicationFile { Name = file } );
            }

            // Add the referenced scripts.
            foreach( var reference in finalReferences )
            {
                var file = reference.Key;
                if( Path.GetExtension( file ) == ".zip" )
                {
                    var inputZip = new Ionic.Zip.ZipFile( file );
                    foreach( var e in inputZip.Entries )
                    {
                        var filename = Path.GetFileName( e.FileName ).ToLower();
                        if( filename == "appdef.xml" ) continue;
                        if( filename == "_package.js" ) continue;

                        var tempStream = new MemoryStream();
                        e.Extract( tempStream );
                        tempStream.Position = 0;
                        var projectName = Path.GetFileNameWithoutExtension( reference.Value );
                        var entryPath = "_references/" + projectName + "/" + e.FileName;
                        outputZip.AddEntry( entryPath, tempStream );
                        appfiles.Add( new ApplicationFile { Name = entryPath } );
                    }
                }
                else
                {
                    var entry = outputZip.AddFile( file );
                    entry.FileName = "_references/" + reference.Value;
                    appfiles.Add( new ApplicationFile { Name = entry.FileName } );
                }
            }

            var stream = new MemoryStream();
            var serializer = new XmlSerializer( typeof( ApplicationDefinition ) );
            serializer.Serialize( stream, appdef );
            stream.Flush();
            stream.Position = 0;
            outputZip.AddEntry( "appdef.xml", stream );

            var packageStream = this.GetType().Assembly.GetManifestResourceStream( "MFiles.SDK.Tasks.Scripts.package.js" );
            outputZip.AddEntry( "_package.js", packageStream );

            outputZip.Save();

            LogArray( "Scripts", outputZip.Entries.Select( e => e.FileName ) );

            return true;
        }
Exemplo n.º 31
0
        public static JsonData Compress
            (string preDefinedRootRelativePath,
            ViewModels.PathAndDirectoriesAndFilesAndFileNameViewModel viewModel)
        {
            JsonData jsonData = null;

            // **************************************************
            if (string.IsNullOrWhiteSpace(viewModel.FileName))
            {
                string errorMessage =
                    "You did not specify file name!";

                jsonData =
                    new JsonData
                {
                    DisplayMessage = true,
                    MessageText    = errorMessage,
                    State          = ViewModels.JsonResultStates.Error,
                };

                return(jsonData);
            }

            viewModel.FileName = viewModel.FileName.Trim();
            // **************************************************

            viewModel.Path =
                FixPath(viewModel.Path);

            string strPreDefinedRootRelativePath =
                FixPreDefinedRootRelativePath(preDefinedRootRelativePath);

            string strRootRelativePath =
                string.Format("{0}{1}",
                              strPreDefinedRootRelativePath, viewModel.Path);

            string strPath =
                System.Web.HttpContext.Current.Server.MapPath(strRootRelativePath);

            string strRootRelativeCompressPath =
                string.Format("{0}{1}",
                              strRootRelativePath, viewModel.FileName);

            string strCompressPathName =
                System.Web.HttpContext.Current.Server.MapPath(strRootRelativeCompressPath);

            if (System.IO.File.Exists(strCompressPathName))
            {
                string strErrorMessage =
                    "There is a file with this name!";

                jsonData =
                    new JsonData()
                {
                    DisplayMessage = true,
                    MessageText    = strErrorMessage,
                    State          = ViewModels.JsonResultStates.Error,
                };

                return(jsonData);
            }

            if (System.IO.Directory.Exists(strCompressPathName))
            {
                string strErrorMessage =
                    "There is a directory with this name!";

                jsonData =
                    new JsonData()
                {
                    DisplayMessage = true,
                    MessageText    = strErrorMessage,
                    State          = ViewModels.JsonResultStates.Error,
                };

                return(jsonData);
            }

            ViewModels.CreatedFileAndDirectoriesAndFilesViewModel
                returnViewModel = new ViewModels.CreatedFileAndDirectoriesAndFilesViewModel();

            Ionic.Zip.ZipFile zipFile = null;

            try
            {
                zipFile =
                    new Ionic.Zip.ZipFile(strCompressPathName);

                InitializeZipFile(zipFile);

                foreach (ViewModels.FileViewModel currentFileViewModel in viewModel.Files)
                {
                    string strCurrentPathName =
                        string.Format("{0}\\{1}",
                                      strPath, currentFileViewModel.Name);

                    if (System.IO.File.Exists(strCurrentPathName))
                    {
                        try
                        {
                            zipFile.AddFile
                                (fileName: strCurrentPathName,
                                directoryPathInArchive: string.Empty);

                            zipFile.Save();
                        }
                        catch (System.Exception ex)
                        {
                            System.IO.FileInfo oFileInfoThatHasError =
                                new System.IO.FileInfo(strCurrentPathName);

                            ViewModels.FileViewModel fileThatHasError =
                                new ViewModels.FileViewModel(oFileInfoThatHasError)
                            {
                                Message = ex.Message
                            };

                            returnViewModel.Files.Add(fileThatHasError);
                        }
                    }
                }

                foreach (ViewModels.DirectoryViewModel currentirectoryViewModel in viewModel.Directories)
                {
                    string strCurrentPath =
                        string.Format("{0}\\{1}",
                                      strPath, currentirectoryViewModel.Name);

                    if (System.IO.Directory.Exists(strCurrentPath))
                    {
                        try
                        {
                            zipFile.AddDirectory
                                (directoryName: strCurrentPath,
                                directoryPathInArchive: currentirectoryViewModel.Name);

                            zipFile.Save();
                        }
                        catch (System.Exception ex)
                        {
                            System.IO.DirectoryInfo oDirectoryInfoThatHasError =
                                new System.IO.DirectoryInfo(strCurrentPath);

                            ViewModels.DirectoryViewModel oDirectoryThatHasError =
                                new ViewModels.DirectoryViewModel(oDirectoryInfoThatHasError)
                            {
                                Message = ex.Message
                            };

                            returnViewModel.Directories.Add(oDirectoryThatHasError);
                        }
                    }
                }

                System.IO.FileInfo oFileInfo =
                    new System.IO.FileInfo(strCompressPathName);

                ViewModels.FileViewModel oFile =
                    new ViewModels.FileViewModel(oFileInfo);

                returnViewModel.CreatedFile = oFile;

                string strInformationMessage =
                    string.Format("The compressed file [{0}] created successfully.",
                                  viewModel.FileName);

                jsonData =
                    new JsonData
                {
                    Data        = returnViewModel,
                    MessageText = strInformationMessage,
                    State       = ViewModels.JsonResultStates.Success,
                };

                return(jsonData);
            }
            catch
            {
                string strErrorMessage =
                    "Unexpected Error on Creating Compressed File!";

                jsonData =
                    new JsonData
                {
                    MessageText = strErrorMessage,
                    State       = ViewModels.JsonResultStates.Error,
                };

                return(jsonData);
            }
            finally
            {
                if (zipFile != null)
                {
                    zipFile.Dispose();
                    zipFile = null;
                }
            }
        }
Exemplo n.º 32
0
        protected void ButtonDownload_Click(object sender, EventArgs e)
        {
            string[] paths = HiddenFieldDownload.Value.Split('|');
            if (paths.Length > 0 && !String.IsNullOrEmpty(paths[0]))
            {
                byte[] downloadFile     = null;
                string downloadFileName = String.Empty;
                if (paths.Length == 1 && ((File.GetAttributes(Request.MapPath(paths[0])) & FileAttributes.Directory) != FileAttributes.Directory))
                {
                    //Single path
                    string path = Request.MapPath(paths[0]);
                    downloadFile     = File.ReadAllBytes(path);
                    downloadFileName = new FileInfo(path).Name;
                }
                else
                {
                    //Multiple paths
                    List <FileInfo>      fileInfos           = new List <FileInfo>();
                    List <DirectoryInfo> emptyDirectoryInfos = new List <DirectoryInfo>();

                    foreach (string relativePath in paths)
                    {
                        string         path = Request.MapPath(relativePath);
                        FileAttributes attr = File.GetAttributes(path);
                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            DirectoryInfo di = new DirectoryInfo(path);
                            //All the files recursively within a directory
                            FileInfo[] pathFileInfos = di.GetFiles("*", SearchOption.AllDirectories);
                            if (pathFileInfos.Length > 0)
                            {
                                fileInfos.AddRange(pathFileInfos);
                            }
                            else
                            {
                                emptyDirectoryInfos.Add(di);
                            }
                            //All the folders recursively within a directory
                            DirectoryInfo[] pathDirectoryInfos = di.GetDirectories("*", SearchOption.AllDirectories);
                            foreach (DirectoryInfo pathDirectoryInfo in pathDirectoryInfos)
                            {
                                if (pathDirectoryInfo.GetFiles().Length == 0)
                                {
                                    emptyDirectoryInfos.Add(pathDirectoryInfo);
                                }
                            }
                        }
                        else
                        {
                            fileInfos.Add(new FileInfo(path));
                        }
                    }

                    //Needed for constructing the directory hierarchy by the DotNetZip requirements
                    string currentFolder = Request.MapPath(RadFileExplorerAlbum.CurrentFolder);
                    string zipFileName   = Path.Combine(Path.GetTempPath(), String.Format("{0}.zip", new Guid()));

                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileName))
                    {
                        foreach (FileInfo fileInfo in fileInfos)
                        {
                            zip.AddFile(fileInfo.FullName, !fileInfo.Directory.FullName.Equals(currentFolder, StringComparison.InvariantCultureIgnoreCase) ? fileInfo.Directory.FullName.Substring(currentFolder.Length + 1) : String.Empty);
                        }
                        foreach (DirectoryInfo directoryInfo in emptyDirectoryInfos)
                        {
                            zip.AddDirectoryByName(
                                directoryInfo.FullName.Substring(currentFolder.Length + 1));
                        }

                        zip.TempFileFolder = Path.GetTempPath();
                        zip.Save();
                    }

                    downloadFile = File.ReadAllBytes(zipFileName);
                    File.Delete(zipFileName);
                    downloadFileName = "Combined.zip";
                }

                Response.Clear();
                Response.AppendHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", downloadFileName));
                Response.ContentType = String.Format("application/{0}", downloadFileName);
                Response.BinaryWrite(downloadFile);
                Response.End();
            }
        }
Exemplo n.º 33
0
 private void saveGame()
 {
     if (string.IsNullOrEmpty(_appSettings.SaveCatalog) || string.IsNullOrEmpty(_appSettings.GameCatalog))
         return;
     var dt = DateTime.MinValue;
     var path = _appSettings.GameCatalog;
     using (var zipfile = new Ionic.Zip.ZipFile())
     {
         RecursiveArchivate(path, zipfile, "", ref dt);
         if (dt <= _lastArchiveTime) return;
         var name = Path.GetFileNameWithoutExtension(_appSettings.GameCatalog);
         var filename = string.Format("{0}\\savegame_{1}_{2}.zip", _appSettings.SaveCatalog, dt.ToString("yyMMdd-HHmmss"), name);
         zipfile.Save(filename);
         File.SetLastWriteTime(filename, dt);
     }
     updateList();
     updateUI();
 }
        } //  ZipFileManager()

        public bool ZipDirectory(string SourceDirectory, string ZipFilePath, bool OverWrite = false)
        {
            try
            {
                //  Make sure the specified Source Directory Exists.
                if (!System.IO.Directory.Exists(SourceDirectory))
                {
                    //  Let the user know that the directory does not exist.
                    if (ErrorMessage != null)
                    {
                        ErrorMessage("The specified source directory - " + SourceDirectory + " - does not exist.  Aborting the MaintTools.ZipFileManager.ZipDirectory() Method!");
                    }

                    //  Return FALSE to the calling method to indicate that this method failed.
                    return(false);
                }


                //  Make sure the specified output Directory Exists.
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(ZipFilePath)))
                {
                    //  Attempt to create the directory.
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(ZipFilePath));
                }


                //  Determine if the specified Output File already exists.
                string outputFilePath = ZipFilePath;
                if (System.IO.File.Exists(ZipFilePath))
                {
                    //  If the user wants the old file overwritten, delete it.
                    if (OverWrite)
                    {
                        System.IO.File.Delete(ZipFilePath);
                    }
                    else
                    {
                        //  Try to find a file name to use.
                        string outputBasePath = outputFilePath.Substring(0, (outputFilePath.Length - 4));
                        string extension      = outputFilePath.Substring((outputFilePath.Length - 4));
                        int    i = 0;
                        outputFilePath = "";
                        while ((i < 100) && (outputFilePath.Length == 0))
                        {
                            if (!System.IO.File.Exists(outputBasePath + "(" + i.ToString() + ")" + extension))
                            {
                                outputFilePath = outputBasePath + "(" + i.ToString() + ")" + extension;
                            }
                            //  Increment the counter.
                            i++;
                        }
                    }
                }


                //  Retrieve the Directory Name to be included in the Zip File.
                string directoryName = SourceDirectory;
                while (directoryName.IndexOf(@"\") != -1)
                {
                    //  Drop the Left Most character from the Directory Name.
                    directoryName = directoryName.Substring(1);
                }


                //  Attempt to zip the files in the directory.
                using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile())
                {
                    zipFile.AddDirectory(SourceDirectory, directoryName);
                    zipFile.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
                    zipFile.Save(ZipFilePath);
                }
            }
            catch (System.Exception caught)
            {
                //  Let the User know that this method failed.
                if (ErrorMessage != null)
                {
                    ErrorMessage("The MaintTools.ZipFileManager.ZipDirectory() Method failed with error message:  " + caught.Message);
                }

                //  Return FALSE to the calling method to indicate that this process failed.
                return(false);
            }

            //  If the process made it to here, it was successful so return TRUE to the calling method.
            return(true);
        }
Exemplo n.º 35
0
 /// <summary>
 /// 将一个压缩文件集合返回压缩后的字节数
 /// </summary>
 /// <param name="filesPath">源文件集合</param>
 /// <returns></returns>
 public static byte[] ZipFilesInfo(IEnumerable<string> filesPath)
 {
     using (var zipFile = new ZipFile())
     {
         foreach (var filePath in filesPath)
         {
             Ionic.Zip.ZipEntry zipEntry = zipFile.AddFile(filePath, @"\");
         }
         zipFile.Comment =
             string.Format("This zip archive was created by the CreateZip example application on machine '{0}'",
                 Dns.GetHostName());
         using (MemoryStream memoryStream = new MemoryStream())
         {
             zipFile.Save(memoryStream);
             return memoryStream.ToArray(); //将流内容写入字节数组
         }
     }
 }
        /// <summary>
        /// Zips a set of files (that must be rooted at the given RootDir) to a set of zip files in the given OutputDir. The files will be prefixed with the given basename.
        /// </summary>
        /// <param name="Files">Fully qualified list of files to zip (must be rooted at RootDir).</param>
        /// <param name="RootDir">Root Directory where all files will be extracted.</param>
        /// <param name="OutputDir">Location to place the set of zip files created.</param>
        /// <param name="StagingDir">Location to create zip files before copying them to the OutputDir. If the OutputDir is on a remote file share, staging may be more efficient. Use null to avoid using a staging copy.</param>
        /// <param name="ZipBaseName">The basename of the set of zip files.</param>
        /// <returns>Some metrics about the zip process.</returns>
        /// <remarks>
        /// This function tries to zip the files in parallel as fast as it can. It makes no guarantees about how many zip files will be created or which files will be in which zip,
        /// but it does try to reasonably balance the file sizes.
        /// </remarks>
        private static FileInfo[] ParallelZipFiles(FileInfo[] InputFiles, DirectoryReference RootDir, DirectoryReference OutputDir, DirectoryReference StagingDir, string ZipBaseName)
        {
            // First get the sizes of all the files. We won't parallelize if there isn't enough data to keep the number of zips down.
            var FilesInfo = InputFiles
                            .Select(InputFile => new { File = new FileReference(InputFile), FileSize = InputFile.Length })
                            .ToList();

            // Profiling results show that we can zip 100MB quite fast and it is not worth parallelizing that case and creating a bunch of zips that are relatively small.
            const long MinFileSizeToZipInParallel = 1024 * 1024 * 100L;
            var        bZipInParallel             = FilesInfo.Sum(FileInfo => FileInfo.FileSize) >= MinFileSizeToZipInParallel;

            // order the files in descending order so our threads pick up the biggest ones first.
            // We want to end with the smaller files to more effectively fill in the gaps
            var FilesToZip = new ConcurrentQueue <FileReference>(FilesInfo.OrderByDescending(FileInfo => FileInfo.FileSize).Select(FileInfo => FileInfo.File));

            // We deliberately avoid Parallel.ForEach here because profiles have shown that dynamic partitioning creates
            // too many zip files, and they can be of too varying size, creating uneven work when unzipping later,
            // as ZipFile cannot unzip files in parallel from a single archive.
            // We can safely assume the build system will not be doing more important things at the same time, so we simply use all our logical cores,
            // which has shown to be optimal via profiling, and limits the number of resulting zip files to the number of logical cores.
            //
            // Sadly, mono implementation of System.IO.Compression is really poor (as of 2015/Aug), causing OOM when parallel zipping a large set of files.
            // However, Ionic is MUCH slower than .NET's native implementation (2x+ slower in our build farm), so we stick to the faster solution on PC.
            // The code duplication in the threadprocs is unfortunate here, and hopefully we can settle on .NET's implementation on both platforms eventually.
            List <Thread> ZipThreads;

            ConcurrentBag <FileInfo> ZipFiles = new ConcurrentBag <FileInfo>();

            DirectoryReference ZipDir = StagingDir ?? OutputDir;

            if (Utils.IsRunningOnMono)
            {
                ZipThreads = (
                    from CoreNum in Enumerable.Range(0, bZipInParallel ? Environment.ProcessorCount : 1)
                    let ZipFileName = FileReference.Combine(ZipDir, string.Format("{0}{1}.zip", ZipBaseName, bZipInParallel ? "-" + CoreNum.ToString("00") : ""))
                                      select new Thread(() =>
                {
                    // don't create the zip unless we have at least one file to add
                    FileReference File;
                    if (FilesToZip.TryDequeue(out File))
                    {
                        // Create one zip per thread using the given basename
                        using (var ZipArchive = new Ionic.Zip.ZipFile(ZipFileName.FullName)
                        {
                            CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed
                        })
                        {
                            // pull from the queue until we are out of files.
                            do
                            {
                                // use fastest compression. In our best case we are CPU bound, so this is a good tradeoff,
                                // cutting overall time by 2/3 while only modestly increasing the compression ratio (22.7% -> 23.8% for RootEditor PDBs).
                                // This is in cases of a super hot cache, so the operation was largely CPU bound.
                                ZipArchive.AddFile(File.FullName, CommandUtils.ConvertSeparators(PathSeparator.Slash, File.Directory.MakeRelativeTo(RootDir)));
                            } while (FilesToZip.TryDequeue(out File));
                            ZipArchive.Save();
                        }
                        // if we are using a staging dir, copy to the final location and delete the staged copy.
                        FileInfo ZipFile = new FileInfo(ZipFileName.FullName);
                        if (StagingDir != null)
                        {
                            FileInfo NewZipFile = ZipFile.CopyTo(CommandUtils.MakeRerootedFilePath(ZipFile.FullName, StagingDir.FullName, OutputDir.FullName));
                            ZipFile.Delete();
                            ZipFile = NewZipFile;
                        }
                        ZipFiles.Add(ZipFile);
                    }
                })).ToList();
            }
            else
            {
                ZipThreads = (
                    from CoreNum in Enumerable.Range(0, bZipInParallel ? Environment.ProcessorCount : 1)
                    let ZipFileName = FileReference.Combine(ZipDir, string.Format("{0}{1}.zip", ZipBaseName, bZipInParallel ? "-" + CoreNum.ToString("00") : ""))
                                      select new Thread(() =>
                {
                    // don't create the zip unless we have at least one file to add
                    FileReference File;
                    if (FilesToZip.TryDequeue(out File))
                    {
                        // Create one zip per thread using the given basename
                        using (var ZipArchive = System.IO.Compression.ZipFile.Open(ZipFileName.FullName, System.IO.Compression.ZipArchiveMode.Create))
                        {
                            // pull from the queue until we are out of files.
                            do
                            {
                                // use fastest compression. In our best case we are CPU bound, so this is a good tradeoff,
                                // cutting overall time by 2/3 while only modestly increasing the compression ratio (22.7% -> 23.8% for RootEditor PDBs).
                                // This is in cases of a super hot cache, so the operation was largely CPU bound.
                                // Also, sadly, mono appears to have a bug where nothing you can do will properly set the LastWriteTime on the created entry,
                                // so we have to ignore timestamps on files extracted from a zip, since it may have been created on a Mac.
                                ZipFileExtensions.CreateEntryFromFile(ZipArchive, File.FullName, CommandUtils.ConvertSeparators(PathSeparator.Slash, File.MakeRelativeTo(RootDir)), System.IO.Compression.CompressionLevel.Fastest);
                            } while (FilesToZip.TryDequeue(out File));
                        }
                        // if we are using a staging dir, copy to the final location and delete the staged copy.
                        FileInfo ZipFile = new FileInfo(ZipFileName.FullName);
                        if (StagingDir != null)
                        {
                            FileInfo NewZipFile = ZipFile.CopyTo(CommandUtils.MakeRerootedFilePath(ZipFile.FullName, StagingDir.FullName, OutputDir.FullName));
                            ZipFile.Delete();
                            ZipFile = NewZipFile;
                        }
                        ZipFiles.Add(ZipFile);
                    }
                })).ToList();
            }
            ZipThreads.ForEach(thread => thread.Start());
            ZipThreads.ForEach(thread => thread.Join());

            return(ZipFiles.OrderBy(x => x.Name).ToArray());
        }
Exemplo n.º 37
-1
        public string Run(List<string> files)
        {
            if (files == null)
                files = new List<string>();

            if (d != null)
            {                
                if (d.inputType ==  Db.actionZipInputType.custom)
                    files.AddRange(d.file);
                               
               
                string folder = d.folderToSave;
                if (folder.EndsWith("\\"))
                    folder = folder.Substring(0, folder.Length - 1);
                string fullZipName = folder + "\\" + d.zipFileName;

                if (System.IO.File.Exists(fullZipName))
                    System.IO.File.Delete(fullZipName);

                Ionic.Zip.ZipFile z = new Ionic.Zip.ZipFile();
                foreach (string f in files)
                {
                    z.AddFile(f);                       
                }
                z.Save(fullZipName);

                return fullZipName;
            }
            return string.Empty;
        }
Exemplo n.º 38
-1
 /// <summary>
 /// 压缩文件夹,文件架下面包含文件夹
 /// </summary>
 /// <param name="filePath">源文件夹路径</param>
 /// <param name="savePath">保存为Zip包的目录</param>
 public static void ZipDirInfo(string filePath, string savePath)
 {
     using (var zip = new ZipFile())
     {
         zip.StatusMessageTextWriter = Console.Out;
         zip.AddDirectory(filePath, @"\");
         zip.Save(savePath);
     }
 }
Exemplo n.º 39
-1
        public void Save(string path, string fileName, string content, string password)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(path))
            {
                zip.Password = password;
                zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;

                if (zip["" + fileName + ""] != null)
                {
                    zip.RemoveEntry(fileName);
                }

                zip.AddEntry(fileName, content, System.Text.Encoding.UTF8);
                zip.Save(path);
            }
        }