Ejemplo n.º 1
0
        void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            string[] us             = (string[])e.UserState;
            string   currentVersion = us[0];
            string   downloadToPath = us[1];
            string   executeTarget  = us[2];

            if (!downloadToPath.EndsWith("\\"))
            {
                downloadToPath += "\\";
            }

            // Download folder + zip file
            string zipName = downloadToPath + currentVersion + ".zip";
            // Download folder\version\ + executable
            string exePath = downloadToPath + currentVersion + "\\" + executeTarget;

            if (new FileInfo(zipName).Exists)
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipName))
                {
                    if (TextVer == "app.version")
                    {
                        if (File.Exists(Environment.CurrentDirectory + "/Launcher.bak"))
                        {
                            File.Delete(Environment.CurrentDirectory + "/Launcher.bak");
                        }
                        File.Move(AppDomain.CurrentDomain.FriendlyName, "Launcher.bak");
                        Thread.Sleep(5000);
                        zip.ExtractAll(downloadToPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);

                        MessageBoxResult result = System.Windows.MessageBox.Show("Launcher updated, restart app!", "Congratulations", MessageBoxButton.OK, MessageBoxImage.Question);
                        if (result == MessageBoxResult.OK)
                        {
                            Process proc = Process.Start(downloadToPath + "\\" + executeTarget);
                            Environment.Exit(0);
                        }
                    }
                    else
                    {
                        zip.ExtractAll(downloadToPath + currentVersion, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    }
                }
                if (new FileInfo(exePath).Exists)
                {
                    Versions.CreateLocalVersionFile(downloadToPath, TextVer, currentVersion);
                    Process proc = Process.Start(exePath);
                }
                else
                {
                    System.Windows.MessageBox.Show("Problem with download. File does not exist.");
                }
            }
            else
            {
                System.Windows.MessageBox.Show("Problem with download. File does not exist.");
            }
        }
Ejemplo n.º 2
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.º 3
0
        public void UpdateSimFiles(String tempFolder, String simTempFolder, String currentfolder)
        {
            String lastArchiveUrl = this.SiteDataConnector.DownloadString("http://tyrant.webdever.ru/getlatestsim.php");

            using (WebClient Client = new WebClient())
            {
                String zipfilename = tempFolder + "\\downoaldedTyrantSim.zip";

                Client.DownloadFile(lastArchiveUrl, zipfilename);

                if (!File.Exists(zipfilename))
                {
                    throw new FileNotFoundException();
                }

                Ionic.Zip.ZipFile zipfile = new Ionic.Zip.ZipFile(zipfilename);

                zipfile.ExtractAll(simTempFolder);


                DirectoryInfo tempDir = new DirectoryInfo(simTempFolder);

                var exes = tempDir.GetFiles("*.exe");

                foreach (FileInfo fInfo in exes)
                {
                    fInfo.CopyTo(currentfolder + "\\" + fInfo.Name, true);
                }
            }
        }
Ejemplo n.º 4
0
 public void ExtractZipFile(string zipFileLocation, string destination)
 {
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileLocation))
     {
         zip.ExtractAll(destination);
     }
 }
Ejemplo n.º 5
0
        public string InstallService(InstallServiceDto input)
        {
            // Start program
            try
            {
                var byteArrayDes = JsonConvert.DeserializeObject <List <int> >(input.ByteArray);
                var newArray     = new byte[byteArrayDes.Count];
                int i            = 0;
                byteArrayDes.ForEach(x =>
                {
                    newArray[i++] = (byte)x;
                });
                if (File.Exists("install.zip"))
                {
                    File.Delete("install.zip");
                }
                if (Directory.Exists("process"))
                {
                    clearFolder("process");
                }
                File.WriteAllBytes("install.zip", newArray);
                using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read("install.zip"))
                {
                    zip1.ExtractAll("process",
                                    Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }


            return("OK");
        }
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 static string Extract(string file)
        {
            var tmp = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString(), new FileInfo(file).Name);
            var zip = new Ionic.Zip.ZipFile(file);

            zip.ExtractAll(tmp);
            return(tmp);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 解压存档到游戏存档目录
        /// </summary>
        /// <param name="file"></param>
        public static void Unzip(string file)
        {
            using (var zip = new Ionic.Zip.ZipFile(file))
            {
                Directory.GetFiles(dirPath, "*.tw*", SearchOption.TopDirectoryOnly).Do(File.Delete);

                zip.ExtractAll(dirPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            }
        }
Ejemplo n.º 9
0
        //----------------------------------------------------------------------------+
        //                                  Restore                                   |
        //----------------------------------------------------------------------------+
        public bool Restore_old(string IDBackUp)
        {
            string nomefileBackUp = "";

            Open();

            XmlNode xNode = document.SelectSingleNode("/ROOT/BACKUPS/BACKUP[@ID='" + IDBackUp + "']");

            if (xNode != null)
            {
                nomefileBackUp = xNode.Attributes["File"].Value;
            }

            Close();

            if (nomefileBackUp == "" || !(new FileInfo(cartellaBackUp + nomefileBackUp)).Exists)
            {
                return(false);
            }

            DirectoryInfo rdf = new DirectoryInfo(App.AppDataDataFolder);
            DirectoryInfo uuf = new DirectoryInfo(App.AppDocumentiFolder);

            if (rdf.Exists)
            {
                rdf.Delete(true);
            }

            if (uuf.Exists)
            {
                uuf.Delete(true);
            }

            FileInfo fi = new FileInfo(App.AppMasterDataFile);

            if (fi.Exists)
            {
                fi.Delete();
            }

            fi = new FileInfo(App.AppDocumentiDataFile);

            if (fi.Exists)
            {
                fi.Delete();
            }

            //apro lo zip
            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(cartellaBackUp + nomefileBackUp);
            zip.Password = App.ZipFilePassword;
            zip.ExtractAll(App.AppDataFolder);

            return(true);
        }
Ejemplo n.º 10
0
        private void btn_TrasferimentoArchiviLocale_Click(object sender, RoutedEventArgs e)
        {
            //richiesta conferma
            Utilities u = new Utilities();

            if (MessageBoxResult.No == u.ConfermaTrasferimentoArchivio())
            {
                return;
            }



            //controllo percorso
            DirectoryInfo origine = new DirectoryInfo(App.AppDataFolder);

            string tmpzipfile = App.AppTempFolder + "zip" + Guid.NewGuid().ToString();

            //Sposto archivio
            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
            zip.AddDirectory(origine.FullName);
            zip.Save(tmpzipfile);

            //Interfaccia
            radioButtonArchivioLocale.IsChecked = true;

            //setto variabili globali
            App.AppSetupTipoGestioneArchivio = App.TipoGestioneArchivio.Locale;

            //salvo nuova configurazione
            GestioneLicenza l = new GestioneLicenza();

            l.SalvaInfoDataUltimoUtilizzo();

            //Configuro path applicativi
            u.ConfiguraPercorsi();

            //trasferisco archivio
            DirectoryInfo destinazione = new DirectoryInfo(App.AppDataFolder);

            zip.ExtractAll(destinazione.FullName, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);



            MasterFile.ForceRecreate();

            //interfaccia
            //modifile all'interfaccia dell'ultimo momento
            radioButtonArchivioLocale.IsEnabled      = false;
            radioButtonArchivioRemoto.IsEnabled      = false;
            buttonSelezionaArchivioRemoto.IsEnabled  = false;
            btn_TrasferimentoArchivi.IsEnabled       = App.AppSetupTipoGestioneArchivio == App.TipoGestioneArchivio.Locale;
            btn_TrasferimentoArchiviLocale.IsEnabled = App.AppSetupTipoGestioneArchivio == App.TipoGestioneArchivio.Remoto;
            MessageBox.Show("Trasferimento archivio avvenuto con successo.");
        }
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
        void downloader_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            string[] us             = (string[])e.UserState;
            string   currentVersion = us[0];
            string   downloadPath   = us[1];
            string   executeTarget  = us[2];
            string   localVersion   = us[3];

            if (!downloadPath.EndsWith("\\"))             // Give a trailing \ if there isn't one
            {
                downloadPath += "\\";
            }

            string zipName    = downloadPath + currentVersion + ".zip"; // Download folder + zip file
            string sourcePath = downloadPath + currentVersion;          // Download Path
            string targetPath = CommConst.executePath;                  // 실행폴더
            string exePath    = targetPath + executeTarget;             // Download folder\version\ + executable

            if (new FileInfo(zipName).Exists)
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipName))
                {
                    zip.ExtractAll(downloadPath + currentVersion,
                                   Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }

                CopyFolder(sourcePath, targetPath);

                if (new FileInfo(exePath).Exists)
                {
                    Versions.CreateLocalVersionFile(downloadPath, localVersion, currentVersion);
                    // 집진기 Controller 종료
                    Process[] psList = Process.GetProcessesByName("CADC");
                    if (psList.Length > 0)
                    {
                        psList[0].Kill();
                    }

                    //MessageBox.Show("Path : " + exePath);
                    Process.Start(exePath);
                    Close();
                }
                else
                {
                    //Debug.Write("Problem with download. File does not exist.");
                    MessageBox.Show("Problem with download. File does not exist.", "Updater");
                }
            }
            else
            {
                //Debug.Write("Problem with download. File does not exist.");
                MessageBox.Show("Problem with download. File does not exist.", "Updater");
            }
        }
Ejemplo n.º 13
0
        void bwRestore_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (Directory.Exists("Data"))
                {
                    Directory.Delete("Data", true);
                }
                if (Directory.Exists(tempPath + "\\Data"))
                {
                    Directory.Delete(tempPath + "\\Data", true);
                }
                if (File.Exists("DB_Full.bak"))
                {
                    File.Delete("DB_Full.bak");
                }
                if (File.Exists(tempPath + "\\DB_Full.bak"))
                {
                    File.Delete(tempPath + "\\DB_Full.bak");
                }

                using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(e.Argument.ToString()))
                {
                    zip.Password = "******";
                    zip.ExtractAll(Environment.CurrentDirectory, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    zip.ExtractAll(tempPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }
                //ZipFile.ExtractToDirectory(e.Argument.ToString(), Environment.CurrentDirectory);
                //ZipFile.ExtractToDirectory(e.Argument.ToString(), tempPath);

                BaseDataBase._NonQuery(@"ALTER DATABASE [Ma3an] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", BaseDataBase.ConnectionStringMaster);
                int x = BaseDataBase._NonQuery(string.Format(@"RESTORE DATABASE [Ma3an] FROM DISK = '{0}' WITH  REPLACE;", tempPath + "\\DB_Full.bak"), BaseDataBase.ConnectionStringMaster);
                BaseDataBase._NonQuery(@"ALTER DATABASE [Ma3an] SET MULTI_USER", BaseDataBase.ConnectionStringMaster);
                if (x != -1)
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            { e.Cancel = true; }
        }
Ejemplo n.º 14
0
 private void UnZipToDirectory(string dir)
 {
     using (var tempZipFile = new TempFile())
     {
         File.WriteAllBytes(tempZipFile.Path, Resources.ShoppingList);
         using (var zip = new Ionic.Zip.ZipFile(tempZipFile.Path))
         {
             Directory.CreateDirectory(dir);
             zip.ExtractAll(dir);
         }
     }
 }
Ejemplo n.º 15
0
        public void UnzipFile(string zipFileName, string toFolder)
        {
            if (!FolderExists(toFolder))
            {
                CreateFolder(toFolder);
            }

            using (Ionic.Zip.ZipFile zipFile = Ionic.Zip.ZipFile.Read(zipFileName))
            {
                zipFile.ExtractAll(toFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            }
        }
Ejemplo n.º 16
0
        //加载打包文件
        private MethodTreeNode ImportMethodPackageFile()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Filter = filter;
            dlg.Title  = "请选择要导入的模型包";
            try
            {
                if (dlg.ShowDialog() != true)
                {
                    return(null);
                }

                System.Windows.Forms.FolderBrowserDialog pathdlg = new System.Windows.Forms.FolderBrowserDialog();
                pathdlg.Description = "请选择模型包解压缩的目录";
                if (pathdlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return(null);
                }
                string savepath = pathdlg.SelectedPath;

                //在temp目录中创建rfdi目录
                string rfdiDir = Path.Combine(Path.GetTempPath(), "rfdi_nodeExport");
                if (Directory.Exists(rfdiDir))  //如果存在,删除当前文件夹
                {
                    Directory.Delete(rfdiDir, true);
                }
                Directory.CreateDirectory(rfdiDir);

                using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(dlg.FileName))
                {
                    zip.ExtractAll(rfdiDir);
                }
                string[] subdirs = Directory.GetDirectories(rfdiDir);

                string extractdir = Path.Combine(savepath, Path.GetFileName(subdirs[0]));
                int    index      = 1;
                while (Directory.Exists(extractdir))
                {
                    extractdir = Path.Combine(savepath, Path.GetFileName(subdirs[0]) + index);
                    index++;
                }
                Directory.CreateDirectory(extractdir);
                DirectoryCopy(subdirs[0], extractdir);
                Directory.Delete(rfdiDir, true);

                return(CreateMethodNodeFromDirectory(extractdir));
            }
            catch (Exception)
            {
                return(null);
            }
        }
        private void DeployPackage(string targetDir)
        {
            // Get the zip file name.
            string outputZip = this.project.GetOutputAssembly(this.ConfigName);

            // MPF is lazy and hardcodes ".exe" to the output assembly. We hardcode it to zip instead.
            outputZip = outputZip.Substring(0, outputZip.Length - 4) + ".zip";

            // Extract the contents.
            var file = new Ionic.Zip.ZipFile(outputZip);

            file.ExtractAll(targetDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
        }
Ejemplo n.º 18
0
        public void ExtractEmbededZipFileContentToFolder(string resourceName, System.Reflection.Assembly assembly, string destinationFolder)
        {
            var zipFileName = this.GetTempFileName();

            this.ExtractEmbededResourceToFile(resourceName, assembly, zipFileName, null);

            using (Ionic.Zip.ZipFile zipFile = Ionic.Zip.ZipFile.Read(zipFileName))
            {
                zipFile.ExtractAll(destinationFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            }

            this.DeleteFile(zipFileName);
        }
Ejemplo n.º 19
0
 public static void DeCompress(string fileName, string saveDir)
 {
     fileName = fileName.ToLower();
     if (fileName.EndsWith(".rar"))
     {
         RarHelper.UnCompressRar(fileName, saveDir);
     }
     else
     {
         using (var zip = new Ionic.Zip.ZipFile(fileName, Encoding.Default))
         {
             zip.ExtractAll(saveDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
         }
     }
 }
Ejemplo n.º 20
0
 private void ExtractZipFile(string zipFileLocation, string destination)
 {
     try
     {
         using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileLocation))
         {
             zip.ExtractAll(destination);
         }
     }
     catch (Exception e)
     {
         MessageBox.Show("That's not an archive file I can extract.\nIt might be the wrong format, or maybe just corrupted.\nTry ReDownloading the file!", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
 }
Ejemplo n.º 21
0
        public string InstallService()
        {
            var input = JsonConvert.DeserializeObject <InstallServiceDto>(SessionIdentity.ConnectionSecurity.Decrypt(Request.Content.ReadAsStringAsync().Result));

            // Start program
            try
            {
                var byteArrayDes = JsonConvert.DeserializeObject <List <int> >(input.ByteArray);
                SessionIdentity.Namespace = input.Namespace;
                SessionIdentity.ClassName = input.ClassName;
                var newArray = new byte[byteArrayDes.Count];
                int i        = 0;
                byteArrayDes.ForEach(x =>
                {
                    newArray[i++] = (byte)x;
                });
                if (File.Exists("install.zip"))
                {
                    File.Delete("install.zip");
                }
                if (Directory.Exists("process"))
                {
                    clearFolder("process");
                }
                File.WriteAllBytes("install.zip", newArray);
                using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read("install.zip"))
                {
                    zip1.ExtractAll("process",
                                    Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }
                assembly = Assembly.LoadFrom("process/" + input.Namespace + ".dll");
                type     = assembly.GetType(input.Namespace + "." + input.ClassName);
                if (type != null)
                {
                    methodInfo = type.GetMethod("RunFromMicroservice");
                    return("Ok");
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }


            return("No");
        }
Ejemplo n.º 22
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.º 23
0
 public void UnpackClick(CommandsForLeftSide commandsForLeftSide, CommandsForRightSide commandsForRightSide, ref TextBox textBox, ref ListView SideRightList, ref ListView SideLeftList)
 {
     if (commandsForLeftSide.IsVisibleLeft)
     {
         if (IsFull)
         {
             var     path = commandsForLeftSide.Path + commandsForLeftSide.ItemLeft;
             ZipFile zip  = new ZipFile(path);
             zip.ExtractAll(commandsForRightSide.Path);
             commandsForRightSide.ChangeListOfDirectories(commandsForRightSide.Path);
             SideRightList.ItemsSource = commandsForRightSide.Directories;
         }
         else
         {
             var item = commandsForLeftSide.ItemLeft;
             int pos  = commandsForLeftSide.ItemLeft.LastIndexOf("\\", StringComparison.CurrentCultureIgnoreCase);
             commandsForLeftSide.ItemLeft = commandsForLeftSide.ItemLeft.Substring(pos + 1);
             ZipFile zip = new ZipFile(item);
             zip.ExtractAll(commandsForRightSide.ItemRight);
         }
     }
     else
     {
         if (IsFull)
         {
             var     path = commandsForRightSide.Path + commandsForRightSide.ItemRight;
             ZipFile zip  = new ZipFile(path);
             zip.ExtractAll(commandsForLeftSide.Path);
             commandsForLeftSide.ChangeListOfDirectories(commandsForLeftSide.Path);
             SideLeftList.ItemsSource = commandsForLeftSide.Directories;
         }
         else
         {
             var item = commandsForRightSide.ItemRight;
             int pos  = commandsForRightSide.ItemRight.LastIndexOf("\\", StringComparison.CurrentCultureIgnoreCase);
             commandsForRightSide.ItemRight = commandsForRightSide.ItemRight.Substring(pos + 1);
             ZipFile zip = new ZipFile(item);
             zip.ExtractAll(commandsForLeftSide.ItemLeft);
         }
     }
 }
Ejemplo n.º 24
0
        private static void UpdatePluginsFromWeb()
        {
            var @lock = Program.ShutdownLock.GetLock();

            try
            {
                if (!Directory.Exists(Path.Combine(AppFolders.TempDir, "plugins_update")))
                {
                    Directory.CreateDirectory(Path.Combine(AppFolders.TempDir, "plugins_update"));
                }
                using (WebClient webClient = new WebClient())
                {
                    foreach (string pluginName in new DirectoryInfo(Settings2.Instance.PluginSourceFolder).GetDirectories().Select(l => l.Name))
                    {
                        try
                        {
                            log.Info($"UpdatePluginsFromWeb: updating '{pluginName}'");
                            var fileName = Path.Combine(AppFolders.TempDir, $"plugins_update\\{pluginName}.zip");
                            webClient.DownloadFile($"https://axio.name/axtools/plugins/{pluginName}.zip", fileName);
                            Directory.Delete(Path.Combine(Settings2.Instance.PluginSourceFolder, pluginName), true);
                            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(fileName, Encoding.UTF8))
                            {
                                zip.ExtractAll(Settings2.Instance.PluginSourceFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                            }
                            log.Info($"UpdatePluginsFromWeb: '{pluginName}' is updated");
                        }
                        catch (Exception ex)
                        {
                            log.Info($"Call to UpdatePluginsFromWeb caused non-critical error while processing '{pluginName}' plug-in: {ex.Message}");
                        }
                    }
                }
            }
            finally
            {
                Program.ShutdownLock.ReleaseLock(@lock);
            }
        }
Ejemplo n.º 25
0
        public static bool DecryptFile(string path, EncryptionArgv encArgv)
        {
            try
            {
                FileStream fs      = new FileStream(path, FileMode.Open, FileAccess.Read);
                byte[]     rawData = new byte[fs.Length];
                fs.Read(rawData, 0, (int)fs.Length);
                fs.Close();
                fs.Dispose();

                Headers header        = new Headers();
                byte[]  decryptedData = null;
                byte[]  MD5Hash       = null;
                bool    ffcFile       = false;
                string  fileName      = Path.GetFileNameWithoutExtension(path);
                string  directoryName = Path.GetDirectoryName(path);
                if (encArgv.OutPath != "")
                {
                    directoryName = encArgv.OutPath;
                }

                // Check header
                if (header.CheckFFCFile(ref rawData))
                {
                    if (!(header.MatchPassword(encArgv.PrivatePassword, rawData)))
                    {
                        Console.WriteLine("\r\n    - Failed: Password do not match");
                        return(false);
                    }

                    if (!(header.MakeEncArgv(ref rawData, ref encArgv)))
                    {
                        Console.WriteLine("\r\n    - Failed: converting headers");
                        return(false);
                    }

                    ffcFile = true;
                    if (encArgv.NeedRestoreFilePath)
                    {
                        try
                        {
                            Directory.CreateDirectory(encArgv.EncFileInfo.FileDirectory);
                        }
                        catch { }

                        if (Directory.Exists(encArgv.EncFileInfo.FileDirectory))
                        {
                            directoryName = encArgv.EncFileInfo.FileDirectory;
                        }
                        else
                        {
                            Console.Write("\r\n    - Warning: Could not create directory: '" + encArgv.EncFileInfo.FileDirectory + "' - ");
                        }
                    }

                    if (encArgv.NeedRestoreInfo)
                    {
                        fileName = encArgv.EncFileInfo.FileName;
                    }
                    else
                    {
                        fileName = fileName + encArgv.EncFileInfo.FileExtension;
                    }

                    decryptedData = DecryptData(ref encArgv.EncFileInfo.FileData, encArgv.PrivatePassword, encArgv.AesInfo);

                    rawData = null;
                    header  = null;

                    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                    MD5Hash = md5.ComputeHash(decryptedData);
                    md5.Dispose();
                    md5 = null;

                    if (!((IStructuralEquatable)MD5Hash).Equals(encArgv.EncFileInfo.MD5FileHash, StructuralComparisons.StructuralEqualityComparer))
                    {
                        Console.WriteLine("\r\n    - Failed: Data do not match");
                        return(false);
                    }
                }
                else
                {
                    ffcFile       = false;
                    header        = null;
                    decryptedData = DecryptData(ref rawData, encArgv.PrivatePassword, encArgv.AesInfo);
                    rawData       = null;
                }

                string createPath = directoryName + "\\" + fileName;

                // Write decrypted data
                if (encArgv.ForceWrite & File.Exists(createPath))
                {
                    Console.Write("\r\n    - Warning: File Exists. Forced writing data... - ");
                    FileInfo file = new FileInfo(createPath);
                    if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        file.Attributes = FileAttributes.Normal;
                    }
                }
                // Check file exists
                else if (File.Exists(createPath))
                {
                    createPath = IOObject.RenameFile(createPath);
                    Console.Write("\r\n    - Warning: File Exists. Renamed file: " + Path.GetFileName(createPath) + " - ");
                }

                using (FileStream fsb = new FileStream(createPath, FileMode.Create, FileAccess.Write))
                {
                    fsb.Write(decryptedData, 0, decryptedData.Length);
                }
                decryptedData = null;

                // Compressed Zip
                if (encArgv.EncFileInfo.IsCompressedZipFile)
                {
                    string folderPath = "";
                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(createPath, Encoding.UTF8))
                    {
                        folderPath = Path.GetDirectoryName(createPath) + "\\" + zip.Comment;
                        Directory.CreateDirectory(folderPath);
                        if (encArgv.ForceWrite)
                        {
                            zip.ExtractAll(folderPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                        }
                        else
                        {
                            try
                            {
                                zip.ExtractAll(folderPath, Ionic.Zip.ExtractExistingFileAction.Throw);
                            }
                            catch
                            {
                                folderPath = IOObject.RenameFolder(folderPath);
                                zip.ExtractAll(folderPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                            }
                        }
                    }
                    File.Delete(createPath);
                }

                // Add file attributes
                if (ffcFile & encArgv.IsOriginalFile & encArgv.NeedRestoreInfo & !encArgv.EncFileInfo.IsCompressedZipFile)
                {
                    FileInfo fi = new FileInfo(createPath);
                    fi.CreationTime   = encArgv.EncFileInfo.CreationTime;
                    fi.LastWriteTime  = encArgv.EncFileInfo.LastWriteTime;
                    fi.LastAccessTime = encArgv.EncFileInfo.LastAccessTime;
                    if (encArgv.EncFileInfo.FileNotContentIndexed)
                    {
                        fi.Attributes |= FileAttributes.NotContentIndexed;
                    }
                    if (encArgv.EncFileInfo.FileOffline)
                    {
                        fi.Attributes |= FileAttributes.Offline;
                    }
                    if (encArgv.EncFileInfo.FileArchive)
                    {
                        fi.Attributes |= FileAttributes.Archive;
                    }
                    if (encArgv.EncFileInfo.FileHidden)
                    {
                        fi.Attributes |= FileAttributes.Hidden;
                    }
                    if (encArgv.EncFileInfo.FileSystem)
                    {
                        fi.Attributes |= FileAttributes.System;
                    }
                    if (encArgv.EncFileInfo.FileReadOnly)
                    {
                        fi.Attributes |= FileAttributes.ReadOnly;
                    }
                    fi = null;
                }

                // Delete file
                if (encArgv.NeedDeleteFile)
                {
                    IOObject.DeleteFileEx(path, encArgv.NeedFillDeleteFile);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\r\n    - Failed: " + ex.Message);
                return(false);
            }
        }
Ejemplo n.º 26
0
        private void btn_TrasferimentoArchivi_Click(object sender, RoutedEventArgs e)
        {
            //richiesta conferma
            Utilities u = new Utilities();

            if (MessageBoxResult.No == u.ConfermaTrasferimentoArchivio())
            {
                return;
            }

            //nuovo percorso
            string nuovaCartella = u.sys_OpenDirectoryDialog();

            if (nuovaCartella == "")
            {
                return;
            }


            //controllo percorso
            DirectoryInfo destinazione = new DirectoryInfo(nuovaCartella);

            if (!destinazione.Exists)
            {
                return;
            }

            DirectoryInfo origine    = new DirectoryInfo(App.AppDataFolder);
            string        tmpzipfile = App.AppTempFolder + "\\zip" + Guid.NewGuid().ToString();

            //Sposto archivio
            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
            zip.AddDirectory(origine.FullName);
            zip.Save(tmpzipfile);
            zip.ExtractAll(destinazione.FullName, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);

            //Interfaccia
            textBoxArchivioRemotoPath.Text      = destinazione.FullName;
            radioButtonArchivioRemoto.IsChecked = true;

            //Configuro applicazione
            App.AppSetupTipoGestioneArchivio = App.TipoGestioneArchivio.Remoto;
            App.AppDataFolder         = destinazione.FullName;
            App.AppPathArchivioRemoto = App.AppDataFolder;

            //salvo nuova configurazione
            GestioneLicenza l = new GestioneLicenza();

            l.SalvaInfoDataUltimoUtilizzo();

            //Configuro path applicativi
            u.ConfiguraPercorsi();


            MasterFile.ForceRecreate();

            //ricarico main window
            ((MainWindow)(this.Owner)).ReloadMainWindow();

            //interfaccia
            //modifile all'interfaccia dell'ultimo momento
            radioButtonArchivioLocale.IsEnabled      = false;
            radioButtonArchivioRemoto.IsEnabled      = false;
            buttonSelezionaArchivioRemoto.IsEnabled  = false;
            buttonSelezionaArchivioRemoto.Visibility = System.Windows.Visibility.Collapsed;
            buttonApplica.IsEnabled                  = false;
            btn_TrasferimentoArchivi.IsEnabled       = App.AppSetupTipoGestioneArchivio == App.TipoGestioneArchivio.Locale;
            btn_TrasferimentoArchiviLocale.IsEnabled = App.AppSetupTipoGestioneArchivio == App.TipoGestioneArchivio.Remoto;
            MessageBox.Show("Trasferimento archivio avvenuto con successo.");
        }
Ejemplo n.º 27
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.º 28
0
 private void UnZipToDirectory(string dir)
 {
     using (var tempZipFile = new TempFile())
     {
         File.WriteAllBytes(tempZipFile.Path, Resources.ShoppingList);
         using (var zip = new Ionic.Zip.ZipFile(tempZipFile.Path))
         {
             Directory.CreateDirectory(dir);
             zip.ExtractAll(dir);
         }
     }
 }
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
        /// <summary>
        /// Lors de la fin d'un téléchargement
        /// </summary>
        /// <param name="d">Download qui termine</param>
        public static void downloader_OnDownloadComplete(Download d)
        {
            // Trucs a faire apres le dl, genre verifs md5, decompression archive etc etc...
            switch (d.type)
            {
                case "package":

                    //decompression
                    try
                    {
                        fUpdater.SetPackage(d.package);
                        fUpdater.SetLabel("Décompression de " + Path.GetFileName(d.DownloadFile));

                        Ionic.Zip.ZipFile zipF = new Ionic.Zip.ZipFile(d.DownloadFile);
                        zipF.ExtractAll(Paths.GetLocalPackagesDir());
                    }
                    catch (Ionic.Zip.ZipException Z)
                    {
                        Console.WriteLine("ERREUR ZIP !");
                        Console.WriteLine(Z.Message);
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine("ERREUR ZIP INCONNUE !");
                        Console.WriteLine(E.Message);
                    }

                    // verif MAj ?

                    //ClientPackages.Get();
                    //Program.DoWork(false, true);
                    //

                    //todo: virer le .zip si ok ou si md5 incorrect

                    break;

                case "file":
                    //todo: verif MD5 ?
                    break;

                default:
                    //Inconnu ???
                    break;

            }
        }
Ejemplo n.º 31
0
        private void Backup_Restore(string fileName, string parameters)
        {
            try
            {
                if (IsInstallDefault)
                {
                    if (!System.IO.File.Exists(CommonCS.DefaultValues.backupPath))
                    {
                        lblMessage.Text = "فایل مورد نظر یافت نشد.";
                        return;
                    }

                    else
                    {
                        if (System.IO.File.Exists(CommonCS.DefaultValues.RestorePath))
                        {
                            System.IO.File.Delete(CommonCS.DefaultValues.RestorePath);
                        }
                    }
                }
            }
            catch (Exception)
            {
                lblMessage.Text = "خطا در نصب پایگاه داده";
                return;
            }


            string error = null;

            thrdPrgress = new Thread(new ThreadStart(startProgressbar));

            int ExitCode;
            ProcessStartInfo _processInfo = null;
            Process          _process     = null;

            try
            {
                thrdPrgress.Start();

                if (IsInstallDefault)
                {
                    //unzip
                    Ionic.Zip.ZipFile oZipFile = new Ionic.Zip.ZipFile(CommonCS.DefaultValues.backupPath);
                    oZipFile.ExtractAll(CommonCS.DefaultValues.UnzipPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }

                _processInfo = new ProcessStartInfo(fileName, parameters);
                _processInfo.CreateNoWindow         = true;
                _processInfo.UseShellExecute        = false;
                _processInfo.RedirectStandardOutput = true;
                _processInfo.RedirectStandardError  = true;
                _processInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                _processInfo.LoadUserProfile        = true;

                _process = Process.Start(_processInfo);
                error    = _process.StandardError.ReadToEnd();
                _process.WaitForExit();
                ExitCode = _process.ExitCode;
                _process.Close();

                prgBackupRestore.Value = 100;
                prgBottom.Value        = 100;

                thrdPrgress.Abort();
                System.Threading.Thread.Sleep(500);
                btnStart.Enabled = true;

                if (error != "")
                {
                    lblMessage.Text = error;
                }

                if (!IsInstallDefault)
                {
                    grpBackRestore.Enabled = true;
                }

                //refresh list file
                DirectoryInfo dir = new DirectoryInfo(backupLocation);
                showDirectoryFiles(dir);

                if (rdRestore.Checked)
                {
                    if (IsAttachDataBase())
                    {
                        lblMessage.Text = "عملیات با موفقیت انجام شد.";
                    }
                    else
                    {
                        lblMessage.Text = "خطا در انجام عملیات.";
                    }
                }
                else
                {
                    lblMessage.Text = "عملیات با موفقیت انجام شد.";
                }

                //lblMessage.Text = "عملیات با موفقیت انجام شد.";
                //ParentForm.Close();
            }
            catch (IOException ex)
            {
                _process.Close();
                thrdPrgress.Abort();
                lblMessage.Text = ex.ToString() + "\n" + error;
            }
        }
Ejemplo n.º 32
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.º 33
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.º 34
0
        /// <summary>
        /// Inverse of <see cref="StoreToTempStorage"/>.
        /// Copies a block of files from a temp storage location given by a temp storage node and game to local storage rooted at the given root dir. 
        /// If the temp manifest for this block is found locally, the copy is skipped, as we assume this is the same machine that created the temp storage and the files are still there.
        /// </summary>
        /// <param name="TempStorageNodeInfo">Node info descibing the block of temp storage (essentially used to identify a subdirectory insides the game's temp storage folder).</param>
        /// <param name="WasLocal">upon return, this parameter is set to true if the temp manifest was found locally and the copy was avoided.</param>
        /// <param name="GameName">game name to determine the temp storage folder for. Empty is equivalent to "UE4".</param>
        /// <param name="RootDir">Folder that all the retrieved files should be rooted from. If null or empty, CmdEnv.LocalRoot is used.</param>
        /// <returns>List of fully qualified paths to all the files that were retrieved. This is returned even if we skip the copy (set WasLocal = true) .</returns>
        public static List<string> RetrieveFromTempStorage(TempStorageNodeInfo TempStorageNodeInfo, out bool WasLocal, string GameName, string RootDir)
        {
            using (var TelemetryStopwatch = new TelemetryStopwatch("RetrieveFromTempStorage"))
            {
                // use LocalRoot if one is not specified
                if (String.IsNullOrEmpty(RootDir))
                {
                    RootDir = CommandUtils.CmdEnv.LocalRoot;
                }

                // First see if the local manifest is there.
                // If it is, then we must be on the same node as the one that originally created the temp storage.
                // In that case, we just verify all the files exist as described in the manifest and use that.
                // If there was any tampering, abort immediately because we never accept tampering, and it signifies a build problem.
                var LocalManifest = LocalTempStorageManifestFilename(TempStorageNodeInfo);
                if (CommandUtils.FileExists_NoExceptions(LocalManifest))
                {
                    CommandUtils.LogVerbose("Found local manifest {0}", LocalManifest);
                    var Local = TempStorageManifest.Load(LocalManifest);
                    var Files = Local.GetFiles(RootDir);
                    var LocalTest = TempStorageManifest.Create(Files, RootDir);
                    if (!Local.Compare(LocalTest))
                    {
                        throw new AutomationException("Local files in manifest {0} were tampered with.", LocalManifest);
                    }
                    WasLocal = true;
                    TelemetryStopwatch.Finish(string.Format("RetrieveFromTempStorage.{0}.{1}.{2}.Local.{3}.{4}.{5}", Files.Count, Local.GetTotalSize(), 0L, 0L, 0L, TempStorageNodeInfo.NodeStorageName));
                    return Files;
                }
                WasLocal = false;

                // We couldn't find the node storage locally, so get it from the shared location.
                var BlockPath = SharedTempStorageDirectory(TempStorageNodeInfo, GameName);

                CommandUtils.LogVerbose("Attempting to retrieve from {0}", BlockPath);
                if (!CommandUtils.DirectoryExists_NoExceptions(BlockPath))
                {
                    throw new AutomationException("Storage Block Does Not Exists! {0}", BlockPath);
                }
                var SharedManifest = SharedTempStorageManifestFilename(TempStorageNodeInfo, GameName);
                InternalUtils.Robust_FileExists(SharedManifest, "Storage Block Manifest Does Not Exists! {0}");

                var Shared = TempStorageManifest.Load(SharedManifest);
                var SharedFiles = Shared.GetFiles(BlockPath, !bZipTempStorage);

                // We know the source files exist and are under RootDir because we created the manifest, which verifies it.
                // Now create the list of target files
                var DestFiles = SharedFiles.Select(Filename => CommandUtils.MakeRerootedFilePath(Filename, BlockPath, RootDir)).ToList();

                long ZipFileSize = 0L;
                long CopyTimeMS = 0L;
                long UnzipTimeMS = 0L;
                if (bZipTempStorage)
                {
                    var LocalZipFilename = Path.ChangeExtension(LocalManifest, "zip");
                    var SharedZipFilename = Path.ChangeExtension(SharedManifest, "zip");
                    if (!CommandUtils.FileExists(SharedZipFilename))
                    {
                        throw new AutomationException("Storage block zip file does not exist! {0}", SharedZipFilename);
                    }
                    var CopyTimer = DateTimeStopwatch.Start();
                    InternalUtils.Robust_CopyFile(SharedZipFilename, LocalZipFilename);
                    CopyTimeMS = (long)CopyTimer.ElapsedTime.TotalMilliseconds;
                    ZipFileSize = new FileInfo(LocalZipFilename).Length;

                    var UnzipTimer = DateTimeStopwatch.Start();
                    using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile(LocalZipFilename))
                    {
                        Zip.ExtractAll(RootDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    }
                    CommandUtils.DeleteFile(LocalZipFilename);
                    UnzipTimeMS = (long)UnzipTimer.ElapsedTime.TotalMilliseconds;
                }
                else
                {
                    var CopyTimer = DateTimeStopwatch.Start();
                    // If the local file already exists, it will be overwritten.
                    foreach (var DestFile in DestFiles)
                    {
                        if (CommandUtils.FileExists_NoExceptions(true, DestFile))
                        {
                            CommandUtils.LogVerbose("Dest file {0} already exists, deleting and overwriting", DestFile);
                            CommandUtils.DeleteFile(DestFile);
                        }
                    }

                    // Do the threaded copy to the local file system.
                    CommandUtils.ThreadedCopyFiles(SharedFiles, DestFiles, ThreadsToCopyWith());
                    CopyTimeMS = (long)CopyTimer.ElapsedTime.TotalMilliseconds;
                }

                // Handle unix permissions/chmod issues.
                if (UnrealBuildTool.Utils.IsRunningOnMono)
                {
                    foreach (string DestFile in DestFiles)
                    {
                        CommandUtils.FixUnixFilePermissions(DestFile);
                    }
                }
                var NewLocal = SaveLocalTempStorageManifest(RootDir, TempStorageNodeInfo, DestFiles);
                // Now compare the created local files to ensure their attributes match the one we copied from the network.
                if (!NewLocal.Compare(Shared))
                {
                    // we will rename this so it can't be used, but leave it around for inspection
                    CommandUtils.RenameFile_NoExceptions(LocalManifest, LocalManifest + ".broken");
                    throw new AutomationException("Shared and Local manifest mismatch.");
                }
                TelemetryStopwatch.Finish(string.Format("RetrieveFromTempStorage.{0}.{1}.{2}.Remote.{3}.{4}.{5}", DestFiles.Count, Shared.GetTotalSize(), ZipFileSize, CopyTimeMS, UnzipTimeMS, TempStorageNodeInfo.NodeStorageName));
                return DestFiles;
            }
        }
Ejemplo n.º 35
0
        private void DeployPackage( string targetDir )
        {
            // Get the zip file name.
            string outputZip = this.project.GetOutputAssembly( this.ConfigName );

            // MPF is lazy and hardcodes ".exe" to the output assembly. We hardcode it to zip instead.
            outputZip = outputZip.Substring( 0, outputZip.Length - 4 ) + ".zip";

            // Extract the contents.
            var file = new Ionic.Zip.ZipFile( outputZip );
            file.ExtractAll( targetDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently );
        }
Ejemplo n.º 36
0
        private void ProcessingFile()
        {
            string localOCRPath = @"C:\Avago.ATF.Common\OCR\";

            do
            {
                Thread.Sleep(2000);
            } while (!File.Exists(ResultZipPath));
            Thread.Sleep(1000);

            if (!Directory.Exists(localOCRPath + fileNameWithoutExtension))
            {
                Directory.CreateDirectory(localOCRPath + fileNameWithoutExtension);
            }

            //Move the original result zip file from @"C:\Avago.ATF.Common\Result.BackUp\ to @"C:\Avago.ATF.Common\OCR\:
            File.Move(ResultZipPath, localOCRPath + fileNameWithoutExtension + @"\" + ResultZipFileName);

            if (debug)
            {
                MessageBox.Show("Before Unzip Ori Clotho Result File at " + localOCRPath + "fileName");
            }
            using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(localOCRPath + fileNameWithoutExtension + @"\" + ResultZipFileName))
            {
                zip1.ExtractAll(localOCRPath + fileNameWithoutExtension + @"\",
                                Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
            }

            string[] resultFiles = Directory.GetFiles(localOCRPath + fileNameWithoutExtension);

            if (debug)
            {
                foreach (string file in resultFiles)
                {
                    MessageBox.Show("File length: " + resultFiles.Length.ToString() + "\r\n" + file);
                }
            }

            if (resultFiles.Length >= 3)
            {
                File.Delete(localOCRPath + fileNameWithoutExtension + @"\" + ResultZipFileName);  //delete original result zip file
                if (debug)
                {
                    MessageBox.Show("Original Zip file deleted.");
                }
                File.Copy(localOCRPath + ResultFileName, localOCRPath + fileNameWithoutExtension + @"\" + ResultFileName, true);  //copy OCR result file and ovewrite
                File.Delete(localOCRPath + ResultFileName);
                Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
                foreach (string file in resultFiles)
                {
                    string fileName = Path.GetFileName(file);
                    if (!(fileName.Contains(".exe") || fileName.Contains(".zip")))
                    {
                        if (debug)
                        {
                            MessageBox.Show("File to be zipped: " + fileName + "\r\n At: " + localOCRPath + fileNameWithoutExtension + @"\");
                        }

                        zip.AddFile(file, "");
                    }
                }

                zip.Save(localOCRPath + fileNameWithoutExtension + @"\" + fileNameWithoutExtension + ".zip");
                if (debug)
                {
                    MessageBox.Show("OCR result file successfully zipped at " + localOCRPath + fileNameWithoutExtension + @"\" + fileNameWithoutExtension + ".zip");
                }
            }
            else
            {
                MessageBox.Show("Unzip Clotho result file contain less that 3 files could be missing result.csv, summary.txt or OriClothoResult.zip file.");
            }

            //Move back Result zip file(contain OCR data) back to the Result.BackUp folder
            System.IO.File.Move(localOCRPath + fileNameWithoutExtension + @"\" + fileNameWithoutExtension + ".zip", ResultZipPath);
            if (debug)
            {
                MessageBox.Show("OCR zipped file successfully moved to C:\\Avago.ATF.Common\\Results.Backup!");
            }

            MessageBox.Show("OCR Process Completed!!");
        }
Ejemplo n.º 37
0
        public override int DebugLaunch( uint grfLaunch )
        {
            CCITracing.TraceCall();

            var clientApp = new MFilesAPI.MFilesClientApplication();
            var apiVersion = clientApp.GetAPIVersion().Display;
            MFilesAPI.Vault vault = null;

            var vaultName = GetConfigurationProperty( "TestVault", true );
            MFilesAPI.VaultConnection vaultConnection;
            try
            {
                vaultConnection = clientApp.GetVaultConnection( vaultName );
            }
            catch
            {
                throw new Exception( "The document vault '" + vaultName + "' was not found." );
            }
            string vaultGuid = vaultConnection.GetGUID();

            // Get the M-Files install directory from the registry.
            var hklm64 = RegistryKey.OpenBaseKey( RegistryHive.LocalMachine, RegistryView.Registry64 );
            var mfKey = hklm64.OpenSubKey( @"Software\Motive\M-Files\" + apiVersion );
            var installDir = (string)mfKey.GetValue( "InstallDir" );
            mfKey.Close();
            hklm64.Close();

            // Log out to free the current application.
            try
            {
                vault = clientApp.BindToVault( vaultName, IntPtr.Zero, false, true );
                if( vault != null ) vault.LogOutWithDialogs( IntPtr.Zero );
            }
            catch { }

            // Deploy the application.
            var relativePath = string.Format( @"Client\Apps\{0}\sysapps\{1}",
                vaultGuid, this.project.GetProjectProperty( "Name" ) ?? "unnamed" );
            var targetDir = Path.Combine( installDir, relativePath );

            // If the directory exists, remove it so there's no residue files left.
            if( Directory.Exists( targetDir ) ) { Directory.Delete( targetDir, true ); }
            Directory.CreateDirectory( targetDir );

            // Extract the Zip contents to the target directory.
            var outputZip = this.project.GetOutputAssembly( this.ConfigName );

            // MPF is lazy and hardcodes ".exe" to the output assembly. We hardcode it to zip instead.
            outputZip = outputZip.Substring( 0, outputZip.Length - 4 ) + ".zip";

            var file = new Ionic.Zip.ZipFile( outputZip );
            file.ExtractAll( targetDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently );

            var launchMode = ( GetConfigurationProperty( "LaunchMode", false ) ?? "" ).ToLowerInvariant();
            vault = clientApp.BindToVault( vaultName, IntPtr.Zero, true, false );
            if( launchMode == "powershell" )
            {
                var builtInState = InitialSessionState.CreateDefault();
                builtInState.Variables.Add( new SessionStateVariableEntry(
                    "vaultName", vaultName, "Name of the vault used for testing." ) );
                builtInState.Variables.Add( new SessionStateVariableEntry(
                    "vault", vault, "M-Files Vault" ) );
                Runspace runspace = RunspaceFactory.CreateRunspace( builtInState );
                runspace.Open();
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript( GetConfigurationProperty( "LaunchPSScript", false ) ?? "" );
                pipeline.Invoke();
                runspace.Close();
            }
            else
            {
                var mfilesPath =
                    clientApp.GetDriveLetter() + ":\\" +
                    vaultName + "\\" +
                    GetConfigurationProperty( "LaunchMFilesPath", false );

                try
                {
                    // We need to log in first - otherwise explorer.exe can't find the folders.
                    Process.Start( "explorer.exe", string.Format( "\"{0}\"", mfilesPath ) );
                }
                catch { }
            }

            return VSConstants.S_OK;
        }
Ejemplo n.º 38
0
        private void CheckUpdate()
        {
            string str3 = "";
            if (NetworkInterface.GetIsNetworkAvailable() == false)
            {
                try
                {
                    str3 = new WebClient().DownloadString("http://www.xxxthedartkprogramerxxx.net//Update/PeXploit/Update.txt");
                    if (appversion == str3)
                    {
                        updateavaialable = false;

                    }
                    else
                    {
                        updateavaialable = true;
                    }
                }
                catch
                {
                    updateavaialable = false;
                }
            }
            if (updateavaialable == true)
            {
                Welcome.INFO = ("Update Found");
                DialogResult result = MessageBox.Show("Update Is Avaialbe Do You Want To Download It ?", "Update Found", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (DialogResult.Yes == result)
                {
                    Welcome.INFO = ("Downloading...");
                    this.Hide();
                    Download_WIndow dw = new Download_WIndow();
                    dw.url = "http://www.xxxthedartkprogramerxxx.net//Download/PeXploit.zip";
                    dw.ShowDialog();
                    this.Show();
                    Thread.Sleep(1000);
                    if (File.Exists(Application.StartupPath + "\\PeXploit.zip"))
                    {
                        this.notifyIcon1.ShowBalloonTip(0x7d0, "Extracting", "Extracting Update", ToolTipIcon.Info);
                        Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Application.StartupPath + @"\Pexploit.zip");
                        zip.ExtractAll(Application.StartupPath + @"\");
                        Thread.Sleep(1000);
                        this.notifyIcon1.ShowBalloonTip(0x7d0, "Extracted", "Opening File", ToolTipIcon.Info);
                        MessageBox.Show("Mainually Delete The Old Files Thanks");
                        System.Diagnostics.Process.Start(Application.StartupPath + @"\PeXploit\PeXploit.exe");
                        Application.Exit();
                    }
                    File.Delete(Application.StartupPath + @"\Pexploit.zip");
                }
            }
            else
            {
                Welcome.INFO = ("You Have The Latest Verion Of PeXploit");
            }
        }
Ejemplo n.º 39
-1
        /// <summary>
        /// Descomprime el archivo especificado en el directorio correspondiente
        /// </summary>
        /// <param name="fi"></param>
        public static string decompressFile(FileInfo fi)
        {
            string name = fi.Name.ToString().Replace(".pkg", "");

            FileInfo zipfile = fi.CopyTo(name + ".zip" ,true);
            string dirDestino = fi.Directory.FullName + @"\" + name;
            if(Directory.Exists(dirDestino)==true)
            {
                Directory.Delete(dirDestino,true);

            }
            Directory.CreateDirectory(dirDestino);

            fi.Delete();
            Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipfile.FullName);
            zf.ExtractAll(dirDestino,Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            Console.WriteLine("extraido aunque no lo parezca");
            return dirDestino;
            /*
            using (FileStream infile = fi.OpenRead())
            {
                string curfile = fi.FullName;
                string originalName = curfile.Remove(curfile.Length - fi.Extension.Length);

                using (FileStream outfile = File.Create(originalName))
                {

                    using (GZipStream decompress = new GZipStream(infile, CompressionMode.Decompress))
                    {
                        decompress.CopyTo(outfile);
                    }
                }
            }
                 */
        }