示例#1
0
        void DownloadCompleteCallback(object sender, AsyncCompletedEventArgs e)
        {
            DLStatus.Text = "Unpacking...";
            DLStatus.Update();
            string newFilePath = Path.Combine(extract_path, "85th SQN DCS Mod Sync.exe");
            string oldFilePath = Path.Combine(extract_path, "85th SQN DCS Mod Sync_old.exe");
            string newReadme   = Path.Combine(extract_path, "Readme.txt");
            string oldReadme   = Path.Combine(extract_path, "Readme_old.txt");

            if (File.Exists(newFilePath))
            {
                File.Move(newFilePath, oldFilePath);
            }
            if (File.Exists(newReadme))
            {
                File.Move(newReadme, oldReadme);
            }
            Thread.Sleep(1000);

            Unzipper.Zipextractor(download_file, extract_path);

            //string desktop_path = Path.Combine(Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Desktop\"), "85th SQN DCS Sync.lnk");
            string desktop_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "85th SQN DCS Sync.lnk");

            CreateShortcut(desktop_path, newFilePath, extract_path);

            DLStatus.Text = "Update is Complete. Click \"Restart\" to Restart the 85th SQN DCS Mod Sync Application.";
            DLStatus.Update();
            Btn_abort.Visible = false;
            Btn_done.Visible  = true;
        }
示例#2
0
        public ISet Read(FileInfo file)
        {
            if (file is null)
            {
                _logger.LogError("File {0} is null", file.Name);
                throw new ArgumentNullException(nameof(file), "File cannot be null");
            }
            if (!file.Exists)
            {
                _logger.LogError("File {0} does not exist", file.Name);
                throw new ArgumentException($"File {file.FullName} does not exist", nameof(file));
            }

            _extractionDirectory = Utils.GetUniqueTempDirectory();

            try
            {
                _logger.LogDebug("Extracting {0} to {1} directory...", file.Name, _extractionDirectory.FullName);
                Unzipper.Unzip(file, _extractionDirectory);
                _logger.LogDebug("Extraction complete");
                Workbook            workbook          = GetWorkbook();
                SharedStringTable   sharedStringTable = GetSharedStringTable();
                IEnumerable <Sheet> sheets            = GetSheets();
                Styles styles = GetStyles();
                throw new NotImplementedException();
            }
            finally
            {
                _extractionDirectory.Delete(recursive: true);
                _logger.LogDebug("Extraction directory {0} has been deleted.", _extractionDirectory.FullName);
            }
        }
示例#3
0
        public async Task UnzipperUnzzipsCorrectly()
        {
            var tested = new Unzipper();
            var result = await tested.UnzipAsync(Input);

            Assert.True(string.Equals(ExpectedFileContent, result.First().Value, StringComparison.InvariantCulture));
        }
示例#4
0
        public static void InstallMiner(MinerBackend minerBackend, string destinationFolder)
        {
            //support Windows and OS X for now, we'll go for Linux in the future
            if (OSVersionPlatform.GetConcretePlatform() == PlatformID.Unix)
            {
                throw new NotImplementedException();
            }

            string minerUrl = GetMinerDownloadUrl(minerBackend);

            if (!String.IsNullOrEmpty(minerUrl))
            {
                string minerDownloadFile = Path.Combine(Path.GetTempPath(), "miner.zip");
                File.Delete(minerDownloadFile);

                new WebClient().DownloadFile(new Uri(minerUrl), minerDownloadFile);
                try
                {
                    Unzipper.UnzipFileToFolder(minerDownloadFile, destinationFolder);
                }
                finally
                {
                    File.Delete(minerDownloadFile);
                }
            }
        }
示例#5
0
        private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
            }
            else
            {
                if (File.Exists("Windward.zip"))
                {
                    MessageBox.Show("Дальше последует установка, укажите место установки. Обратите внимание, что папка для игры будет создана автоматически!");
                    BrowseDirectory();
                }

                if (File.Exists("GameUpdate.zip"))
                {
                    MessageBox.Show("Файлы обновления скачаны! Далее последует распаковка.");
                }

                Unzipper.WorkerSupportsCancellation = true;
                Unzipper.RunWorkerAsync();
            }

            ProgressBar.Value = 0;
            Status.Text       = "0MB / 0MB    0%";

            CancelDownload.Enabled = false;
        }
示例#6
0
        public static void InstallMiner(string userAgent, AvailableMiner miner, string destinationFolder)
        {
            //support Windows and OS X for now, we'll go for Linux in the future
            if (OSVersionPlatform.GetConcretePlatform() == PlatformID.Unix)
            {
                throw new NotImplementedException();
            }

            string minerDownloadFile = Path.Combine(Path.GetTempPath(), "miner.zip");

            File.Delete(minerDownloadFile);

            WebClient webClient = new WebClient();

            webClient.Headers.Add("user-agent", userAgent);

            webClient.DownloadFile(new Uri(miner.Url), minerDownloadFile);
            try
            {
                //first delete the folder contents. this became necessary with cgminer 3.8.0 because
                //ck stopped shipping cgminer-nogpu.exe, which would leave an old executable behind
                //and gum up the works later (running an older exe to find the installed version)
                DeleteFolderContents(destinationFolder);

                Unzipper.UnzipFileToFolder(minerDownloadFile, destinationFolder);
            }
            finally
            {
                File.Delete(minerDownloadFile);
            }
        }
示例#7
0
        public void CancellationTokenCancells()
        {
            var tested            = new Unzipper();
            var cancelationSource = new CancellationTokenSource();

            cancelationSource.Cancel();
            Assert.Throws <AggregateException>(() => tested.UnzipAsync(Input, cancelationSource.Token).Result);
        }
示例#8
0
        private static void Unzip()
        {
            var zipFile   = @"C:\DATA\Zipper.zip";
            var unzipPath = @"C:\DATA\Zipper";

            var unzipper = new Unzipper(zipFile, unzipPath);

            unzipper.Unzip();
        }
示例#9
0
    void DownloadDone()

    {
        Unzipper unzipper = GameObject.Find("Unzipper").GetComponent <Unzipper>();

        unzipper.StartUrl = TempSavePath + Files[0];
        Debug.Log("Download Complete");
        i = 0;
        unzipper.CallUnzip();
    }
示例#10
0
		static void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
		{
			Stream s = e.Result;

			Unzipper unzip = new Unzipper(s);

			foreach (string filename in unzip.GetFileNamesInZip())
			{
				content.Add("/" + filename);
			}
			ready = true;
		}
        //public static void moveCache(string Des,List<string> DeleteList)
        //{

        //}
        //TODO
        public static void Unpackage(string sha1)
        {
            if (sha1List != null)
            {
                foreach (string element in sha1List)
                {
                    Unzipper.UnZip(@"\HikazeLauncher\download\" + sha1 + ".zip", @".\HikazeLauncher\temp");
                }
            }
            else
            {
                throw new NullReferenceException("sha1List Empty");
            }
        }
    public static void InstallDone() // dont change this
    {
        Unzipper Unzipper = GameObject.Find("Unzipper").GetComponent <Unzipper>();

        Unzipper.GetComponent <Unzipper>().InstallText.text = ("Afronden van installatie");
        DownloadGame   downloader     = GameObject.Find("Downloader").GetComponent <DownloadGame>();
        InstallOptions installoptions = GameObject.Find("InstallOptions").GetComponent <InstallOptions>();

        installoptions.ResetShortcut();
        downloader.GetComponent <DownloadGame>().CleanUp();
        Unzipper.GetComponent <Unzipper>().InstallText.text = ("Installatie Voltooid !");
        Gamebuttons.Enable();
        ExitButtonStatic.SetActive(true);
    }
示例#13
0
        public static void InstallMiner(string destinationFolder)
        {
            string minerUrl = GetMinerDownloadUrl();

            if (!String.IsNullOrEmpty(minerUrl))
            {
                string minerDownloadFile = Path.Combine(Path.GetTempPath(), "miner.zip");
                File.Delete(minerDownloadFile);

                new WebClient().DownloadFile(new Uri(minerUrl), minerDownloadFile);
                try
                {
                    //if the executing assembly is in "destinationFolder" then
                    string executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                    if (destinationFolder.ToLower().Contains(executingPath.ToLower()))
                    {
                        //extract MultiMiner.Update.exe from the zip file, run it, and exit
                        //use a random directory - rare user report of being unable to delete contents
                        //if an existing directory is reused
                        string temporaryFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

                        Unzipper.UnzipFileToFolder(minerDownloadFile, temporaryFolder);
                        string updaterFilePath  = Path.Combine(temporaryFolder, "MultiMiner.Update.exe");
                        string updaterArguments = String.Format("\"{0}\" \"{1}\"", minerDownloadFile, Assembly.GetEntryAssembly().Location);

                        ProcessStartInfo startInfo = new ProcessStartInfo(updaterFilePath, updaterArguments);
                        startInfo.CreateNoWindow = true;
                        startInfo.WindowStyle    = ProcessWindowStyle.Hidden;
                        Process.Start(startInfo);

                        Environment.Exit(0);

                        Directory.Delete(temporaryFolder, true);
                    }
                    else
                    {
                        //otherwise, unzip the archive directly into the folder
                        Unzipper.UnzipFileToFolder(minerDownloadFile, destinationFolder);
                    }
                }
                finally
                {
                    File.Delete(minerDownloadFile);
                }
            }
        }
示例#14
0
        private void Unzipper_DoWork(object sender, DoWorkEventArgs e)
        {
            {
                if (File.Exists(Path.Combine(Application.StartupPath, "Windward.zip")))
                {
                    using (ZipArchive file = ZipFile.OpenRead(Path.Combine(Application.StartupPath, "Windward.zip")))
                    {
                        string path     = GamePath.Text;
                        string filepath = Path.Combine(Application.StartupPath, "Windward.zip");
                        ZipExtension.ExtractToDirectory(file, GamePath.Text, true);

                        DialogResult answr = MessageBox.Show("Установка завершена! Хотите ли запустить игру?", "Запуск", MessageBoxButtons.YesNo);
                        if (answr == DialogResult.Yes)
                        {
                            Process.Start(Path.Combine(GamePath.Text, "Windward.exe"));
                        }
                    }

                    Unzipper.CancelAsync();
                }

                if (File.Exists(Path.Combine(Application.StartupPath, "update.zip")))
                {
                    using (ZipArchive file = ZipFile.OpenRead(Path.Combine(Application.StartupPath, "update.zip")))
                    {
                        string filepath = Path.Combine(Application.StartupPath, "update.zip");
                        string path     = Application.StartupPath;
                        ZipExtension.ExtractToDirectory(file, GamePath.Text, true);
                        MessageBox.Show("Сейчас программа будет перезапущена!");
                    }
                    Unzipper.CancelAsync();
                }

                if (File.Exists(Path.Combine(Application.StartupPath, "GameUpdate.zip")))
                {
                    using (ZipArchive file = ZipFile.OpenRead(Path.Combine(Application.StartupPath, "GameUpdate.zip")))
                    {
                        string filepath = Path.Combine(Application.StartupPath, "GameUpdate.zip");
                        string path     = GamePath.Text;
                        ZipExtension.ExtractToDirectory(file, path, true);
                    }
                    Unzipper.CancelAsync();
                }
            }
        }
示例#15
0
        public void Upload(byte[] zipFile)
        {
            var tempFolder = new TempFolderMaker();

            tempFolder.CreateNewTempFolder();

            var unzipper = new Unzipper(zipFile, tempFolder.PathToTemp);
            var path     = Directory.GetFiles(tempFolder.PathToTemp, "*.dll").First();
            var dllBytes = File.ReadAllBytes(path);

            var resolver = AddModule(dllBytes);

            ExtractFiles(tempFolder.PathToTemp, resolver.GetModuleManifest().Name);

            tempFolder.Delete();

            ModuleManager.ChangeModuleStatus(resolver.GetModuleManifest().Name, ModuleStatus.Enable);
        }
示例#16
0
        public ActionResult Index(HttpPostedFileBase file)
        {
            var fname = file.FileName;

            if (!fname.IsEmpty())
            {
                var path     = _productSourceFolder + "/uploads";
                var filename = Path.GetFileName(fname);
                var dest     = Path.Combine(path, filename);
                file.SaveAs(dest);
                Unzipper.unzipFile(dest, _productDetinationFolder);
            }

            var res = new JsonResult {
                Data = "uploaded"
            };

            return(res);
        }
示例#17
0
        public static ArrayList GetListFormJObject(string GamePath, string GameVersion, string OldGameVersion = null)
        {
            ArrayList LibList     = new ArrayList();
            JObject   ReadingJson = JsonHandler.ReadVersionJson(GamePath, GameVersion);

            if (ReadingJson["inheritsFrom"] != null)
            {
                LibList.AddRange(GetListFormJObject(GamePath, ReadingJson["inheritsFrom"].ToString(), GameVersion));
            }
            foreach (JToken lib in ReadingJson["libraries"])
            {
                if (lib["natives"] != null)
                {
                    if (lib["natives"]["windows"] != null)
                    {
                        if (string.IsNullOrEmpty(OldGameVersion))
                        {
                            Unzipper.UnZip(GamePath + @"\libraries\" + ConvertPackageToPath(lib["name"].ToString(), lib["natives"]["windows"].ToString()),
                                           GamePath + @"\versions\" + GameVersion + @"\" + GameVersion + @"-natives");
                        }
                        else
                        {
                            Unzipper.UnZip(GamePath + @"\libraries\" + ConvertPackageToPath(lib["name"].ToString(), lib["natives"]["windows"].ToString()),
                                           GamePath + @"\versions\" + OldGameVersion + @"\" + OldGameVersion + @"-natives");
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    LibList.Add(lib["name"]);
                }
            }
            return(LibList);
            //TODO:分流非Natives并解压Natives
        }
示例#18
0
        public void UnzipFileToFolder_Succeeds()
        {
            //arrange
            string       tempPath      = Path.GetTempPath();
            string       executingPath = Path.GetFullPath("App_Data");
            const string fileName      = "Unzipper-Test.zip";
            string       tempFilePath  = Path.Combine(tempPath, Path.ChangeExtension(fileName, "txt"));
            string       zipFilePath   = Path.Combine(executingPath, fileName);

            File.Delete(tempFilePath);

            //act
            Unzipper.UnzipFileToFolder(zipFilePath, tempPath);

            //assert
            Assert.IsTrue(File.Exists(zipFilePath));
            string contents = File.ReadAllText(tempFilePath);

            Assert.IsTrue(contents.Equals("Unzipper Test"));

            File.Delete(tempFilePath);
        }
示例#19
0
        void DownloadCompleteCallback(object sender, AsyncCompletedEventArgs e)
        {
            DLStatus.Text = "Unpacking...";
            DLStatus.Update();
            File.Move(extract_path + "DCS Mod Sync App v0.5.exe", extract_path + "DCS Mod Sync App v0.5_old.exe");
            File.Move(extract_path + "Readme v0.5.txt", extract_path + "Readme v0.5_old.txt");
            Thread.Sleep(1000);

            Unzipper.Zipextractor(download_file, extract_path);
            if (File.Exists(extract_path + "DCS Mod Sync App v0.5_old.exe"))
            {
                File.Delete(extract_path + "DCS Mod Sync App v0.5_old.exe");
            }
            if (File.Exists(extract_path + "Readme v0.5_old.txt"))
            {
                File.Delete(extract_path + "Readme v0.5_old.txt");
            }
            DLStatus.Text = "Update is Complete. Click \"Restart\" to Restart the 85th SQN DCS Mod Sync Application.";
            DLStatus.Update();
            Btn_abort.Visible = false;
            Btn_done.Visible  = true;
        }
示例#20
0
        static void Main(string[] args)
        {
            if (!ValidateArguments(args))
            {
                OutputProgramUsage();
                return;
            }

            string zipFilePath        = args[0];
            string executableFilePath = args[1];

            List <Process> runningProcesses = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(executableFilePath)).ToList();

            int       retryCount = 0;
            const int maxRetries = 20;

            while ((runningProcesses.Count > 0) && (retryCount < maxRetries))
            {
                Thread.Sleep(500);
                retryCount++;
                runningProcesses = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(executableFilePath)).ToList();
            }

            if (runningProcesses.Count > 0)
            {
                throw new Exception(String.Format("Timeout waiting for {0} to exit.", executableFilePath));
            }

            //let resources be freed
            Thread.Sleep(1000);

            //unzip the update
            Unzipper.UnzipFileToFolder(zipFilePath, Path.GetDirectoryName(executableFilePath));

            //relaunch the calling executable
            Process.Start(executableFilePath);
        }
示例#21
0
 public void PathWithoutExtension()
 {
     Unzipper.PathWithoutExtension("test.dll").Should().Be("test");
     Unzipper.PathWithoutExtension(@"wwwroot\test.txt").Should().Be(@"wwwroot\test");
     Unzipper.PathWithoutExtension(@"wwwroot\test.dll.dll").Should().Be(@"wwwroot\test");
 }
示例#22
0
 public void Unzip_WhenPasssedNull_ThrowsArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>(() => Unzipper.Unzip(null, _directoryThatExists));
     Assert.Throws <ArgumentNullException>(() => Unzipper.Unzip(_fileThatExists, null));
     Assert.Throws <ArgumentNullException>(() => Unzipper.Unzip(null, null));
 }
示例#23
0
        public void Unzip_WhenPassedNotExistingFile_ThrowsArgumentException()
        {
            FileInfo nonExistingFile = new FileInfo("c://this_surely_does_not/exists.xlsx");

            Assert.Throws <ArgumentException>(() => Unzipper.Unzip(nonExistingFile, _directoryThatExists));
        }
示例#24
0
        private static async Task Main(string[] args)
        {
            var project = new ProjectSettings();
            var logger  = new AggregateLogger(
                new ConsoleLogger {
                InfoColor = ConsoleColor.Gray, Formatter = (level, message) => $"{message}{Environment.NewLine}"
            },
                new FileLoggerBase(Path.Combine(project.WorkingDirectory.FullName, project.LogFileName)));
            var quotesDownloader = new StockQuotesDownloadService(new Downloader(), logger);

            Dictionary <string, string> unzippedStocks = null;

            logger.LogInfo($"Hello in {project.Name}. This test will read a directory and load it into Dictionary of deserialized stock quotes.");
            logger.LogInfo($"Would you like to download latest stocks from {project.QuotesDownloadUrl} ? (y/n)");
            var response = GetBinaryDecisionFromUser();

            byte[] rawBytes = null;
            if (response)
            {
                await quotesDownloader.Download(project);
            }
            else
            {
                logger.LogInfo("Would you like to read archive from disk? (y/n)");
                var      readArchive     = GetBinaryDecisionFromUser();
                FileInfo inputFile       = null;
                var      useExistingFile = false;
                if (readArchive)
                {
                    if (File.Exists(Path.Combine(project.WorkingDirectory.FullName, project.ArchiveFileName)))
                    {
                        logger.LogInfo($"Would you like to use existing archive from {project.WorkingDirectory.FullName}? (y/n)");
                        useExistingFile = GetBinaryDecisionFromUser();
                        if (useExistingFile)
                        {
                            inputFile = new FileInfo(Path.Combine(project.WorkingDirectory.FullName, project.ArchiveFileName));
                        }
                    }
                    if (!useExistingFile)
                    {
                        logger.LogInfo("Point to the archive:");
                        var userInput = GetPathToExistingFileFromUser(".zip");
                        inputFile = new FileInfo(userInput);
                    }

                    var fileReader     = new FileService();
                    var taskToReadFile = fileReader.ReadAllBytesAsync(inputFile.FullName);
                    var elapsed        = ShowSpinnerUntilTaskIsRunning(taskToReadFile);
                    rawBytes = await taskToReadFile;
                    logger.LogInfo($"Read {rawBytes.Length} bytes in {elapsed.AsTime()}");
                }
                else
                {
                    logger.LogInfo("Would you like to read unzipped files from disk? (y/n)");
                    var readFiles = GetBinaryDecisionFromUser();
                    if (readFiles)
                    {
                        var useFilesFromDefaultDir = false;
                        if (project.UnzippedFilesDirectory.Exists)
                        {
                            var filesFound = Directory.GetFiles(project.UnzippedFilesDirectory.FullName).Select(f => new FileInfo(f))
                                             .Count(f => f.Extension.EndsWith(project.QuotesFileExtension));
                            if (filesFound > 0)
                            {
                                logger.LogInfo($"Would you like to use {filesFound} files from {project.WorkingDirectory.FullName}? (y/n)");
                                useFilesFromDefaultDir = GetBinaryDecisionFromUser();
                                //if (useFilesFromDefaultDir)
                                //{
                                //    unzippedFilesDirectory = new DirectoryInfo(Path.Combine(workingDirectory.FullName, unzippedFilesDirectoryName));
                                //}
                            }
                        }
                        if (!useFilesFromDefaultDir)
                        {
                            logger.LogInfo("Not supported. Bye!");
                        }

                        var directoryStocksReader = new DirectoryService(new FileService());
                        var taskToRead            = directoryStocksReader.ReadTopDirectoryAsync(project.UnzippedFilesDirectory.FullName, $"*.{project.QuotesFileExtension}");
                        var elapsed = ShowSpinnerUntilTaskIsRunning(taskToRead);
                        unzippedStocks = await taskToRead;
                        logger.LogInfo($"Read {unzippedStocks.Count} stocks in {elapsed.AsTime()}");
                    }
                }
            }

            if (rawBytes?.Length > 0)
            {
                Console.WriteLine();
                var unzipper    = new Unzipper();
                var taskToUnzip = unzipper.UnzipAsync(rawBytes);
                var elapsed     = ShowSpinnerUntilTaskIsRunning(taskToUnzip);
                unzippedStocks = await taskToUnzip;
                logger.LogInfo($"Unzipped {unzippedStocks.Count} stocks in {elapsed.AsTime()}");
            }

            if (unzippedStocks?.Count > 0)
            {
                logger.LogInfo($"Deserializing {unzippedStocks.Count} stocks:");
                var bullkDeserializer = new StocksBulkDeserializer(new StocksDeserializer(new StockQuoteCsvClassMap()));
                var taskToDeserialize = bullkDeserializer.DeserializeAsync(unzippedStocks);
                var elapsed           = ShowSpinnerUntilTaskIsRunning(taskToDeserialize);
                var deserialized      = await taskToDeserialize;

                logger.LogInfo($"Deserialzed {unzippedStocks.Count} stocks in {elapsed.AsTime()}");

                logger.LogInfo($"Would you like to print some stock quotes? (y/n)");
                var decision = GetBinaryDecisionFromUser();
                if (decision)
                {
                    logger.LogInfo("Please enter the TICKER for the stock of your choice:");
                    var     line  = GetNonEmptyStringFromUser();
                    Company found = null;
                    while ((found = deserialized.FirstOrDefault(c => c.Ticker.Equals(line, StringComparison.InvariantCultureIgnoreCase))) == null)
                    {
                        logger.LogInfo($"{line} not found in the collection.");
                        line = GetNonEmptyStringFromUser();
                    }
                    found.Quotes.ForEach(q => Console.Out.WriteLine($"{q} Open: {q.Open} High: {q.High} Low: {q.Low} Close: {q.Close}"));
                }
                logger.LogInfo($"Would you like save files to {project.UnzippedFilesDirectory.FullName}? (y/n)");
                var saveFiles = GetBinaryDecisionFromUser();
                if (saveFiles)
                {
                    if (!project.UnzippedFilesDirectory.Exists)
                    {
                        project.UnzippedFilesDirectory.Create();
                    }
                    var tasksToSave = new List <Task>();
                    foreach (var stock in unzippedStocks)
                    {
                        tasksToSave.Add(File.WriteAllTextAsync(Path.Combine(project.UnzippedFilesDirectory.FullName, stock.Key), stock.Value));
                    }
                    var taskForSave       = Task.WhenAll(tasksToSave);
                    var elapsedWhenSaving = ShowSpinnerUntilTaskIsRunning(taskForSave);
                    logger.LogInfo($"Saved {unzippedStocks.Count} stocks to {project.UnzippedFilesDirectory.FullName} in {elapsed.AsTime()}");
                }
            }

            Console.WriteLine("press any key to exit...");
            Console.ReadKey();
        }
        public ActionResult UploadFile(HttpPostedFileBase[] files)
        {
            //Object FILES_FROM_UPLOAD = null;
            multipleTrue = false;
            var fi = files;

            if (fi != null)
            {
                System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/uploadedFiles/"));

                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }

                // Common FileNames object to use
                List <FileNames> fileNamesList = new List <FileNames>();

                Unzipper unzipper = new Unzipper(fileNamesList);// Declaring common obj

                try
                {
                    foreach (var file in files)
                    {
                        if (file.FileName != null)
                        {
                            string FILE_NAME = Path.GetFileName(file.FileName);
                            string SAVE_PATH = Path.Combine(Server.MapPath("~/uploadedFiles"), FILE_NAME);
                            file.SaveAs(SAVE_PATH);


                            // Checking whether if a zip file is being uploaded

                            if (System.IO.Path.GetExtension(file.FileName) == ".zip") // Uploded file is a zip file
                            {
                                unzipper.setFileName(file.FileName);
                                unzipper.Unzip();// Unzipping



                                SAVE_PATH = Path.Combine(Server.MapPath("~/uploadedFiles"), FILE_NAME);
                            }

                            if (System.IO.Path.GetExtension(FILE_NAME) != ".zip")
                            {
                                fileNamesList.Add(new FileNames(FILE_NAME)); // Add file name to the list
                            }
                        }
                        if (multipleTrue)
                        {
                            REDIRECT_PAGE = "MultipleFiles";
                        }


                        if (fileNamesList.Count > 1)// Check how many file are being uploaded
                        {
                            multipleTrue         = true;
                            ViewBag.multipleTrue = multipleTrue;
                            REDIRECT_PAGE        = "MultipleFiles"; // If multiple files are being uploaded, Redirect to this page
                        }
                        else if (fileNamesList.Count == 1)
                        {
                            REDIRECT_PAGE = "Tool_Home";
                        }

                        else // If no file is uploaded,
                        {
                            REDIRECT_PAGE = "UploadFile";
                        }
                    }
                }
                catch (Exception e)
                {
                    return(Redirect(REDIRECT_PAGE));
                }

                TempData["UPLOADED_FILES_LIST"] = fileNamesList;
                TempData.Keep("UPLOADED_FILES_LIST");
                ViewBag.names = fileNamesList;
            }
            return(Redirect(REDIRECT_PAGE));
        }
示例#26
0
        static void Main(string[] args)
        {
            bool showHelp     = false;
            var  instructions = new UpdateInstructions {
                StartDelay = 1000
            };

            var p = new OptionSet()
            {
                { "a|access=", "Required. The Amazon {ACCESS KEY} with permissions to access the S3 bucket",
                  v => instructions.AwsAccessKey = v },
                { "s|secret=", "Required. The Amazon {SECRET KEY} with permissions to access the S3 bucket",
                  v => instructions.AwsSecretKey = v },
                { "b|bucket=", "Required. The Amazon S3 {BUCKET} name containing the files",
                  v => instructions.BucketName = v },
                { "r|remotepath=", "Required. The {REMOTE_PATH} of the update zip file within the S3 bucket",
                  v => instructions.RemotePath = v },
                { "f|folder=", "Required. The local path of the folder containing the application. The ZIPFILE will be extracted here, replacing existing files",
                  v => instructions.Folder = v },
                { "e|exe=", "Required. The local path of the {EXECUTABLE} to launch after completion",
                  v => instructions.ExePath = v },
                { "v|service=", "Optional. Is the exe a TopShelf service? If yes, appends a start argument\nOptions: true or false. Default is false.",
                  (bool v) => instructions.IsService = v },
                { "d|delay=", "Optional. The {DELAY} in millseconds to wait before beginning the update process. Default is 1000.",
                  (int v) => instructions.StartDelay = v },
                { "t|temp=", "Optional. The local path to the {TEMPDIR} in which to store download files\nBy default \\temp in relation to updater will be used",
                  v => instructions.TempDir = v },
                { "u|url=", "Optional. The {URL} to POST errors to",
                  v => instructions.ErrorUrl = v },
                { "h|help", "show this message and exit",
                  v => showHelp = v != null },
            };

            try
            {
                p.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("There was an error: ");
                Console.WriteLine(e.Message);
                ShowHelp(p);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            bool success = false;

            try
            {
                Console.WriteLine("Beginning update process");
                Console.Write("Delay is set to {0}ms. Waiting.", instructions.StartDelay);
                Thread.Sleep(instructions.StartDelay);
                Console.WriteLine("Continuing");
                // If temp directory wasn't set by an argument, set it to current folder\Temp
                if (string.IsNullOrWhiteSpace(instructions.TempDir))
                {
                    instructions.TempDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Temp";
                }

                // Make sure the temp directory exists
                Directory.CreateDirectory(instructions.TempDir);

                // Try to delete any files that exist in the directory
                try
                {
                    var dirInfo = new DirectoryInfo(instructions.TempDir);
                    foreach (System.IO.FileInfo file in dirInfo.GetFiles())
                    {
                        file.Delete();
                    }
                }
                catch (Exception)
                {
                    // Do nothing, deleting files isn't really all that important.
                }


                Console.WriteLine("Using TempDir: " + instructions.TempDir);

                // Download file to temp dir
                var downloader =
                    new FileDownloader(
                        new S3Caller(new SimpleCredentialsRetriever(instructions.AwsAccessKey, instructions.AwsSecretKey)),
                        instructions.BucketName);

                var    srcFilename    = instructions.RemotePath;
                string workerFilename = srcFilename;
                if (srcFilename.Contains('/'))
                {
                    workerFilename = srcFilename.Split('/').Last();
                }
                var destFullPath = Path.Combine(instructions.TempDir, workerFilename);

                Console.WriteLine("Downloading file from S3 bucket: " + instructions.BucketName);
                Console.WriteLine("Source file: " + srcFilename);
                Console.WriteLine("Destination: " + destFullPath);
                downloader.DownloadFile(srcFilename, destFullPath);

                // Extract zip to folder, replacing all files
                Console.WriteLine("Download complete. Extracting zip file to: " + instructions.Folder);
                Unzipper.Unzip(destFullPath, instructions.Folder, true);

                // Run the exe
                Console.WriteLine("Update complete. Launching: " + instructions.ExePath);
                success = true;
            }
            catch (Exception ex)
            {
                // TODO: Try to Post error message to url
                Console.WriteLine("THERE WAS AN ERROR!\n" + ex);
            }
            finally
            {
                if (instructions.IsService)
                {
                    Console.WriteLine("Launching as a service by appending the start argument");
                    Process.Start(instructions.ExePath, "start");
                }
                else
                {
                    Process.Start(instructions.ExePath);
                }

                if (success)
                {
                    Console.WriteLine("Success. Exiting.");
                }
            }
        }
示例#27
0
        static void Main(string[] args)
        {
            var spiderFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Arachnee.Spider");
            var now          = DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss");
            var logFilePath  = Path.Combine(spiderFolder, now + "_spider.log");

            Logger.Initialize(logFilePath);

            Console.WriteLine("Log file at " + logFilePath);

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

            Console.WriteLine($"Write \"{MovieChoice}\" or \"{TvSeriesChoice}\" to choose what to download:");
            var choice = Console.ReadLine();

            Logger.Instance.LogMessage("Asked to download " + choice);

            var downloader = new ArchiveDownloader();

            string zipPath;

            if (choice == MovieChoice)
            {
                zipPath = downloader.Download <Movie>(DateTime.UtcNow.AddDays(-2), spiderFolder);
            }
            else if (choice == TvSeriesChoice)
            {
                zipPath = downloader.Download <TvSeries>(DateTime.UtcNow.AddDays(-2), spiderFolder);
            }
            else
            {
                Logger.Instance.LogError(choice + " not handled.");
                return;
            }

            var idsPath = Unzipper.Unzip(zipPath);

            var proxy = new TmdbProxy();

            var reader       = new ArchiveReader(proxy);
            int entriesCount = reader.CountLines(idsPath);

            reader.SkippedId += CountSkippedId;

            IEnumerable <Entry> entries;

            if (choice == MovieChoice)
            {
                entries = reader.Read <Movie>(idsPath);
            }
            else if (choice == TvSeriesChoice)
            {
                entries = reader.Read <TvSeries>(idsPath);
            }
            else
            {
                Logger.Instance.LogError(choice + " not handled.");
                return;
            }


            string outputFilePath = Path.Combine(spiderFolder, now + "_output.spdr");

            var serializer = new HighPressureSerializer(outputFilePath);

            var chrono = Stopwatch.StartNew();

            int threshold = 0;

            foreach (var entry in entries)
            {
                _progress++;
                if (_progress > threshold)
                {
                    float progress = (float)_progress / entriesCount * 100;
                    Logger.Instance.LogMessage($"{_progress}/{entriesCount} ({progress:##0.000}%) - elapsed: {chrono.Elapsed}");

                    threshold = _progress + 100;
                }

                if (string.IsNullOrEmpty(entry.MainImagePath))
                {
                    Logger.Instance.LogDebug("Skip " + entry + " because it has no image.");
                    continue;
                }

                var connectionsToCompress = new List <Connection>();
                foreach (var connection in entry.Connections.Where(c => c.Type != ConnectionType.Crew))
                {
                    Logger.Instance.LogDebug(entry + " :: " + connection.Label + " :: " + connection.ConnectedId);
                    connectionsToCompress.Add(connection);
                }

                if (connectionsToCompress.Count == 0)
                {
                    continue;
                }

                serializer.CompressAndWrite(entry.Id, connectionsToCompress);
            }

            Console.WriteLine("Job done, press any key");
            Console.ReadKey();
        }