public void Initialize(Stream stream)
        {
            _zipStream      = stream;
            _tempFolderName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ Guid.NewGuid().ToString()}");
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            archive.ExtractToDirectory(_tempFolderName);

            DirectoryInfo folder = new DirectoryInfo(_tempFolderName);

            FileInfo[] files = folder.GetFiles();
            var        entryAssemblyFileName = Path.GetFileNameWithoutExtension(_packagePath).ToLower() + ".dll";
            FileInfo   configFile            = files.SingleOrDefault(p => p.Name.ToLower() == entryAssemblyFileName);

            if (configFile == null)
            {
                throw new QStack.Framework.Core.ServiceFrameworkException("can not find the entry assembly.the package name must be same as the entry assembly.");
            }
            else
            {
                FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(configFile.FullName);

                _pluginInfo = new PluginInfoDto
                {
                    DisplayName = fileVersionInfo.FileDescription,
                    Version     = fileVersionInfo.FileVersion,
                    Name        = Path.GetFileNameWithoutExtension(fileVersionInfo.FileName)
                };
            }
        }
		private async void ButtonRestore_Click(object sender, RoutedEventArgs e)
		{
			var selected = ListBoxBackups.SelectedItem as BackupFile;
			if(selected != null)
			{
				var result =
					await
					Helper.MainWindow.ShowMessageAsync("Restore backup " + selected.DisplayName,
					                                   "This can not be undone! Make sure you have a current backup (if necessary). To create one, CANCEL and click \"CREATE NEW\".",
					                                   MessageDialogStyle.AffirmativeAndNegative);
				if(result == MessageDialogResult.Affirmative)
				{
					var archive = new ZipArchive(selected.FileInfo.OpenRead(), ZipArchiveMode.Read);
					archive.ExtractToDirectory(Config.Instance.DataDir, true);
					Config.Load();
					Config.Save();
					DeckList.Load();
					DeckList.Save();
					DeckStatsList.Load();
					DeckStatsList.Save();
					DefaultDeckStats.Load();
					DefaultDeckStats.Save();
					Helper.MainWindow.ShowMessage("Success", "Please restart HDT for this to take effect.");
				}
			}
		}
        public void Initialize(Stream stream)
        {
            _zipStream      = stream;
            _tempFolderName = $"{ AppDomain.CurrentDomain.BaseDirectory }{ Guid.NewGuid().ToString()}";
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            archive.ExtractToDirectory(_tempFolderName);

            var folder = new DirectoryInfo(_tempFolderName);

            var files = folder.GetFiles();

            var configFiles = files.Where(p => p.Name == "plugin.json");

            if (!configFiles.Any())
            {
                throw new Exception("The plugin is missing the configuration file.");
            }
            else
            {
                using (var s = configFiles.First().OpenRead())
                {
                    LoadConfiguration(s);
                }
            }
        }
Example #4
0
        public void Initialize(Stream stream)
        {
            _zipStream      = stream;
            _tempFolderName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ Guid.NewGuid().ToString()}");
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            archive.ExtractToDirectory(_tempFolderName);

            DirectoryInfo folder = new DirectoryInfo(_tempFolderName);

            FileInfo[] files = folder.GetFiles();

            FileInfo configFile = files.SingleOrDefault(p => p.Name == "plugin.json");

            if (configFile == null)
            {
                throw new MissingConfigurationFileException();
            }
            else
            {
                using (FileStream s = configFile.OpenRead())
                {
                    LoadConfiguration(s);
                }
            }
        }
 /// <summary>
 /// Downloads the specified web driver version.
 /// </summary>
 /// <param name="version">The version to download.</param>
 protected override void Update(string version)
 {
     using (var client = new WebClient())
     using (var stream = client.OpenRead("http://chromedriver.storage.googleapis.com/" + version + "/chromedriver_win32.zip"))
     using (var archive = new ZipArchive(stream))
         archive.ExtractToDirectory(Path.Combine(ParentPath, version));
 }
Example #6
0
        private static bool InstallModule() {
            try {
                var ini = new IniFile(Path.Combine(FileUtils.GetDocumentsCfgDirectory(), "launcher.ini"));
                var theme = ini["WINDOW"].GetNonEmpty("theme");
                var directory = Path.Combine(AcRootDirectory.Instance.RequireValue, @"launcher", @"themes", theme ?? @"default", @"modules", ModuleId);

                var installed = false;
                if (!Directory.Exists(directory)) {
                    Directory.CreateDirectory(directory);

                    using (var stream = new MemoryStream(BinaryResources.ModuleCmHelper))
                    using (var archive = new ZipArchive(stream)) {
                        archive.ExtractToDirectory(directory);
                    }

                    installed = true;
                }

                var active = ini["MODULES"].GetStrings("ACTIVE");
                if (!active.Contains(ModuleId)) {
                    ini["MODULES"].Set("ACTIVE", active.Append(@"CmHelper").Distinct());
                    ini.Save();
                    installed = true;
                }

                return installed;
            } catch (Exception e) {
                throw new InformativeException("Can’t install UI module", e);
            }
        }
 /// <summary>
 /// Downloads the specified web driver version.
 /// </summary>
 /// <param name="version">The version to download.</param>
 protected override void Update(string version)
 {
     using (var client = new WebClient())
     using (var stream = client.OpenRead("http://selenium-release.storage.googleapis.com/" + version + "/IEDriverServer_Win32_" + version + ".0.zip"))
     using (var archive = new ZipArchive(stream))
         archive.ExtractToDirectory(Path.Combine(ParentPath, version));
 }
        public EmbeddedProcessTemplate(string processTemplateName)
        {
            _templatePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetType(), processTemplateName + ".zip"))
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
                    archive.ExtractToDirectory(_templatePath);
        }
 public static Archive LoadArchiveFromFile(Stream from, string dest)
 {
     if(!Directory.Exists(dest)) {
     Directory.CreateDirectory(dest);
       }
       var zip = new ZipArchive(from);
       zip.ExtractToDirectory(dest, true);
       return LoadArchiveFromDir(dest);
 }
 /*
  * We expect teh Zip archive to contain:
  * ddd.zip {ddd = south-offset declination, SCP=0, NCP=180
  *      ddd {directory}
  *          bddd0.acc   {accelerator files}
  *          bddd0.cat   {astrometric catalogue data}
  *          bddd1.acc   {accelerator files}
  *          bddd1.cat   {astrometric catalogue data}
  *          ...
  *          bddd9.acc   {accelerator files}
  *          bddd9.cat   {astrometric catalogue data}
  *          *.
  */
 private async Task ExtractOne(string zipName, string destinationDirectory)
 {
     await using (var zipStream = new FileStream(zipName, FileMode.Open))
     {
         var zip = new System.IO.Compression.ZipArchive(zipStream, ZipArchiveMode.Read);
         Console.WriteLine($"Extracting {zipName}, {zip.Entries.Count} entries");
         zip.ExtractToDirectory(destinationDirectory);
         Console.WriteLine($"Finished {zipName}");
     }
 }
Example #11
0
        public virtual void BeforeFirstTest()
        {
            m_scratch.Create();

            using (var sampleDb = new MemoryStream( Properties.Resources.SampleDatabase ))
            using (var archive = new ZipArchive( sampleDb ))
                archive.ExtractToDirectory( m_scratch.FullName );

            Database.CreateOnce( Path.Combine( m_scratch.FullName, "movie.mdf" ) );
        }
Example #12
0
        private void BtExtraerTodoClick(object sender, EventArgs e)
        {
            const string rutaExtraido = @"C:\Tests\Extraidos\";

            using (var zip = new FileStream(RutaZip, FileMode.Open))
            {
                using (var archivo = new ZipArchive(zip, ZipArchiveMode.Update))
                {
                    archivo.ExtractToDirectory(rutaExtraido);
                }
            }
        }
        private static void ExtractSolution(string name, string destinationFolder)
        {
            var solutionArchivePath = Path.GetFullPath(name + ".zip");

            Assert.IsTrue(File.Exists(solutionArchivePath), "Test solution does not exist at {0}", solutionArchivePath);

            using (var solutionStream = File.OpenRead(solutionArchivePath))
            using (var archive = new ZipArchive(solutionStream, ZipArchiveMode.Read, true))
            {
                archive.ExtractToDirectory(destinationFolder);
            }
        }
Example #14
0
        private static void ResignScriptsInPackages(string packagePath, string outputPath)
        {
            var packages = Directory.EnumerateFiles(packagePath, "*.nupkg");

            foreach (var targetPackage in packages)
            {

                List<string> scriptPaths = new List<string>();
                using (FileStream stream = new FileStream(targetPackage, FileMode.Open))
                {
                    using (ZipArchive originalArchive = new ZipArchive(stream))
                    {
                        Console.WriteLine("{0}:", packagePath);
                        if (!originalArchive.Entries.Any(z => z.GetFileExtension().Contains("ps1")))
                        {
                            Console.WriteLine("No Powershell scripts found in {0}", targetPackage);
                            continue;
                        }

                        scriptPaths.AddRange(
                            originalArchive.Entries.Where(z => z.GetFileExtension().Contains("ps1"))
                                .Select(z => z.FullName));

                        var tempPath = Path.GetRandomFileName();
                        originalArchive.ExtractToDirectory(tempPath);

                        foreach (var script in scriptPaths)
                        {
                            var currentFile = Path.Combine(tempPath, script);
                            bool isSigned = Verifier.HasValidSignature(currentFile);
                            Console.WriteLine("{0} is {1}", currentFile, isSigned ? "signed" : "not signed");
                            if (!isSigned)
                            {
                                SignFile.SignFileFromDisk(currentFile);
                            }
                        }

                        var newPackageName = Path.GetFileName(targetPackage);
                        var outputPackagePath = Path.Combine(outputPath, newPackageName);

                        var parent = Path.GetDirectoryName(outputPackagePath);
                        if (!Directory.Exists(parent))
                        {
                            Directory.CreateDirectory(parent);
                        }
                        ZipFile.CreateFromDirectory(tempPath,outputPackagePath);

                    }
                }

            }
        }
Example #15
0
        public void SetupFolder()
        {
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            _zipStream.Position = 0;
            _folderName         = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", $"{_pluginConfiguration.Name}");

            archive.ExtractToDirectory(_folderName, true);

            DirectoryInfo folder = new DirectoryInfo(_tempFolderName);

            folder.Delete(true);
        }
 public static void UnZip(string zipFile, string destPath=null)
 {
     if (destPath.IsNullOrWhiteSpace()) {
       FileInfo fi = new FileInfo(zipFile);
       destPath = fi.DirectoryName;
       }
       if (!Directory.Exists(destPath)) {
       Directory.CreateDirectory(destPath);
       }
       using (FileStream zipFileToOpen = new FileStream(zipFile, FileMode.Open))
       using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Update))
       archive.ExtractToDirectory(destPath);
 }
Example #17
0
        public static void NewLineInitialize(TestContext testContext)
        {
            _testFolderPath = Path.Combine(Path.GetTempPath(), "TrimCopyTest");

            if (Directory.Exists(_testFolderPath))
                Directory.Delete(_testFolderPath, true);

            using (var ms = new MemoryStream(Properties.Resources.newLineInputOutput))
            using (var za = new ZipArchive(ms))
            {
                za.ExtractToDirectory(_testFolderPath);
            }
        }
        public void SetupFolder()
        {
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            _zipStream.Position = 0;
            _folderName         = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{Configuration.Name}";

            archive.ExtractToDirectory(_folderName, true);

            var folder = new DirectoryInfo(_tempFolderName);

            folder.Delete(true);
        }
 private static void extractZip(ZipArchive zip, string destination, bool mapFilesInFolder)
 {
     if(mapFilesInFolder)
     {
         foreach(ZipArchiveEntry e in zip.Entries)
         {
             e.ExtractToFile(destination + "/" + e.Name);
         }
     }
     else
     {
         zip.ExtractToDirectory(destination);
     }
 }
Example #20
0
 private void Completed(object sender, AsyncCompletedEventArgs e)
 {
     label.Text = "Extracing";
     using (var fileStream = new FileStream("sai.zip", FileMode.Open))
     {
         using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Read))
         {
             archive.ExtractToDirectory(Application.StartupPath, true);
         }
     }
     MessageBox.Show("Updated!");
     Process.Start("VisualSAIEditor.exe");
     Application.Exit();
 }
Example #21
0
        public void Initialize(Stream stream)
        {
            var     tempFolderName = $"{ AppDomain.CurrentDomain.BaseDirectory }{ Guid.NewGuid().ToString()}";
            ZipTool archive        = new ZipTool(stream, ZipArchiveMode.Read);

            archive.ExtractToDirectory(tempFolderName);

            var folder = new DirectoryInfo(tempFolderName);

            var files = folder.GetFiles();

            var configFiles = files.Where(p => p.Name == "plugin.json");

            if (!configFiles.Any())
            {
                throw new Exception("The plugin is missing the configuration file.");
            }
            else
            {
                using (var s = configFiles.First().OpenRead())
                {
                    LoadConfiguration(s);
                }
            }

            folder.Delete(true);

            _folderName = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{_pluginConfiguration.Name}";

            if (Directory.Exists(_folderName))
            {
                throw new Exception("The plugin has been existed.");
            }

            stream.Position = 0;
            archive.ExtractToDirectory(_folderName);
        }
Example #22
0
        public static void ExtractToDirectory(
            string sourceArchiveFileName, string destinationDirectoryName,
            Encoding entryNameEncoding)
        {
            if (sourceArchiveFileName == null)
            {
                throw new ArgumentNullException("sourceArchiveFileName");
            }

            using (ZipArchive zipArchive = ZipFile.Open(sourceArchiveFileName,
                                                        ZipArchiveMode.Read, entryNameEncoding))
            {
                zipArchive.ExtractToDirectory(destinationDirectoryName);
            }
        }
        public bool UnZipPackage(string zipFile, out PluginInfoDto pluginInfoDto)
        {
            pluginInfoDto = null;
            using (FileStream fs = new FileStream(zipFile, FileMode.Open))
            {
                DirectoryInfo folder = null;
                try
                {
                    ZipTool archive = new ZipTool(fs, ZipArchiveMode.Read);
                    fs.Position = 0;
                    var pluginName = Path.GetFileNameWithoutExtension(zipFile);
                    var destFolder = Path.Combine(_baseDirectory, _pluginOptions.InstallBasePath, $"{pluginName}");


                    archive.ExtractToDirectory(destFolder, true);

                    folder = new DirectoryInfo(destFolder);

                    FileInfo[] files = folder.GetFiles();
                    var        entryAssemblyFileName = Path.GetFileNameWithoutExtension(zipFile).ToLower() + ".dll";
                    FileInfo   configFile            = files.SingleOrDefault(p => p.Name.ToLower() == entryAssemblyFileName);

                    if (configFile == null)
                    {
                        throw new QStack.Framework.Core.ServiceFrameworkException("can not find the entry assembly.the package name must be same as the entry assembly.");
                    }
                    else
                    {
                        FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(configFile.FullName);

                        pluginInfoDto = new PluginInfoDto
                        {
                            DisplayName = fileVersionInfo.FileDescription,
                            Version     = fileVersionInfo.FileVersion,
                            Name        = Path.GetFileNameWithoutExtension(fileVersionInfo.FileName)
                        };
                    }
                    pluginInfoDto.IntallPath = Path.GetRelativePath(_baseDirectory, destFolder);

                    return(true);
                }
                catch
                {
                    folder?.Delete(true);
                    return(false);
                }
            }
        }
Example #24
0
 // decompress
 // @return value: true(decomp), false(no need), null(error)
 public static bool? Decompress(string ArcPath)
 {
     // check
     switch(Path.GetExtension(ArcPath)){
         case ".bms":
         case ".bme":
         case ".bml":
             // Nothing
             Console.WriteLine("Archive Extract: No need.");
             // Move File
             File.Move(ArcPath, ExtractPath + Path.GetFileName(ArcPath));
             return false;
         case ".zip":
             // Zip archive
             var ZipArc = new ZipArchive(new FileStream(ArcPath, FileMode.Open));
             ZipArc.ExtractToDirectory(ExtractPath);
             Console.WriteLine("Archive Extract: Success(Type: Zip).");
             ZipArc.Dispose();
             return true;
         case ".rar":
             // Rar archive
             // Load Unrar.dll
             var rarMgr = new UnRarDllMgr();
             var UnrarPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\bin\\unrar64.dll";
             if(!rarMgr.LoadModule(UnrarPath)) {
                 // Error Message
                 Console.WriteLine("Error: Can't Load \"Unrar64.dll\"");
                 return null;
             }
             // Filelist get
             var FileLists = rarMgr.GetFileList(ArcPath);
             // All Extract
             foreach(var FileData in FileLists) {
                 rarMgr.FileExtractToFolder(ArcPath, FileData.FileNameW, ExtractPath);
             }
             Console.WriteLine("Archive Extract: Success(Type: Rar).");
             // Release Unrar.dll
             rarMgr.UnloadModule();
             rarMgr.CloseArchive();
             return true;
         default:
             // Error Message
             Console.WriteLine("Error: this extension({0}) is not supported.",
                 Path.GetExtension(ArcPath));
             return null;
     }
 }
Example #25
0
        public static SymbolPackage Extract(Stream fileStream, string package, string filePath)
        {
            if (!package.EndsWith(".symbols.nupkg", StringComparison.OrdinalIgnoreCase))
            {
                throw new Exception("Not a symbols package bro");
            }

            var packageId = package.Substring(0, package.Length - ".symbols.nupkg".Length);

            using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Read))
            {
                Directory.CreateDirectory(filePath);
                archive.ExtractToDirectory(filePath);
            }

            return new SymbolPackage(filePath, packageId);
        }
 private void ExtractDatabase()
 {
     if (!File.Exists(this.databasePath))
     {
         using (Stream stream = this.GetResource("awagame.zip"))
         using (ZipArchive zip = new ZipArchive(stream))
         {
             try
             {
                 zip.ExtractToDirectory(this.PluginDataPath);
             }
             catch
             {
                 Console.WriteLine("Unable to extract awagame.zip");
             }
         }
     }
 }
Example #27
0
        internal static void Unzip(byte[] bs, string directoryPath)
        {
            // Avoid IOException in ZipFile.ExtractToDirectory(...)
            // when directoryPath is not empty.
            if (Directory.Exists(directoryPath) && !Bool.IsEmptyDirectory(directoryPath))
            {
                Directory.Delete(directoryPath, true);
            }

            using (var ms = new MemoryStream(bs))
            {
                using (var za = new ZipArchive(ms))
                {
                    // A wrapping directory is not created.
                    za.ExtractToDirectory(directoryPath);
                }
            }
        }
        public void SetupFolder(string destFolder = null)
        {
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            _zipStream.Position = 0;
            if (string.IsNullOrWhiteSpace(destFolder))
            {
                _folderName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _pluginOptions.InstallBasePath, $"{_pluginInfo.Name}");
            }
            else
            {
                _folderName = destFolder;
            }
            archive.ExtractToDirectory(_folderName, true);
            _pluginInfo.IntallPath = Path.GetRelativePath(AppDomain.CurrentDomain.BaseDirectory, _folderName);
            DirectoryInfo folder = new DirectoryInfo(_tempFolderName);

            folder.Delete(true);
        }
Example #29
0
        /// <summary>
        /// Extracts all the files in the specified zip archive to a directory on the file system.
        /// </summary>
        public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName, Encoding entryNameEncoding)
        {
            if (string.IsNullOrEmpty(sourceArchiveFileName))
            {
                throw new ArgumentNullException("sourceArchiveFileName");
            }
            if (string.IsNullOrEmpty(destinationDirectoryName))
            {
                throw new ArgumentNullException("destinationDirectoryName");
            }

            using (var zipFileStream = new FileStream(sourceArchiveFileName, FileMode.Open))
            {
                using (var archive = new ZipArchive(zipFileStream, ZipArchiveMode.Read))
                {
                    archive.ExtractToDirectory(destinationDirectoryName);
                }
            }
        }
Example #30
0
        public void TestZipController()
        {
            ApplicationManager.Run("TestZip", appManager =>
            {
                string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                Directory.CreateDirectory(tempDirectory);
                string tempZipPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                try
                {
                    // Create file on server using vfs
                    appManager.VfsWebRootManager.WriteAllText("foo.txt", "Hello zip");

                    // Make sure it's part of the zip we get
                    using (var zipFile = new ZipArchive(appManager.ZipManager.GetZipStream("site")))
                    {
                        zipFile.ExtractToDirectory(tempDirectory);

                        string settings = File.ReadAllText(Path.Combine(tempDirectory, "wwwroot", "foo.txt"));
                        Assert.Contains("Hello zip", settings);
                    }

                    string barFile = Path.Combine(tempDirectory, "wwwroot", "bar.txt");
                    File.WriteAllText(barFile, "Kudu zip");

                    ZipFile.CreateFromDirectory(tempDirectory, tempZipPath);

                    // Upload a zip with an additional file
                    appManager.ZipManager.PutZipFile("site", tempZipPath);

                    // Use vfs to make sure it's there
                    string barContent = appManager.VfsWebRootManager.ReadAllText("bar.txt");
                    Assert.Contains("Kudu zip", barContent);
                }
                finally
                {
                    Directory.Delete(tempDirectory, recursive: true);
                    File.Delete(tempZipPath);
                }
            });
        }
Example #31
0
        public void Initialize(Stream stream)
        {
            using (ZipTool archive = new ZipTool(stream, ZipArchiveMode.Read))
            {
                archive.ExtractToDirectory(_folderName);

                var folder = new DirectoryInfo(_folderName);

                var files = folder.GetFiles();

                var configFiles = files.Where(p => p.Name == "plugin.json");

                if (!configFiles.Any())
                {
                    throw new Exception("The plugin is missing the configuration file.");
                }
                else
                {
                    LoadConfiguration(configFiles.First().OpenRead());
                }
            }
        }
        private static void UpdateAvaliable()
        {
            MessageBoxResult mbr = MessageBox.Show("An update for Virtual Pokemon Tabletop was found...\n\nCurrent Version: " + VersioningInfo.Version + "\nLatest Version: " + LatestVersion.Version_Name, "Virtual Pokemon Tabletop Update", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);

            if (mbr == MessageBoxResult.Yes)
            {
                Directory.CreateDirectory(MainWindow.AssemblyDirectory + "/Updater/");
                WebClient wc = new WebClient();
                wc.DownloadFile("http://vptu.assaultbirdsoftware.me/Updater/UpdateApp/VPTU_Updater.zip", MainWindow.AssemblyDirectory + "/Updater/VPTU_Updater.zip");

                using (FileStream FileStream = new FileStream(MainWindow.AssemblyDirectory + "/Updater/VPTU_Updater.zip", FileMode.Open))
                    using (System.IO.Compression.ZipArchive Archive = new System.IO.Compression.ZipArchive(FileStream, ZipArchiveMode.Read))
                    {
                        Archive.ExtractToDirectory(MainWindow.AssemblyDirectory + "/Updater/");
                    }
                Process.Start(MainWindow.AssemblyDirectory + "/Updater/Updater.exe", "");
                Process.GetCurrentProcess().Kill();
            }
            else if (mbr == MessageBoxResult.No)
            {
                // Nothing
            }
        }
        private async void Initialize() {
            //try {
                using (var stream = await file.OpenStreamForWriteAsync())
                using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) {

                    var folder = await GetTempImportFolder();

                    zip.ExtractToDirectory(folder.Path);
                    var file = await folder.GetFileAsync("tiles.json");

                    var array = JsonArray.Parse(await FileIO.ReadTextAsync(file));

                    array.ForEach((entry) => {
                        var jsonObject = entry.GetObject();

                        var tile = new SecondaryTile() {
                            TileId = jsonObject.Read("TileId"),
                            Arguments = jsonObject.Read("Arguments"),
                            DisplayName = jsonObject.Read("Name"),
                        };

                        var uri = new Uri($"ms-appdata:///local/import/{tile.TileId}/normal");
                        tile.VisualElements.Square150x150Logo = uri;
                        TileList.Items.Add(tile);
                    });
                }
                IsPrimaryButtonEnabled = true;
                Loading.Visibility = Visibility.Collapsed;
                TileList.IsEnabled = true;
            //} catch(Exception e) {
            //    new MessageDialog(e.Message)
            //        .Title("Import failed")
            //        .ShowAsync();
            //    Hide();
            //}
        }
Example #34
0
        private static void BackupFolder()
        {
            // create zip file using current date
            using (FileStream zipToOpen = File.Open(DateTime.Now.ToString() + Directory.GetCurrentDirectory()
                + ".zip", FileMode.Create))
            {
                // create archive
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    // get list of files to be zipped, using current directory
                    var fileList = Directory.GetFiles((Directory.GetCurrentDirectory()));

                    // loop through each file in current directory and zip
                    foreach (var file in fileList)
                    {
                        archive.CreateEntryFromFile(file, file);
                    }

                // back up new zip file to folder
                    // FINISH - REPLACE NAME WITH NAME OF BACKUP DIRECTORY? NOW USING MSDN STRING NAME
                archive.ExtractToDirectory(Directory.GetCurrentDirectory());
                }
            }
        }
Example #35
0
        /// <summary>
        /// Extract the complete archive to the specified destination.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="destination">Location where to extract the files.</param>
        /// <param name="entries">The entries to extract, currently not supported.</param>
        /// <returns>TRUE on success or FALSE on failure.</returns>
        public bool extractTo(Context ctx, string destination, PhpValue entries = default(PhpValue))
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            if (!Operators.IsEmpty(entries))
            {
                PhpException.ArgumentValueNotSupported(nameof(entries), entries);
                return(false);
            }

            try
            {
                _archive.ExtractToDirectory(FileSystemUtils.AbsolutePath(ctx, destination));
                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(false);
            }
        }
Example #36
0
        public void TestZipController()
        {
            ApplicationManager.Run("TestZip", appManager =>
            {
                string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                Directory.CreateDirectory(tempDirectory);
                string tempZip1Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                string tempZip2Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                string foundContent;
                try
                {
                    var siteRoot = "site";
                    var wwwRoot = "wwwroot";
                    var testFile1Name = "TestFile1." + System.Guid.NewGuid().ToString("N") + ".txt";
                    var testFile1Content = "Hello World\n" + System.Guid.NewGuid().ToString("N");
                    var testFile1LocalPath = Path.Combine(tempDirectory, wwwRoot, testFile1Name);

                    TestTracer.Trace("Creating first test file {0} is on the server.", testFile1Name);
                    appManager.VfsWebRootManager.WriteAllText(testFile1Name, testFile1Content);

                    TestTracer.Trace("Verifying first file {0} is in downloaded.", testFile1Name);
                    using (var zipFile = new ZipArchive(appManager.ZipManager.GetZipStream(siteRoot)))
                    {
                        zipFile.ExtractToDirectory(tempDirectory);
                        foundContent = File.ReadAllText(testFile1LocalPath);
                        Assert.Equal(testFile1Content, foundContent);
                    }

                    var testFile2Name = "TestFile2." + System.Guid.NewGuid().ToString("N") + ".txt";
                    var testFile2LocalPath = Path.Combine(tempDirectory, wwwRoot, testFile2Name);
                    var testFile2InitialContent = "Hello World with a guid\n" + System.Guid.NewGuid().ToString("N");
                    var testFile2UpdatedContent = "Hello World without a guid";

                    // Make sure our second version of the file is smaller so we can see bugs in file overwrite.
                    Assert.True(testFile2UpdatedContent.Length < testFile2InitialContent.Length);

                    TestTracer.Trace("Uploading second file {0}.", testFile2Name);
                    File.WriteAllText(testFile2LocalPath, testFile2InitialContent);
                    ZipFile.CreateFromDirectory(tempDirectory, tempZip1Path);
                    appManager.ZipManager.PutZipFile(siteRoot, tempZip1Path);

                    TestTracer.Trace("Verifying second file {0} is in uploaded.", testFile2Name);
                    foundContent = appManager.VfsWebRootManager.ReadAllText(testFile2Name);
                    Assert.Equal(testFile2InitialContent, foundContent);

                    TestTracer.Trace("Uploading zip with modified second file and missing first file.", testFile2UpdatedContent);
                    File.Delete(testFile1LocalPath);
                    File.WriteAllText(testFile2LocalPath, testFile2UpdatedContent);
                    ZipFile.CreateFromDirectory(tempDirectory, tempZip2Path);
                    appManager.ZipManager.PutZipFile(siteRoot, tempZip2Path);

                    TestTracer.Trace("Verifying second file is in uploaded and modified correctly.");
                    foundContent = appManager.VfsWebRootManager.ReadAllText(testFile2Name);
                    Assert.Equal(testFile2UpdatedContent, foundContent);

                    // This is expected because our zip controller does not delete files
                    // that are missing from the zip if they are already existing on the server.
                    TestTracer.Trace("Verifying first file still on server.");
                    foundContent = appManager.VfsWebRootManager.ReadAllText(testFile1Name);
                    Assert.Equal(testFile1Content, foundContent);

                }
                finally
                {
                    Directory.Delete(tempDirectory, recursive: true);
                    File.Delete(tempZip1Path);
                    File.Delete(tempZip2Path);
                }
            });
        }
Example #37
0
        private void CreateISOImageWithGrub(string compiledFile)
        {
            string isoDirectory = Path.Combine(Options.DestinationDirectory, "iso");

            if (Directory.Exists(isoDirectory))
            {
                Directory.Delete(isoDirectory, true);
            }

            Directory.CreateDirectory(isoDirectory);
            Directory.CreateDirectory(Path.Combine(isoDirectory, "boot"));
            Directory.CreateDirectory(Path.Combine(isoDirectory, "boot", "grub"));
            Directory.CreateDirectory(isoDirectory);

            string loader = string.Empty;

            if (Options.BootLoader == BootLoader.Grub_0_97)
            {
                loader = @"boot/grub/stage2_eltorito";
                File.WriteAllBytes(Path.Combine(isoDirectory, "boot", "grub", "stage2_eltorito"), GetResource(@"grub\0.97", "stage2_eltorito"));
                File.WriteAllBytes(Path.Combine(isoDirectory, "boot", "grub", "menu.lst"), GetResource(@"grub\0.97", "menu.lst"));
            }
            else if (Options.BootLoader == BootLoader.Grub_2_00)
            {
                loader = @"boot/grub/i386-pc/eltorito.img";
                File.WriteAllBytes(Path.Combine(isoDirectory, "boot", "grub", "grub.cfg"), GetResource(@"grub\2.00", "grub.cfg"));

                Directory.CreateDirectory(Path.Combine(isoDirectory, "boot", "grub", "i386-pc"));

                var data = GetResource(@"grub\2.00", "i386-pc.zip");
                var dataStream = new MemoryStream(data);

                var archive = new ZipArchive(dataStream);

                archive.ExtractToDirectory(Path.Combine(isoDirectory, "boot", "grub"));
            }

            File.Copy(compiledFile, Path.Combine(isoDirectory, "boot", "main.exe"));

            ImageFile = Path.Combine(Options.DestinationDirectory, Path.GetFileNameWithoutExtension(Options.SourceFile) + ".iso");

            string arg =
                "-relaxed-filenames" +
                " -J -R" +
                " -o " + Quote(ImageFile) +
                " -b " + Quote(loader) +
                " -no-emul-boot" +
                " -boot-load-size 4" +
                " -boot-info-table " +
                Quote(isoDirectory);

            LaunchApplication(AppLocations.mkisofs, arg, true);
        }
Example #38
0
 private bool ExtractPackage()
 {
     try
     {
         ZipArchive zipArchive = new ZipArchive(new MemoryStream(this.Package.Package));
         if (Directory.Exists(".tmp"))
             Directory.Delete(".tmp", true);
         zipArchive.ExtractToDirectory(".tmp");
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Example #39
0
        public async void Extract()
        {
            if (zipfile != null)
            {
                _unzip.ZipFileName = zipfile.Name;
                string type = zipfile.ContentType;
            }
            else
            {
                ErrorMessage = "No File Selected";
                return;
            }


            string mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(extractToFolder, extractToFolder.Name);

            Stream stream = await zipfile.OpenStreamForReadAsync();
            try
            {
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
                {
                    try
                    {
                        StorageFolder folderToSave = await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFolderAsync(mruToken);
                        IEnumerable<StorageFolder> folders = await folderToSave.GetFoldersAsync();
                        StorageFolder fileNameFolder;
                        string requiredPath = string.Format("{0}\\{1}", folderToSave.Path, zipfile.Name.Replace(".zip", ""));
                        int reqFolderCount = folders.Where(x => x.Path.Contains(requiredPath)).Count();
                        if (reqFolderCount == 0)
                        {
                            fileNameFolder = await folderToSave.CreateFolderAsync(zipfile.Name.Replace(".zip", ""));
                        }
                        else
                        {
                            fileNameFolder = await folderToSave.CreateFolderAsync(zipfile.Name.Replace(".zip", string.Format("({0})", reqFolderCount + 1)));
                        }
                        //StorageFolder fileNameFolder = await folderToSave.CreateFolderAsync(zipfile.Name.Replace(".zip", ""));
                        if (!string.IsNullOrEmpty(fileNameFolder.Path))
                        {
                            _unzip.IsSuccess = false;
                            this.InProgress = true;
                            await Task.Run(() => archive.ExtractToDirectory(fileNameFolder.Path));
                            _unzip.IsSuccess = true;
                            this.InProgress = false;
                            ErrorMessage = "Success Extraction";
                        }

                    }
                    catch (Exception ex)
                    {
                        _unzip.ErrorMessage = ex.Message;
                    }
                }


                using (var archive = new  ZipArchive(stream, ZipArchiveMode.Read))
                {
                    try
                    {
                        StorageFolder folderToSave = await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFolderAsync(mruToken);
                        IEnumerable<StorageFolder> folders = await folderToSave.GetFoldersAsync();
                        StorageFolder fileNameFolder;
                        string requiredPath = string.Format("{0}\\{1}", folderToSave.Path, zipfile.Name.Replace(".zip", ""));
                        int reqFolderCount = folders.Where(x => x.Path.Contains(requiredPath)).Count();
                        if (reqFolderCount == 0)
                        {
                            fileNameFolder = await folderToSave.CreateFolderAsync(zipfile.Name.Replace(".zip", ""));
                        }
                        else
                        {
                            fileNameFolder = await folderToSave.CreateFolderAsync(zipfile.Name.Replace(".zip", string.Format("({0})", reqFolderCount + 1)));
                        }
                        //StorageFolder fileNameFolder = await folderToSave.CreateFolderAsync(zipfile.Name.Replace(".zip", ""));
                        if (!string.IsNullOrEmpty(fileNameFolder.Path))
                        {
                            _unzip.IsSuccess = false;
                            this.InProgress = true;
                            await Task.Run(() => archive.ExtractToDirectory(fileNameFolder.Path));
                            _unzip.IsSuccess = true;
                            this.InProgress = false;
                            ErrorMessage = "Success Extraction";
                        }

                    }
                    catch (Exception ex)
                    {
                        _unzip.ErrorMessage = ex.Message;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
            }
           
        } 
Example #40
0
        public async Task InstallPlugin(PluginEntry plugin, IProgress<double?> progress = null, CancellationToken cancellation = default(CancellationToken)) {
            var destination = GetPluginDirectory(plugin.Id);

            try {
                plugin.IsInstalling = true;
                
                var data = await CmApiProvider.GetDataAsync($"plugins/get/{plugin.Id}", progress, cancellation);
                if (data == null || cancellation.IsCancellationRequested) return;

                await Task.Run(() => {
                    if (Directory.Exists(destination)) {
                        FileUtils.Recycle(destination);
                    }

                    using (var stream = new MemoryStream(data, false))
                    using (var archive = new ZipArchive(stream)) {
                        archive.ExtractToDirectory(destination);
                    }
                }, cancellation);
                if (cancellation.IsCancellationRequested) return;

                plugin.InstalledVersion = plugin.Version;
                File.WriteAllText(Path.Combine(destination, ManifestName), JsonConvert.SerializeObject(plugin));

                if (plugin.IsEnabled) {
                    PluginEnabled?.Invoke(this, new AppAddonEventHandlerArgs { PluginId = plugin.Id });
                }
            } catch (Exception e) {
                NonfatalError.Notify(ToolsStrings.Plugins_CannotInstall, e);
            } finally {
                plugin.IsInstalling = false;
            }
        }
Example #41
0
        private void butRecord_Click(object sender, EventArgs e)
        {
            var assembly = typeof(Form1).Assembly;

            if (!_InitTraceResources)
            {
                _TempDir = Path.GetTempFileName();

                File.Delete(_TempDir);
                Directory.CreateDirectory(_TempDir);

                using (Stream stream = assembly.GetManifestResourceStream("DesuraLogRecorder.resources.zip"))
                using (StreamReader reader = new StreamReader(stream))
                using (var zip = new ZipArchive(stream))
                {
                    zip.ExtractToDirectory(_TempDir);
                }

                _InitTraceResources = true;
            }

            var json = getJson();
            var outFile = Path.Combine(_TempDir, Path.GetRandomFileName()) + ".html";

            using (Stream stream = assembly.GetManifestResourceStream("DesuraLogRecorder.LogTrace.html"))
            using (StreamReader reader = new StreamReader(stream))
            {
                var all = reader.ReadToEnd();
                File.WriteAllText(outFile, all.Replace("//@@TRACE_DATA@@", json));
            }

            var psi = new ProcessStartInfo() {
                UseShellExecute = true,
                FileName = String.Format("file:///{0}", outFile.Replace('\\', '/'))
            };

            Process.Start(psi);
        }
Example #42
0
        private async Task<bool> LoadAndInstall() {
            if (_isInstalling) return false;
            _isInstalling = true;

            try {
                var data = await CmApiProvider.GetDataAsync("data/latest");
                if (data == null) throw new InformativeException(ToolsStrings.AppUpdater_CannotLoad, ToolsStrings.Common_MakeSureInternetWorks);

                string installedVersion = null;
                await Task.Run(() => {
                    var location = FilesStorage.Instance.Combine(FilesStorage.DataDirName);
                    Directory.Delete(location, true);

                    using (var stream = new MemoryStream(data, false))
                    using (var archive = new ZipArchive(stream)) {
                        installedVersion = VersionFromData(archive.GetEntry(@"Manifest.json").Open().ReadAsStringAndDispose());
                        archive.ExtractToDirectory(location);
                    }
                });

                InstalledVersion = installedVersion;
                Logging.Write("Data loaded: " + InstalledVersion);
                return true;
            } catch (Exception e) {
                NonfatalError.Notify(ToolsStrings.ContentSyncronizer_CannotLoadContent, ToolsStrings.ContentSyncronizer_CannotLoadContent_Commentary, e);
            } finally {
                _isInstalling = false;
            }

            return false;
        }
Example #43
0
        private void OnOpenFile(string fileName)
        {
            // Show message.
            this.textBox.AppendText(string.Format("Opening file \'{0}\'...{1}", fileName, Environment.NewLine));

            try
            {
                // Open a stream to the ZIP file.
                using (FileStream fileInStream = new FileStream(fileName, FileMode.Open))
                {
                    // Open the ZIP archive.
                    using (ZipArchive zipArchive = new ZipArchive(fileInStream, ZipArchiveMode.Read))
                    {
                        // The shape file name.
                        string shapeFileName = null;

                        this.textBox.AppendText(string.Format("Extracting shape ZIP archive...{0}", Environment.NewLine));
                        foreach (ZipArchiveEntry entry in zipArchive.Entries)
                        {
                            // If this is the shape file, save the name.
                            if (Path.GetExtension(entry.Name) == ".shp")
                            {
                                shapeFileName = entry.Name;
                            }
                            this.textBox.AppendText(string.Format("- {0}: {1} bytes {2} bytes compressed{3}", entry.Name, entry.Length, entry.CompressedLength, Environment.NewLine));
                        }

                        // If there are no entries, throw an exception.
                        if (null == shapeFileName) throw new FileNotFoundException("The ZIP archive does not contain a shape file.");

                        // Create the name of a temporary folder.
                        string tempFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                        this.textBox.AppendText(string.Format("Shape file name is: \'{0}\'{1}", shapeFileName, Environment.NewLine));

                        // Create the temporary folder.
                        System.IO.Directory.CreateDirectory(tempFolder);

                        this.textBox.AppendText(string.Format("Creating temporary folder \'{0}\'...{1}", tempFolder, Environment.NewLine));

                        try
                        {
                            // Extract the shapefile contents.
                            zipArchive.ExtractToDirectory(tempFolder);

                            // Open the shapefile.
                            using (Shapefile shapefile = new Shapefile(Path.Combine(tempFolder, shapeFileName)))
                            {
                                this.textBox.AppendText(Environment.NewLine);

                                // Write the basic information.
                                this.textBox.AppendText(string.Format("Type: {0}, Shapes: {1:n0}{2}", shapefile.Type, shapefile.Count, Environment.NewLine));

                                this.textBox.AppendText(Environment.NewLine);

                                // Create a map object.
                                Map map = new Map(new MapRectangle(
                                    shapefile.BoundingBox.Left,
                                    shapefile.BoundingBox.Top,
                                    shapefile.BoundingBox.Right,
                                    shapefile.BoundingBox.Bottom));

                                // Write the bounding box of this shape file.
                                this.textBox.AppendText(string.Format("Bounds: {0},{1} -> {2},{3}{4}",
                                    shapefile.BoundingBox.Left,
                                    shapefile.BoundingBox.Top,
                                    shapefile.BoundingBox.Right,
                                    shapefile.BoundingBox.Bottom,
                                    Environment.NewLine));

                                // Enumerate all shapes.
                                foreach (Shape shape in shapefile)
                                {
                                    // Shape basic information.
                                    //this.textBox.AppendText(string.Format("{0} {1} {2} ", shape.RecordNumber, shape.Type, shape.GetMetadata("name")));

                                    // Create a new shape.
                                    MapShape mapShape;
                                    switch (shape.Type)
                                    {
                                        case ShapeType.Point:
                                            ShapePoint shapePoint = shape as ShapePoint;
                                            mapShape = new MapShapePoint(new MapPoint(shapePoint.Point.X, shapePoint.Point.Y));
                                            break;
                                        case ShapeType.Polygon:
                                            ShapePolygon shapePolygon = shape as ShapePolygon;

                                            //this.textBox.AppendText(string.Format(": {0}", shapePolygon.Parts.Count));

                                            MapShapePolygon mapShapePolygon = new MapShapePolygon(new MapRectangle(
                                                shapePolygon.BoundingBox.Left,
                                                shapePolygon.BoundingBox.Top,
                                                shapePolygon.BoundingBox.Right,
                                                shapePolygon.BoundingBox.Bottom));
                                            foreach(PointD[] part in shapePolygon.Parts)
                                            {
                                                MapPart mapPart = new MapPart();
                                                foreach (PointD point in part)
                                                {
                                                    mapPart.Points.Add(point.X, point.Y);
                                                }
                                                mapShapePolygon.Parts.Add(mapPart);
                                            }
                                            mapShape = mapShapePolygon;
                                            break;
                                        default:
                                            throw new NotSupportedException(string.Format("Shape type {0} is not supported.", shape.Type));
                                    }
                                    // Add the shape metadata.
                                    foreach (string name in shape.GetMetadataNames())
                                    {
                                        mapShape.Metadata[name] = shape.GetMetadata(name);
                                    }
                                    // Add the shape to the map.
                                    map.Shapes.Add(mapShape);
                                    //this.textBox.AppendText(Environment.NewLine);
                                }

                                this.textBox.AppendText(Environment.NewLine);

                                // Create a memory stream.
                                using (MemoryStream memoryStream = new MemoryStream())
                                {
                                    // Serialize the map data.
                                    map.Write(memoryStream);
                                    // Display the XML.
                                    this.textBox.AppendText(Encoding.UTF8.GetString(memoryStream.ReadToEnd()));

                                    this.textBox.AppendText(Environment.NewLine);
                                    this.textBox.AppendText(Environment.NewLine);

                                    // Set the stream position to zero.
                                    memoryStream.Position = 0;
                                    // Display a dialog to save the file.
                                    if (this.saveFileDialog.ShowDialog(this) == DialogResult.OK)
                                    {
                                        // Create a file stream.
                                        using (FileStream fileOutStream = System.IO.File.Create(this.saveFileDialog.FileName))
                                        {
                                            // Compress the stream.
                                            //using (GZipStream zipStream = new GZipStream(fileOutStream, CompressionLevel.Optimal))
                                            //{
                                                this.textBox.AppendText("Uncompressed data is {0} bytes.{1}".FormatWith(memoryStream.Length, Environment.NewLine));
                                                memoryStream.CopyTo(fileOutStream);
                                                this.textBox.AppendText("Compressed data is {0} bytes.{1}".FormatWith(fileOutStream.Length, Environment.NewLine));
                                            //}
                                        }
                                    }
                                }
                                //this.textBox.AppendText(map.ToXml().ToString());
                                this.textBox.AppendText(Environment.NewLine);
                            }
                        }
                        finally
                        {
                            // Delete the temporary folder.
                            this.textBox.AppendText(Environment.NewLine);
                            System.IO.Directory.Delete(tempFolder, true);
                            this.textBox.AppendText(string.Format("Temporary folder \'{0}\' deleted.{1}", tempFolder, Environment.NewLine));
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                this.textBox.AppendText(string.Format("An exception occurred. {0}", exception.Message));
            }
            this.textBox.AppendText(Environment.NewLine);
            this.textBox.AppendText("Done.");
        }
Example #44
0
        string EnsurePhantom()
        {
            if (phantomExists)
                return phantomLocationCache;

            mutex.WaitOne();
            try
            {
                if (phantomExists)
                    return phantomLocationCache;

                ;
                var targetLocation = Path.Combine(assemblyDir, "phantomjs.exe");

                if (File.Exists(targetLocation))
                    return phantomLocationCache = targetLocation;

                try
                {
                    File.WriteAllBytes(targetLocation, Resources.phantomjs);
                }
                catch (IOException err)
                {
                    if (!err.Message.Contains("it is being used by another process"))
                        throw;
                }

                if (Directory.Exists(Path.Combine(assemblyDir, "JSRunners")))
                    return phantomLocationCache = targetLocation;

                using (var stream = new MemoryStream(Resources.runners))
                {
                    using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
                        archive.ExtractToDirectory(assemblyDir);
                }

                phantomExists = true;

                return phantomLocationCache = targetLocation;
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
Example #45
0
        public bool Extract(string mmuZipFile, string outputDir)
        {
            System.IO.Compression.ZipArchive zip = ZipFile.Open(mmuZipFile, ZipArchiveMode.Update);
            string dir      = "";
            bool   noFolder = false;

            for (int i = 0; i < zip.Entries.Count; i++)
            {
                var p = zip.Entries[i].FullName.IndexOf('\\');
                if (p == -1)
                {
                    p = zip.Entries[i].FullName.IndexOf('/');
                }
                if (p >= 0)
                {
                    if ((i > 0) && (dir != zip.Entries[i].FullName.Substring(0, p)))
                    {
                        noFolder = true;
                    }
                    dir = zip.Entries[i].FullName.Substring(0, p);
                }
                else
                {
                    noFolder = true;
                }
            }

            if (noFolder)
            { //there is no folder in the zip archive containing all the files, folder needs to be created, extract MMU name from file and make sure the name is unique in the folder structure
                dir = NameMUUDir(zip);
                if (Directory.Exists(outputDir + dir))
                {
                    int k = 1;
                    while (Directory.Exists(outputDir + dir + "-" + k.ToString()))
                    {
                        k++;
                    }
                    dir = dir + "-" + k.ToString() + "\\";
                }
                dir = dir.Replace("mmu", "").Replace("MMU", "");
                zip.ExtractToDirectory(outputDir + dir);
            }
            else
            { //there is common folder - check if it is unque in the folder sturcture, if not change the folder name using MMU name and version
                if (Directory.Exists(outputDir + dir))
                {
                    Stream descFile = null;
                    for (int i = 0; i < zip.Entries.Count; i++)
                    {
                        if (zip.Entries[i].Name == "description.json")
                        {
                            descFile = zip.Entries[i].Open();
                            break;
                        }
                    }
                    if (descFile == null)
                    {
                        return(false);
                    }

                    byte[] descBuff = new byte[descFile.Length];
                    descFile.Read(descBuff, 0, Convert.ToInt32(descFile.Length));
                    var mmudescription = Serialization.FromJsonString <MMUDescription>(Encoding.UTF8.GetString(descBuff));
                    dir = mmudescription.Name + "-" + mmudescription.Version;
                    dir = dir.Replace("mmu", "").Replace("MMU", "");
                    if (Directory.Exists(outputDir + dir))
                    {
                        int k = 1;
                        while (Directory.Exists(outputDir + dir + "-" + k.ToString()))
                        {
                            k++;
                        }
                        dir = dir + "-" + k.ToString() + "\\";
                    }
                    else
                    {
                        dir += "\\";
                    }
                    descFile.Dispose();

                    Directory.CreateDirectory(outputDir + dir);

                    //extraction file by file
                    for (int i = 0; i < zip.Entries.Count; i++)
                    {
                        var p = zip.Entries[i].FullName.IndexOf('\\');
                        if (p == -1)
                        {
                            p = zip.Entries[i].FullName.IndexOf('/');
                        }
                        var basefile = zip.Entries[i].FullName.Substring(p + 1);
                        p = basefile.LastIndexOf('\\');
                        if (p == -1)
                        {
                            p = basefile.LastIndexOf('/');
                        }
                        if (p > -1)
                        {
                            if (!Directory.Exists(outputDir + dir + basefile.Substring(0, p)))
                            {
                                Directory.CreateDirectory(outputDir + dir + basefile.Substring(0, p));
                            }
                        }
                        if (basefile != "") //it is empty in case of root directory entry
                        {
                            zip.Entries[i].ExtractToFile(outputDir + dir + basefile);
                        }
                    }
                }
                else
                {
                    // dir = dir.Replace("mmu", "").Replace("MMU", "");
                    zip.ExtractToDirectory(outputDir);
                }
            }


            zip.Dispose();
            return(true);
            //ZipFile.ExtractToDirectory(mmuZipFile, outputDir);
        }