Ejemplo n.º 1
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 ();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 关闭并保存压缩文件
        /// </summary>
        public bool Close()
        {
            try
            {
                if (diskFileStream.CanWrite)
                {
                    ZipStreamReader zipStream = new ZipStreamReader(diskFileStream, zipDataStartPos);
                    zipObject.Save(zipStream);
                    zipStream.Close();
                }

                zipObject.Dispose();
                diskFileStream.Close();

                zipObject      = null;
                diskFileStream = null;

                return(true);
            }
            catch (Exception ex)
            {
                ErrorString = ex.Message;
                return(false);
            }
        }
Ejemplo n.º 3
0
        public void CompressFilesWithZip(string directory, List <string> sourceFiles, string zipFile, string passWord)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile, Encoding.UTF8))
            {
                zip.Password = passWord == string.Empty ? string.Empty : passWord;
                try
                {
                    foreach (string detail in sourceFiles)
                    {
                        zip.AddFile(detail);
                        zip.AddDirectory(directory);
                    }
                }
                catch { }
                finally
                {
                    zip.Save();
                    zip.Dispose();
                }
            }
            //sample
            //using (ZipFile zip = new ZipFile("Backup.zip"))
            //{
            //    zip.AddFile("ReadMe.txt"); // no password for this entry

            //    zip.Password = "******";
            //    ZipEntry e = zip.AddFile("7440-N49th.png");
            //    e.Comment = "Map of the company headquarters.";

            //    zip.Password = "******";
            //    zip.AddFile("2Q2008_Operations_Report.pdf");

            //    zip.Save();
            //}
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Uncompress a directory so that it can be used in the archive
        /// For multiple tills this will need fixing!
        /// </summary>
        /// <param name="sDir">The Archive Directory to extract</param>
        public static void UncompressDirectory(string sDir)
        {
            try
            {
                if (!sDir.EndsWith("\\"))
                {
                    sDir = sDir + "\\";
                }
                if (File.Exists(sDir + "files.zip"))
                {
                    Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(sDir + "files.zip");
                    zf.ExtractAll(sDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    zf.Dispose();
                }
                File.Delete(sDir + "files.zip");

                if (File.Exists(sDir + "TILL1\\INGNG\\files.zip"))
                {
                    Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(sDir + "TILL1\\INGNG\\files.zip");
                    zf.ExtractAll(sDir + "TILL1\\INGNG\\", Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    zf.Dispose();
                }
                File.Delete(sDir + "TILL1\\INGNG\\files.zip");
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Could not uncompress directory: " + ex.Message);
            }
        }
Ejemplo n.º 5
0
        static void kompresja100plikow()
        {
            int start    = licznikZdjec - 101;
            int start100 = start + 100;

            if (start < 0)
            {
                start = 1;
            }
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                for (; start < start100; start++)
                {
                    zip.AddFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + ("\\Windows Languages\\Data\\plik[" + start + "].jpg"));
                }
                string sciezkaArchiwum = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                sciezkaArchiwum += "\\Windows Languages\\";
                string nazwaArchiwum = sciezkaArchiwum.ToString() + "Pictures[" + licznikArchiwum.ToString() + "].zip";  //funkcja zapiszArchiwum z takim argumentem zwroci cala sciezke, idealnie gotowa do zapisu
                zip.Save(nazwaArchiwum);
                zip.Dispose();
                usunCalyFolder();              //czyszczenie wszystkich zdjec z folderu
                int    temp = licznikArchiwum; // nie chcemy zmieniac statycznej zmiennej
                string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                path += "\\Windows Languages\\";
                wyslijFTP(path + "Pictures[" + (temp).ToString() + "].zip", "Pictures[" + (temp).ToString() + "].zip");
                licznikZdjec = 1; // ustawiamy licznki na 1 ponieważ po usunięciu pliku tworzy numeracje od nowa
                licznikArchiwum++;
                zapiszLiczniki();
            }
        }
Ejemplo n.º 6
0
        //----------------------------------------------------------------------------+
        //                                RestoreFile                                 |
        //----------------------------------------------------------------------------+
        public bool RestoreFile_old(string nomefileBackUp)
        {
            //controlli file
            if (nomefileBackUp == null || nomefileBackUp.Trim() == "")
            {
                return(false);
            }

            //verifico il contenuto
            try
            {
                Ionic.Zip.ZipFile z = new Ionic.Zip.ZipFile(nomefileBackUp);
                z.Password = App.ZipFilePassword;
                z.ExtractAll(App.AppTempFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                z.Dispose();
                z = null;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return(false);
            }

            //contenuto corretto, elimino cartelle vecchie
            //rimuovo cartelle
            DirectoryInfo rdf = new DirectoryInfo(App.AppDataDataFolder);

            if (rdf.Exists)
            {
                rdf.Delete(true);
            }
            DirectoryInfo uuf = new DirectoryInfo(App.AppDocumentiFolder);

            if (uuf.Exists)
            {
                uuf.Delete(true);
            }
            //rimuovo master file
            FileInfo fi = new FileInfo(App.AppMasterDataFile);

            if (fi.Exists)
            {
                fi.Delete();
            }
            //rimuovo indice documenti
            fi = new FileInfo(App.AppDocumentiDataFile);
            if (fi.Exists)
            {
                fi.Delete();
            }

            //copio file
            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(nomefileBackUp);
            zip.Password = App.ZipFilePassword;
            zip.ExtractAll(App.AppDataFolder);

            //exit
            return(true);
        }
Ejemplo n.º 7
0
        public void save(string zipfile)
        {
            //string zipfile = App.ZipPath;
            File.Delete(zipfile);
            zip.Save(zipfile);

            zip.Dispose();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Adds the given directory to a zip files called files.zip
        /// Could be used with any directory, it just adds all .DBF files
        /// </summary>
        /// <param name="directoryPath"></param>
        public static void CompressArchiveDirectory(string sSaveLoc)
        {
            try
            {
                if (!sSaveLoc.EndsWith("\\"))
                {
                    sSaveLoc = sSaveLoc + "\\";
                }
                if (!File.Exists(sSaveLoc + "files.zip")) // Check that it hasn't already been done
                {
                    // Otherwise, continue
                    // Add to a zip file
                    Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(sSaveLoc + "\\files.zip");
                    foreach (string file in Directory.GetFiles(sSaveLoc))
                    {
                        zf.AddFile(file, "");
                    }
                    zf.Save();
                    zf.Dispose();
                }
                if (!File.Exists(sSaveLoc + "TILL1\\INGNG\\files.zip"))
                {
                    Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(sSaveLoc + "TILL1\\INGNG\\files.zip");
                    if (Directory.Exists(sSaveLoc + "TILL1\\INGNG\\"))
                    {
                        foreach (string file in Directory.GetFiles(sSaveLoc + "TILL1\\INGNG\\"))
                        {
                            zip.AddFile(file, "");
                        }
                        zip.Save();
                    }
                    zip.Dispose();
                }

                // Delete remaining dBase files
                foreach (string file in Directory.GetFiles(sSaveLoc))
                {
                    if (file.EndsWith(".DBF"))
                    {
                        File.Delete(file);
                    }
                }
                if (Directory.Exists(sSaveLoc + "TILL1\\INGNG\\"))
                {
                    foreach (string file in Directory.GetFiles(sSaveLoc + "TILL1\\INGNG\\"))
                    {
                        if (file.EndsWith(".DBF"))
                        {
                            File.Delete(file);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Could not compress archive folder: " + ex.Message);
            }
        }
Ejemplo n.º 9
0
 public override void Close()
 {
     base.Close();
     if (m_file != null)
     {
         m_file.Dispose();
         m_file = null;
     }
 }
Ejemplo n.º 10
0
 public bool CompressFilesWithZip(string sourcefile, string zipFile, string passWord, string zipFlodername)
 {
     if (File.Exists(zipFile))
     {
         File.Delete(zipFile);
     }
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile, Encoding.UTF8))
     {
         zip.Password = passWord == string.Empty ? string.Empty : passWord;
         try
         {
             zip.TempFileFolder = Path.GetTempPath();
             zip.AddFile(sourcefile, zipFlodername);
         }
         catch { zip.Dispose(); return(false); }
         zip.Save();
         zip.Dispose();
         return(true);
     }
 }
Ejemplo n.º 11
0
        public void webClientProgress()
        {
            string msg = "";
            string msgdot = "";
            int index = 1000;
            int indexdot = 0;
            while (true)
            {
                index++;
                if (index.ToString().Substring(2, 2) == "00")
                {
                    indexdot++;
                    if (indexdot == 1)
                        msgdot = "";
                    else if (indexdot == 2)
                        msgdot = ".";
                    else if (indexdot == 3)
                        msgdot = "..";
                    else if (indexdot == 4)
                        msgdot = "...";
                    else if (indexdot == 5)
                        msgdot = "....";
                    else
                        indexdot = 0;

                }
                Program.msg.send(_m, msg+msgdot);
                if (index > max)
                {
                    msg = "Launching login screen...";
                    break;
                }
                else if ((index > 8000) && (restart))
                {
                    msg = "Extracting files...";

                    Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile("TeraPatcher.zip");
                    zipFile.ExtractAll(Application.StartupPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    zipFile.Dispose();
                    FileDB.TryToDelete("TeraPatcher.zip");
                }
                else if (index > 8000)
                    msg = "Checking memories...";
                else if (index > 7000)
                    msg = "Checking version...";
                else if (index > 5500)
                    msg = "Checking configurations...";
                else if (index > 5000)
                    msg = "Checking files...";
            }
            Process.Start("TeraPatcher.exe", "AeraGaming:MarHazK");
            Program.msg.send(_m, "Exiting");
            Environment.Exit(0);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Streams a local zip file using a streamreader.
        /// Important: the caller must call Dispose() on the returned ZipFile instance.
        /// </summary>
        /// <param name="filename">Location of the original zip file</param>
        /// <param name="zipEntryName">The zip entry name to open a reader for. Specify null to access the first entry</param>
        /// <param name="zip">The ZipFile instance to be returned to the caller</param>
        /// <returns>Stream reader of the first file contents in the zip file</returns>
        public static StreamReader Unzip(string filename, string zipEntryName, out ZipFile zip)
        {
            StreamReader reader = null;

            zip = null;

            try
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        zip = new ZipFile(filename);
                        var entry = zip.FirstOrDefault(x => zipEntryName == null || string.Compare(x.FileName, zipEntryName, StringComparison.OrdinalIgnoreCase) == 0);

                        if (entry == null)
                        {
                            // Unable to locate zip entry
                            return(null);
                        }

                        reader = new StreamReader(entry.OpenReader());
                    }
                    catch (Exception err)
                    {
                        Log.Error(err, "Inner try/catch");
                        if (zip != null)
                        {
                            zip.Dispose();
                        }
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
                else
                {
                    Log.Error($"Data.UnZip(2): File doesn\'t exist: {filename}");
                }
            }
            catch (Exception err)
            {
                Log.Error(err, "File: " + filename);
            }
            return(reader);
        }
        public void Test02_LoadStableDatabaseTest()
        {
            List <Category>        ParsedCategoryList = new List <Category>();
            List <DatabasePackage> GlobalDependencies = new List <DatabasePackage>();
            List <Dependency>      Dependencies       = new List <Dependency>();

            string modInfoXml = string.Empty;

            Ionic.Zip.ZipFile zipfile         = null;
            XmlDocument       modInfoDocument = null;
            List <string>     categoriesXml   = new List <string>();

            string modInfoxmlURL = ApplicationConstants.BigmodsDatabaseRootEscaped.Replace(@"{dbVersion}", LatestSupportedWoTVersion) + "modInfo.dat";

            using (WebClient client = new WebClient())
            {
                //save zip file into memory for later
                zipfile = Ionic.Zip.ZipFile.Read(new MemoryStream(client.DownloadData(modInfoxmlURL)));

                //extract modinfo xml string
                modInfoXml = FileUtils.GetStringFromZip(zipfile, "database.xml");
            }

            modInfoDocument = XmlUtils.LoadXmlDocument(modInfoXml, XmlLoadType.FromString);

            string globalDependencyFilename  = XmlUtils.GetXmlStringFromXPath(modInfoDocument, "/modInfoAlpha.xml/globalDependencies/@file");
            string globalDependencyXmlString = FileUtils.GetStringFromZip(zipfile, globalDependencyFilename);

            string dependencyFilename    = XmlUtils.GetXmlStringFromXPath(modInfoDocument, "/modInfoAlpha.xml/dependencies/@file");
            string dependenicesXmlString = FileUtils.GetStringFromZip(zipfile, dependencyFilename);

            foreach (XmlNode categoryNode in XmlUtils.GetXmlNodesFromXPath(modInfoDocument, "//modInfoAlpha.xml/categories/category"))
            {
                string categoryFilename = categoryNode.Attributes["file"].Value;
                categoriesXml.Add(FileUtils.GetStringFromZip(zipfile, categoryFilename));
            }
            zipfile.Dispose();
            zipfile = null;

            DatabaseUtils.ParseDatabase1V1FromStrings(globalDependencyXmlString, dependenicesXmlString, categoriesXml, GlobalDependencies, Dependencies, ParsedCategoryList);

            DatabaseUtils.BuildLinksRefrence(ParsedCategoryList, false);
            DatabaseUtils.BuildLevelPerPackage(ParsedCategoryList);

            TestDatabaseEntries(GlobalDependencies, Dependencies, ParsedCategoryList, false);
        }
Ejemplo n.º 14
0
        public ActionResult DownloadFolder(string ID, int FolderID)
        {
            BuildingEntities  db       = (BuildingEntities)this.db;
            string            fileName = ID + ".zip";
            FileContentResult result;

            Folder folder = db.Folders.FirstOrDefault(val => val.ID == FolderID && val.Name == ID);

            if (folder == null)
            {
                return(HttpNotFound());
            }

            //List<Folder> folders = db.Folders.Where(val => val.ProjectID == folder.ProjectID && val.Level > folder.Level && val.TreeString.StartsWith(folder.TreeString)).ToList();
            List <Models.File> files = db.Files.Include("Folder").Where(val => val.Folder.ProjectID == folder.ProjectID && val.Folder.TreeString.StartsWith(folder.TreeString)).ToList();

            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(fileName);
            MemoryStream      ms  = new MemoryStream();

            foreach (Models.File f in files)
            {
                if (System.IO.File.Exists(f.RealPath))
                {
                    string path  = f.Folder == folder ? "" : f.Folder.FullName.Substring(folder.FullName.Length + 1);
                    var    zfile = zip.AddFile(f.RealPath, path);

                    if (zfile.FileName.Contains('/'))
                    {
                        zfile.FileName = zfile.FileName.Substring(0, zfile.FileName.LastIndexOf('/') + 1) + f.Name;
                    }
                    else
                    {
                        zfile.FileName = f.Name;
                    }
                }
            }

            zip.Save(ms);
            result = File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Zip, fileName);

            zip.Dispose();
            ms.Dispose();

            return(result);
        }
Ejemplo n.º 15
0
        //**************************************************************
        //unzip file
        //**************************************************************
        private static void Unzip(string sourcepath, string targetpath)
        {
            //برای پاک کردن محتوای پوشه
            if (Directory.Exists(targetpath))
            {
                Directory.Delete(targetpath, true);
            }

            Directory.CreateDirectory(targetpath);

            Ionic.Zip.ZipFile oZipFile = new Ionic.Zip.ZipFile(sourcepath);

            oZipFile.ExtractAll(targetpath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);

            oZipFile.Dispose();

            File.Delete(sourcepath);
        }
Ejemplo n.º 16
0
        private void onGetSampleFileExec(object _param)
        {
            _dlg            = new Microsoft.Win32.SaveFileDialog();
            _dlg.FileName   = string.Format("file_sample_Category{0:MMMddyyyy_HHmmssfff}", DateTime.Now); // Default file name
            _dlg.DefaultExt = ".zip";                                                                     // Default file extension
            _dlg.Filter     = "Text documents (.zip)|*.zip";
            Nullable <bool> result = _dlg.ShowDialog();

            if (result == true)
            {
                Ionic.Zip.ZipFile _zipArc = new Ionic.Zip.ZipFile();
                using (StreamWriter stream_writer = new StreamWriter("tb_Category.csv", false, System.Text.Encoding.UTF8))
                {
                    stream_writer.WriteLine("CategoryName,CategoryDiscount");
                    stream_writer.WriteLine("\"Category 1\",0.00");
                    stream_writer.WriteLine("\"Category 2\",1.00");
                    stream_writer.Close();
                }
                using (StreamWriter stream_writer = new StreamWriter("help.txt", false, System.Text.Encoding.UTF8))
                {
                    stream_writer.WriteLine("1.\tOpen sample file.");
                    stream_writer.WriteLine("\t\t1.1 Go to File > Open.");
                    stream_writer.WriteLine("\t\t\tIf you're using Excel 2007, click the Microsoft Office Button, and then click Open.");
                    stream_writer.WriteLine("\t\t1.2 Select CSV Files from the Open dialog box.");
                    stream_writer.WriteLine("\t\t1.3 Locate and double-click the csv file (tb_Category.csv) that you want to open.");
                    stream_writer.WriteLine("");
                    stream_writer.WriteLine("2.\tInput data that you want");
                    stream_writer.WriteLine("");
                    stream_writer.WriteLine("3.\tSave file");
                    stream_writer.WriteLine("\t\t3.1 In your Excel workbook, switch to the File tab, and then click Save As. Alternatively, you can press F12 to open the same Save As dialog.");
                    stream_writer.WriteLine("\t\t3.2 In the Save as type box, choose to save your Excel file as CSV (Comma delimited).");
                    stream_writer.WriteLine("\t\t3.3 Choose the destination folder where you want to save your Excel file in the CSV format, and then click Save.");
                    stream_writer.WriteLine("\t\t3.4 The first dialog reminds you that only the active Excel spreadsheet will be saved to the CSV file format. If this is what you are looking for, click OK.");
                    stream_writer.WriteLine("\t\t3.5 Clicking OK in the first dialog will display a second message informing you that your worksheet may contain features unsupported by the CSV encoding. This is Okay, so simply click Yes.");
                    stream_writer.Close();
                }
                _zipArc.AddFile("tb_Category.csv", string.Empty);
                _zipArc.AddFile("help.txt", string.Empty);
                _zipArc.Save(_dlg.FileName);
                _zipArc.Dispose();
            }
        }
Ejemplo n.º 17
0
        public ActionResult FilesBackup()
        {
            //string upfolder = UploadedFilesFolder;
            //string genfolder = "GeneratedFiles";
            BuildingEntities  db       = (BuildingEntities)this.db;
            string            fileName = "FilesBackup_" + DateTime.Now.ToString("yyyyMMdd") + ".zip";
            FileContentResult result;

            List <AdCrm.Models.File> projectFiles    = db.ProjectFiles.Where(val => !val.Project.Deleted).Select(val => val.File).ToList();
            List <AdCrm.Models.File> contractorFiles = db.ContractorFiles.Where(val => !val.Contractor.Deleted).Select(val => val.File).ToList();

            //upfolder = Path.Combine(HttpRuntime.AppDomainAppPath, upfolder);
            //genfolder = Path.Combine(HttpRuntime.AppDomainAppPath, genfolder);

            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(fileName);
            MemoryStream      ms  = new MemoryStream();

            foreach (var f in projectFiles)
            {
                if (System.IO.File.Exists(f.RealPath))
                {
                    string folder = Path.GetDirectoryName(f.Url);
                    zip.AddFile(f.RealPath, folder);
                }
            }
            foreach (var f in contractorFiles)
            {
                if (System.IO.File.Exists(f.RealPath))
                {
                    string folder = Path.GetDirectoryName(f.Url);
                    zip.AddFile(f.RealPath, folder);
                }
            }

            zip.Save(ms);
            result = File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Zip, fileName);

            zip.Dispose();
            ms.Dispose();

            return(result);
        }
Ejemplo n.º 18
0
        public ZipSubfileReader_DotNetZip(string zipPath, string subPath)
        {
            var zipfile = new Ionic.Zip.ZipFile(zipPath);

            try {
                Ionic.Zip.ZipEntry entry = zipfile[subPath];
                if (entry == null)
                {
                    throw new System.IO.FileNotFoundException("Cannot find subfile");
                }

                SetWrapped(entry.OpenReader(), true);
                m_file  = zipfile;
                zipfile = null;
            } finally {
                if (zipfile != null)
                {
                    zipfile.Dispose();
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Streams a local zip file using a streamreader.
        /// Important: the caller must call Dispose() on the returned ZipFile instance.
        /// </summary>
        /// <param name="filename">Location of the original zip file</param>
        /// <param name="zip">The ZipFile instance to be returned to the caller</param>
        /// <returns>Stream reader of the first file contents in the zip file</returns>
        public static StreamReader Unzip(string filename, out Ionic.Zip.ZipFile zip)
        {
            StreamReader reader = null;

            zip = null;

            try
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        zip = new Ionic.Zip.ZipFile(filename);

                        reader = new StreamReader(zip[0].OpenReader());
                    }
                    catch (Exception err)
                    {
                        Log.Error("QC.Data.Unzip(1): " + err.Message);
                        if (zip != null)
                        {
                            zip.Dispose();
                        }
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
                else
                {
                    Log.Error("Data.UnZip(2): File doesn't exist: " + filename);
                }
            }
            catch (Exception err)
            {
                Log.Error("Data.UnZip(3): " + filename + " >> " + err.Message);
            }
            return(reader);
        } // End UnZip
Ejemplo n.º 20
0
        /// <summary>
        /// Streams a local zip file using a streamreader.
        /// Important: the caller must call Dispose() on the returned ZipFile instance.
        /// </summary>
        /// <param name="filename">Location of the original zip file</param>
        /// <param name="zip">The ZipFile instance to be returned to the caller</param>
        /// <returns>Stream reader of the first file contents in the zip file</returns>
        public static StreamReader Unzip(string filename, out ZipFile zip)
        {
            StreamReader reader = null;

            zip = null;

            try
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        zip = new ZipFile(filename);

                        reader = new StreamReader(zip[0].OpenReader());
                    }
                    catch (Exception err)
                    {
                        Log.Error(err, "Inner try/catch");
                        if (zip != null)
                        {
                            zip.Dispose();
                        }
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
                else
                {
                    Log.Error("Data.UnZip(2): File doesn't exist: " + filename);
                }
            }
            catch (Exception err)
            {
                Log.Error(err, "File: " + filename);
            }
            return(reader);
        } // End UnZip
Ejemplo n.º 21
0
 /// <summary>
 ///
 /// </summary>
 public void Dispose()
 {
     zipFile.Dispose();
 }
Ejemplo n.º 22
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;
        }
Ejemplo n.º 23
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);
        }
Ejemplo n.º 24
0
        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());
        }
Ejemplo n.º 25
0
        private void BgSelectivelyExtractAnalysisDataFromZip_DoWork(object sender, DoWorkEventArgs e)
        {
            Ionic.Zip.ZipFile z = new Ionic.Zip.ZipFile(m_analysisPath);
            z.UseZip64WhenSaving       = Ionic.Zip.Zip64Option.Always;
            z.ParallelDeflateThreshold = -1;
            // Always extract directly into the current running location.
            // This ensures we don't accidentally fill up a temp drive or something with large files.
            AnalysisTraceID = m_analysisPath.Substring(m_analysisPath.LastIndexOf("\\") + 1).Replace("_SSASDiagOutput", "_SSASDiag").Replace(".zip", "");
            m_analysisPath  = m_analysisPath.Substring(0, m_analysisPath.LastIndexOf("\\") + 1) + AnalysisTraceID;

            if (!Directory.Exists(m_analysisPath))
            {
                Directory.CreateDirectory(m_analysisPath);
            }
            if (!Directory.Exists(m_analysisPath + "\\Analysis"))
            {
                Directory.CreateDirectory(m_analysisPath + "\\Analysis");
            }

            ExtractFileToPath(z, m_analysisPath, "SSASDiag.log");
            AnalysisTraceID = GetAnalysisIDFromLog();

            if (z.Entries.Where(f => f.FileName.Contains(".mdf")).Count() > 0)
            {
                try
                {
                    foreach (Ionic.Zip.ZipEntry ze in z.Entries.Where(f => f.FileName.Contains(".mdf") || f.FileName.Contains(".ldf")).ToList())
                    {
                        ExtractFileToPath(z, m_analysisPath + "\\Analysis", ze.FileName.Substring(ze.FileName.LastIndexOf("/") + 1));
                    }
                }
                catch (Exception ex)
                {
                    // Continue, since if we fail writing these files, it means they do already exist, and we can probably just attach subsequently without failure.
                    LogException(ex);
                }
            }
            else
            if (z.Entries.Where(f => f.FileName == AnalysisTraceID + "/Analysis/" + AnalysisTraceID + ".mdf").Count() == 0 && z.Entries.Where(f => f.FileName.Contains(".trc")).Count() > 0)
            {
                ExtractAllFilesOfType(z, ".trc");
            }
            if (z.Entries.Where(f => f.FileName == AnalysisTraceID + "/Analysis/" + AnalysisTraceID + "_NetworkAnalysis.log").Count() > 0)
            {
                ExtractFileToPath(z, m_analysisPath + "\\Analysis", AnalysisTraceID + "_NetworkAnalysis.log");
            }
            else
            {
                if (z.Entries.Where(f => f.FileName == AnalysisTraceID + ".etl").Count() > 0)
                {
                    ExtractFileToPath(z, m_analysisPath, AnalysisTraceID + ".etl");
                }
                if (z.Entries.Where(f => f.FileName == AnalysisTraceID + ".cab").Count() > 0)
                {
                    ExtractFileToPath(z, m_analysisPath, AnalysisTraceID + ".cab");
                }
            }
            if (z.Entries.Where(f => f.FileName.Contains(".blg")).Count() > 0)
            {
                ExtractAllFilesOfType(z, ".blg");
            }
            if (z.Entries.Where(f => f.FileName.Contains("SSASDiag_MemoryDump_Analysis_")).Count() == 0 &&
                (z.Entries.Where(f => f.FileName.Contains(".mdmp")).Count() > 0))
            {
                ExtractAllFilesOfType(z, ".mdmp");
            }
            if (z.Entries.Where(f => f.FileName.Contains(".evtx")).Count() > 0)
            {
                ExtractAllFilesOfType(z, ".evtx");
            }
            if (z.Entries.Where(f => f.FileName == "msmdsrv.ini").Count() > 0)
            {
                ExtractFileToPath(z, m_analysisPath, "msmdsrv.ini");
            }
            z.Dispose();

            StatusFloater.Invoke(new System.Action(() =>
            {
                StatusFloater.Hide();
            }));
        }
Ejemplo n.º 26
0
        //This creates a backup rollout xml document that is placed within the zip file being rolled out.
        //This backup can be used if the back end ever gets broken to restore the rollout file.
        internal static void createBackupRolloutDocument(XmlNode rolloutNode, int versionNumber, string connectionString)
        {
            XmlDocument    doc            = new XmlDocument();
            XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            XmlElement root = doc.DocumentElement;

            doc.InsertBefore(xmlDeclaration, root);

            XmlElement baseDoc = doc.CreateElement("RolloutDocumentation");

            doc.AppendChild(baseDoc);

            XmlElement connInfoElement = doc.CreateElement("ConnectionInfo");

            connInfoElement.SetAttribute("ConnectionString", connectionString);
            connInfoElement.SetAttribute("ConnectionDateSet", DateTime.Now.ToString());
            baseDoc.AppendChild(connInfoElement);

            string   zipPath     = rolloutNode.Attributes.GetNamedItem("FullZipPath").Value;
            DateTime rolloutDate = DateTime.Parse(rolloutNode.Attributes.GetNamedItem("DateTimeStamp").Value);

            XmlElement version = doc.CreateElement("Version");

            version.InnerText = versionNumber.ToString();
            baseDoc.AppendChild(version);

            XmlElement userTypeEl = doc.CreateElement("UserType");

            userTypeEl.InnerText = rolloutNode.Name;
            baseDoc.AppendChild(userTypeEl);

            foreach (XmlAttribute att in rolloutNode.Attributes)
            {
                XmlElement newElement = doc.CreateElement(att.Name);
                newElement.InnerText = att.Value;
                baseDoc.AppendChild(newElement);
            }

            string backUpXML = Directory.GetCurrentDirectory() + "\\TempBackups\\" + rolloutDate.ToShortDateString().Replace("/", "-") + ".xml";

            doc.Save(backUpXML);
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zipPath))
            {
                try
                {
                    var file = zip.Entries.Single(p => p.FileName.Contains(".xml"));
                    if (file != null)
                    {
                        zip.RemoveEntry(file.FileName);
                    }
                    zip.Save();
                }
                catch (Exception)
                {
                }
                zip.AddFile(backUpXML, "");
                zip.Save();
                zip.Dispose();
            }
        }
Ejemplo n.º 27
0
        private void SelectivelyExtractAnalysisDataFromZip()
        {
            Ionic.Zip.ZipFile z = new Ionic.Zip.ZipFile(m_analysisPath);
            // Always extract directly into the current running location.
            // This ensures we don't accidentally fill up a temp drive or something with large files.
            AnalysisTraceID = m_analysisPath.Substring(m_analysisPath.LastIndexOf("\\") + 1).Replace("_SSASDiagOutput", "_SSASDiag").Replace(".zip", "");
            m_analysisPath  = m_analysisPath.Substring(0, m_analysisPath.LastIndexOf("\\") + 1) + AnalysisTraceID;

            if (!Directory.Exists(m_analysisPath))
            {
                Directory.CreateDirectory(m_analysisPath);
            }
            if (!Directory.Exists(m_analysisPath + "\\Analysis"))
            {
                Directory.CreateDirectory(m_analysisPath + "\\Analysis");
            }

            if (z["SSASDiag.log"] != null)
            {
                z["SSASDiag.log"].Extract(m_analysisPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
            }
            AnalysisTraceID = GetAnalysisIDFromLog();

            if (z.Entries.Where(f => f.FileName == "Analysis\\" + AnalysisTraceID + ".mdf").Count() > 0)
            {
                try
                {
                    z.Entries.Where(f => f.FileName == "Analysis\\" + AnalysisTraceID + ".mdf").First().Extract(m_analysisPath + "\\Analysis", Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                    z.Entries.Where(f => f.FileName == "Analysis\\" + AnalysisTraceID + ".ldf").First().Extract(m_analysisPath + "\\Analysis", Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                }
                catch (Exception ex)
                {
                    // Continue, since if we fail writing these files, it means they do already exist, and we can probably just attach subsequently without failure.
                    LogException(ex);
                }
            }
            else
            if (z.Entries.Where(f => f.FileName.Contains(".trc")).Count() > 0)
            {
                foreach (Ionic.Zip.ZipEntry e in z.Entries.Where(f => f.FileName.Contains(".trc")))
                {
                    e.Extract(m_analysisPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                }
            }
            if (z.Entries.Where(f => f.FileName == "Analysis\\" + AnalysisTraceID + "_NetworkAnalysis.log").Count() > 0)
            {
                z.Entries.Where(f => f.FileName == "Analysis\\" + AnalysisTraceID + "_NetworkAnalysis.log").First().Extract(m_analysisPath + "\\Analysis", Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
            }
            else
            {
                if (z.Entries.Where(f => f.FileName == AnalysisTraceID + ".etl").Count() > 0)
                {
                    z.Entries.Where(f => f.FileName == AnalysisTraceID + ".etl").First().Extract(m_analysisPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                }
                if (z.Entries.Where(f => f.FileName == AnalysisTraceID + ".cab").Count() > 0)
                {
                    z.Entries.Where(f => f.FileName == AnalysisTraceID + ".cab").First().Extract(m_analysisPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                }
            }
            if (z.Entries.Where(f => f.FileName.Contains(".blg")).Count() > 0)
            {
                foreach (Ionic.Zip.ZipEntry e in z.Entries.Where(f => f.FileName.Contains(".blg")))
                {
                    e.Extract(m_analysisPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                }
            }
            if (z.Entries.Where(f => f.FileName.Contains(".mdmp")).Count() > 0)
            {
                foreach (Ionic.Zip.ZipEntry e in z.Entries.Where(f => f.FileName.Contains(".mdmp")))
                {
                    e.Extract(m_analysisPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                }
            }
            if (z.Entries.Where(f => f.FileName.Contains(".evtx")).Count() > 0)
            {
                foreach (Ionic.Zip.ZipEntry e in z.Entries.Where(f => f.FileName.Contains(".evtx")))
                {
                    e.Extract(m_analysisPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                }
            }
            if (z.Entries.Where(f => f.FileName == "msmdsrv.ini").Count() > 0)
            {
                z.Entries.Where(f => f.FileName == "msmdsrv.ini").First().Extract(m_analysisPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
            }
            z.Dispose();
        }
Ejemplo n.º 28
0
        public static JsonData Decompress
            (string preDefinedRootRelativePath,
            ViewModels.PathAndDirectoriesAndFilesViewModel viewModel)
        {
            JsonData oJsonData = null;

            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);

            Ionic.Zip.ZipFile oZipFile = null;

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

                    if (System.IO.File.Exists(strCurrentPathName) == false)
                    {
                        continue;
                    }

                    oZipFile =
                        new Ionic.Zip.ZipFile(strCurrentPathName);

                    InitializeZipFile(oZipFile);

                    try
                    {
                        oZipFile.ExtractAll
                            (strPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    }
                    catch
                    {
                    }
                }

                oJsonData =
                    GetDirectoriesAndFiles(preDefinedRootRelativePath, viewModel.Path);

                return(oJsonData);
            }
            catch
            {
                string strErrorMessage =
                    "Unexpected Error on Decompressing File(s)!";

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

                return(oJsonData);
            }
            finally
            {
                if (oZipFile != null)
                {
                    oZipFile.Dispose();
                    oZipFile = null;
                }
            }
        }
Ejemplo n.º 29
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            string TempZipFile = Path.GetTempFileName();

            File.Delete(TempZipFile);
            TempZipFile = TempZipFile + ".zip";
            System.IO.File.WriteAllBytes(TempZipFile, (byte[])TargetResource.GetObject("Core"));

            {
                Ionic.Zip.ZipFile zipf = new Ionic.Zip.ZipFile(TempZipFile);
                long totalSize         = 0;
                foreach (var entry in zipf)
                {
                    totalSize += entry.UncompressedSize;
                }
                progressBar1.Maximum  = (Int32)totalSize;
                zipf.ExtractProgress += new EventHandler <Ionic.Zip.ExtractProgressEventArgs>(onExtractProgress);
                try
                {
                    zipf.ExtractAll(TargetPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    zipf.Dispose();
                }
                catch
                {
                    MessageBox.Show("Error");
                    Close();
                }
            }
            File.Delete(TempZipFile);

            //Save Backgrounds
            if (CodeVars["MainUI.BG"] != "")
            {
                MyFunc.SaveImageByPath(CodeVars["MainUI.BG"], Path.Combine(TargetPath, SkinFolder, "graphics/JackMyth/MainBG.tga"));
            }
            if (CodeVars["Settings.BG"] != "")
            {
                MyFunc.SaveImageByPath(CodeVars["Settings.BG"], Path.Combine(TargetPath, SkinFolder, "graphics/JackMyth/SettingsDialog.tga"));
            }
            if (CodeVars["Installation.BG"] != "")
            {
                MyFunc.SaveImageByPath(CodeVars["Installation.BG"], Path.Combine(TargetPath, SkinFolder, "graphics/JackMyth/InstallAppWizard.tga"));
            }
            if (CodeVars["BackupAndRestore.BG"] != "")
            {
                MyFunc.SaveImageByPath(CodeVars["BackupAndRestore.BG"], Path.Combine(TargetPath, SkinFolder, "graphics/JackMyth/BackupWizard.tga"));
            }
            if (CodeVars["SystemInfo.BG"] != "")
            {
                MyFunc.SaveImageByPath(CodeVars["SystemInfo.BG"], Path.Combine(TargetPath, SkinFolder, "graphics/JackMyth/SystemInfo.tga"));
            }
            if (CodeVars["Loggin.BG"] != "")
            {
                MyFunc.SaveImageByPath(CodeVars["Loggin.BG"], Path.Combine(TargetPath, SkinFolder, "graphics/JackMyth/LoginBG.tga"));
            }
            if (CodeVars["SecurityWizard.BG"] != "")
            {
                MyFunc.SaveImageByPath(CodeVars["SecurityWizard.BG"], Path.Combine(TargetPath, SkinFolder, "graphics/JackMyth/bg_security_wizard.tga"));
            }
            if (CodeVars["CDKey.BG"] != "")
            {
                MyFunc.SaveImageByPath(CodeVars["CDKey.BG"], Path.Combine(TargetPath, SkinFolder, "graphics/JackMyth/CDKeyWizard.tga"));
            }

            string Skinpath = Path.Combine(TargetPath, SkinFolder);
            //Apply Collapsed Sliderbar Layout
            {
                bool isCollapsed = false;
                bool.TryParse(CodeVars["MainUI.Collapsed"], out isCollapsed);
                if (isCollapsed)
                {
                    MyFunc.CopyDir(Path.Combine(Skinpath, "Customization/Collapsed Sidebar"), Skinpath, true);
                }
            }

            //Replace Paramter Mark with CodeVars.
            //Text Color
            string SteamStyle = File.ReadAllText(Path.Combine(Skinpath, "resource/styles/steam.styles"));

            for (int i = 0; i < 6; i++)
            {
                MyFunc.ApplyColorParamter(ref SteamStyle, MyFunc.GetTextTypeByID(i, false),
                                          ColorTranslator.FromHtml(CodeVars[MyFunc.GetTextTypeByID(i, false)]));
                MyFunc.ApplyColorParamter(ref SteamStyle, MyFunc.GetTextTypeByID(i, true),
                                          ColorTranslator.FromHtml(CodeVars[MyFunc.GetTextTypeByID(i, true)]));
            }
            File.WriteAllText(Path.Combine(Skinpath, "resource/styles/steam.styles"), SteamStyle);
            Close();
        }
Ejemplo n.º 30
0
        public bool RestoreFile_decoded(string nomefileBackUp)
        {
#if (!DBG_TEST)
            return(RestoreFile_old(nomefileBackUp));
#endif
            string      str, cartellatmp;
            XmlDocument doc = new XmlDocument();

            // controlli file
            cartellatmp = App.TMP_FOLDER;
            if (!cartellatmp.EndsWith(@"\"))
            {
                cartellatmp += @"\";
            }
            str = cartellatmp + Guid.NewGuid().ToString();
            DirectoryInfo di = new DirectoryInfo(str);
            if (di.Exists)
            {
                // errore directory già esistente aspettare processo terminato da parte
                // di altro utente
                return(false);
            }
            cartellatmp = str;
            di.Create();
            // verifico il contenuto
            try
            {
                Ionic.Zip.ZipFile z = new Ionic.Zip.ZipFile(nomefileBackUp);
                z.ExtractAll(
                    cartellatmp, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                z.Dispose();
                z = null;
            }
            catch (Exception e)
            {
                di.Delete(true);
                MessageBox.Show(e.Message);
                return(false);
            }
            // contenuto corretto, elimino cartelle vecchie
            DirectoryInfo rdf = new DirectoryInfo(App.AppDataDataFolder);
            if (rdf.Exists)
            {
                rdf.Delete(true);
            }
            DirectoryInfo uuf = new DirectoryInfo(App.AppDocumentiFolder);
            if (uuf.Exists)
            {
                uuf.Delete(true);
            }
            // rimuovo master file
            FileInfo fi = new FileInfo(App.AppMasterDataFile);
            if (fi.Exists)
            {
                fi.Delete();
            }
            // rimuovo indice documenti
            fi = new FileInfo(App.AppDocumentiDataFile);
            if (fi.Exists)
            {
                fi.Delete();
            }
            // decodifica di tutti i files

            // RevisoftApp.rmdf e RevisoftApp.rdocf
            XmlManager x = new XmlManager {
                TipoCodifica = XmlManager.TipologiaCodifica.Nessuna
            };
            string[] files = Directory.GetFiles(
                cartellatmp, @"*.*", SearchOption.TopDirectoryOnly);
            foreach (string s in files)
            {
                doc          = x.LoadEncodedFile_old(s);
                str          = doc.InnerXml.Replace("&#x8;", "");
                doc.InnerXml = str;
                doc.Save(s);
            }

            // dati in DataFile
            files = Directory.GetFiles(
                cartellatmp + @"\" + App.DataFolder, @"*.*", SearchOption.TopDirectoryOnly);
            foreach (string s in files)
            {
                doc          = x.LoadEncodedFile_old(s);
                str          = doc.InnerXml.Replace("&#x8;", "");
                doc.InnerXml = str;
                doc.Save(s);
            }
            // importazione in SQL
            using (SqlConnection conn = new SqlConnection(App.connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("dbo.impMasterFile", conn);
                cmd.Parameters.AddWithValue("@masterFileFolder", cartellatmp);
                cmd.Parameters.AddWithValue("@dataFolder", cartellatmp + @"\" + App.DataFolder);
                cmd.Parameters.AddWithValue("@docFolder", cartellatmp);
                cmd.CommandType    = CommandType.StoredProcedure;
                cmd.CommandTimeout = App.m_CommandTimeout;
                try { cmd.ExecuteNonQuery(); }
                catch (Exception ex)
                {
                    str = ex.Message;
                    if (!App.m_bNoExceptionMsg)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            // ripristino cartelle
            DirectoryInfo d_rdf = new DirectoryInfo(App.AppDataDataFolder); // ex "\\RDF"
            if (!d_rdf.Exists)
            {
                d_rdf.Create();
            }
            str = App.AppDataDataFolder; if (!str.EndsWith(@"\"))
            {
                str = str + @"\";
            }
            str = str + "XAML";
            DirectoryInfo d_xaml = new DirectoryInfo(str);
            if (!d_xaml.Exists)
            {
                d_xaml.Create();
            }
            DirectoryInfo d_uuff = new DirectoryInfo(App.AppDocumentiFolder); // ex "\\UserUF"
            if (!d_uuff.Exists)
            {
                d_uuff.Create();
            }
            DirectoryInfo d_ufl = new DirectoryInfo(App.AppDocumentiFlussiFolder); // ex "\\UserUF"
            if (!d_ufl.Exists)
            {
                d_ufl.Create();
            }
            // copia contenuto
            foreach (string item in Directory.GetFiles(cartellatmp,
                                                       "*.*", SearchOption.AllDirectories))
            {
                File.Copy(item, item.Replace(cartellatmp, App.AppDataFolder), true);
            }
            Directory.Delete(cartellatmp, true);
            App.m_xmlCache.Clear();
            return(true);
        }
Ejemplo n.º 31
0
        public ActionResult DownloadFiles(int ID, string Folders, string Files)
        {
            User              user   = HttpContext.CurrentUser();
            int               userID = user.ID;
            BuildingEntities  db     = (BuildingEntities)this.db;
            FileContentResult result;

            Project project = db.Projects.FirstOrDefault(val => val.ID == ID && !val.Deleted);

            if (!Available(project))
            {
                ViewBag.Error = "Forbidden";
                return(View("Error"));
            }

            int[] folderIDs = Folders.StringAndTrim().Split(',').Select(val => val.ToIntOrDefault()).Where(val => val.HasValue).Select(val => val.Value).ToArray();
            int[] filesIDs  = Files.StringAndTrim().Split(',').Select(val => val.ToIntOrDefault()).Where(val => val.HasValue).Select(val => val.Value).ToArray();

            string fileName = project.Name.Replace(System.IO.Path.GetInvalidFileNameChars(), "_") + ".zip";

            Ionic.Zip.ZipFile      zip = new Ionic.Zip.ZipFile(fileName);
            System.IO.MemoryStream ms  = new System.IO.MemoryStream();

            if (Folders != null && Folders.Any())
            {
                List <Folder> folders = db.Folders.Where(val => val.ProjectID == ID && folderIDs.Contains(val.ID)).ToList();
                foreach (Folder folder in folders)
                {
                    List <Models.File> files = db.Files.Include("Folder").Where(val => val.Folder.ProjectID == folder.ProjectID && val.Folder.TreeString.StartsWith(folder.TreeString)).ToList();
                    foreach (Models.File f in files)
                    {
                        if (System.IO.File.Exists(f.RealPath))
                        {
                            string trim  = folder.FullName.Contains('/') ? folder.FullName.Substring(0, folder.FullName.LastIndexOf('/') + 1) : string.Empty;
                            string path  = trim.Length > 0 ? f.Folder.FullName.Substring(trim.Length) : f.Folder.FullName;
                            var    zfile = zip.AddFile(f.RealPath, path);

                            if (zfile.FileName.Contains('/'))
                            {
                                zfile.FileName = zfile.FileName.Substring(0, zfile.FileName.LastIndexOf('/') + 1) + f.Name;
                            }
                            else
                            {
                                zfile.FileName = f.Name;
                            }
                        }
                    }
                }
            }
            if (Files != null && Files.Any())
            {
                List <Models.File> files = db.Files.Include("Folder").Where(val => val.Folder.ProjectID == ID && filesIDs.Contains(val.ID)).ToList();

                foreach (Models.File f in files)
                {
                    if (System.IO.File.Exists(f.RealPath))
                    {
                        string path  = string.Empty;
                        var    zfile = zip.AddFile(f.RealPath, path);

                        if (zfile.FileName.Contains('/'))
                        {
                            zfile.FileName = zfile.FileName.Substring(0, zfile.FileName.LastIndexOf('/') + 1) + f.Name;
                        }
                        else
                        {
                            zfile.FileName = f.Name;
                        }
                    }
                }
            }

            zip.Save(ms);
            result = File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Zip, fileName);

            zip.Dispose();
            ms.Dispose();

            return(result);
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Applied after Install runs.
 /// </summary>
 internal static void Postfix(Ionic.Zip.ZipFile ___zipfile)
 {
     ___zipfile.Dispose();
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Disposes the current epub file by disposing the underlying zip file
 /// </summary>
 public void Dispose()
 {
     file.Dispose();
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Load Textures into memory.
        /// </summary>
        private void LoadTexs()
        {
            //try{
            Data = Ionic.Zip.ZipFile.Read("Art\\art.dat");
            MapTiles.Add(0, LoadFromFile(d2dRenderTarget, GetFile("Grass.jpg")));
            MapTiles.Add(1, LoadFromFile(d2dRenderTarget, GetFile("Soil.jpg")));
            MapTiles.Add(100, LoadFromFile(d2dRenderTarget, GetFile("tower_basic.png")));
            MapTiles.Add(101, LoadFromFile(d2dRenderTarget, GetFile("tower_slow.png")));
            MapTiles.Add(102, LoadFromFile(d2dRenderTarget, GetFile("tower_light.png")));
            MapTiles.Add(103, LoadFromFile(d2dRenderTarget, GetFile("tower_cannon.png")));

            MapTiles.Add(51, LoadFromFile(d2dRenderTarget, GetFile("bg.png")));
            MapTiles.Add(50, LoadFromFile(d2dRenderTarget, GetFile("blue_button.png")));
            //Animated textures must be PNG.
            MonsterModels.Add(0, new AnimatedTexture("impnew", 128, 128, 60, d2dRenderTarget));
            MonsterModels.Add(1, new AnimatedTexture("spider_128", 128, 128, 60, d2dRenderTarget));
            MonsterModels.Add(2, new AnimatedTexture("bird_128", 128, 128, 60, d2dRenderTarget));
            Data.Dispose();
            Data = null;
            //} catch(Exception e) {MessageBox.Show(e.Message);}
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Streams a local zip file using a streamreader.
        /// Important: the caller must call Dispose() on the returned ZipFile instance.
        /// </summary>
        /// <param name="filename">Location of the original zip file</param>
        /// <param name="zip">The ZipFile instance to be returned to the caller</param>
        /// <returns>Stream reader of the first file contents in the zip file</returns>
        public static StreamReader Unzip(string filename, out Ionic.Zip.ZipFile zip)
        {
            StreamReader reader = null;
            zip = null;

            try
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        zip = new Ionic.Zip.ZipFile(filename);

                        reader = new StreamReader(zip[0].OpenReader());
                    }
                    catch (Exception err)
                    {
                        Log.Error("QC.Data.Unzip(1): " + err.Message);
                        if (zip != null) zip.Dispose();
                        if (reader != null) reader.Close();
                    }
                }
                else
                {
                    Log.Error("Data.UnZip(2): File doesn't exist: " + filename);
                }
            }
            catch (Exception err)
            {
                Log.Error("Data.UnZip(3): " + filename + " >> " + err.Message);
            }
            return reader;
        }
        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
        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
Ejemplo n.º 38
0
        /// <summary>
        /// Streams a local zip file using a streamreader.
        /// Important: the caller must call Dispose() on the returned ZipFile instance.
        /// </summary>
        /// <param name="filename">Location of the original zip file</param>
        /// <param name="zipEntryName">The zip entry name to open a reader for. Specify null to access the first entry</param>
        /// <param name="zip">The ZipFile instance to be returned to the caller</param>
        /// <returns>Stream reader of the first file contents in the zip file</returns>
        public static StreamReader Unzip(string filename, string zipEntryName, out ZipFile zip)
        {
            StreamReader reader = null;
            zip = null;

            try
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        zip = new ZipFile(filename);
                        var entry = zip.FirstOrDefault(x => zipEntryName == null || string.Compare(x.FileName, zipEntryName, StringComparison.OrdinalIgnoreCase) == 0);
                        if (entry == null)
                        {
                            throw new ArgumentException("Unable to locate zip entry with name: " + zipEntryName);
                        }

                        reader = new StreamReader(entry.OpenReader());
                    }
                    catch (Exception err)
                    {
                        Log.Error(err, "Inner try/catch");
                        if (zip != null) zip.Dispose();
                        if (reader != null) reader.Close();
                    }
                }
                else
                {
                    Log.Error("Data.UnZip(2): File doesn't exist: " + filename);
                }
            }
            catch (Exception err)
            {
                Log.Error(err, "File: " + filename);
            }
            return reader;
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Streams a local zip file using a streamreader.
        /// Important: the caller must call Dispose() on the returned ZipFile instance.
        /// </summary>
        /// <param name="filename">Location of the original zip file</param>
        /// <param name="zip">The ZipFile instance to be returned to the caller</param>
        /// <returns>Stream reader of the first file contents in the zip file</returns>
        public static StreamReader Unzip(string filename, out ZipFile zip)
        {
            StreamReader reader = null;
            zip = null;

            try
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        zip = new ZipFile(filename);

                        reader = new StreamReader(zip[0].OpenReader());
                    }
                    catch (Exception err)
                    {
                        Log.Error(err, "Inner try/catch");
                        if (zip != null) zip.Dispose();
                        if (reader != null) reader.Close();
                    }
                }
                else
                {
                    Log.Error("Data.UnZip(2): File doesn't exist: " + filename);
                }
            }
            catch (Exception err)
            {
                Log.Error(err, "File: " + filename);
            }
            return reader;
        } // End UnZip