private void StartDownloading() { var file = transferServer.EndExportDatabase(new DownloadDatabaseRequests { User = UserHolder.Current?.ToLite(), DownloadStatistics = currentLite }); FileTools.CreateParentDirectory(DisconnectedClient.DownloadBackupFile); pbDownloading.Minimum = 0; pbDownloading.Maximum = file.Length; Task.Factory.StartNew(() => { using (var ps = new ProgressStream(file.Stream)) { ps.ProgressChanged += (s, args) => Dispatcher.Invoke(() => pbDownloading.Value = ps.Position); using (FileStream fs = File.OpenWrite(DisconnectedClient.DownloadBackupFile)) ps.CopyTo(fs); } Dispatcher.Invoke(() => { MessageBox.Show(Window.GetWindow(this), "You have successfully downloaded a local database. \r\nThe application will turn off now.\r\nNext time you start it up, choose Run disconnected.", "Download complete", MessageBoxButton.OK); }); Environment.Exit(0); }); }
public void EnsureBandwidthIsReportedIfProgressIsShorterThanOneSecond() { byte[] inputContent = new byte[1024]; FileTransmissionEvent transmission = new FileTransmissionEvent(this.transmissionType, this.filename); using (var inputStream = new MemoryStream(inputContent)) using (var outputStream = new MemoryStream()) using (var progressStream = new ProgressStream(inputStream, transmission)) { progressStream.CopyTo(outputStream); Assert.That(outputStream.Length == inputContent.Length); } Assert.Greater(transmission.Status.BitsPerSecond, 0); }
/// <summary> /// Retrieves a single file from a zip file. /// </summary> /// <param name="fileName">The zip file in which to find the file.</param> /// <param name="entryPath">The file to find in the zip file.</param> /// <param name="copyTo">A stream to which to copy the file, before closing the zipFile.</param> /// <param name="prog">A prog tracking object, defaults to null (i.e. no prog tracking).</param> public static void CopyFile(this ZipArchive zip, string entryPath, Stream copyTo, IProgress prog = null) { if (zip is null) { throw new ArgumentNullException(nameof(zip)); } if (copyTo is null) { throw new ArgumentNullException(nameof(copyTo)); } var entry = zip.GetEntry(entryPath); if (entry is null) { throw new FileNotFoundException($"Could not find file {entryPath} in the zip file."); } using var copyFrom = entry.Open(); using var progStream = new ProgressStream(copyFrom, entry.Length, prog, false); progStream.CopyTo(copyTo); }
protected override void ProcessRecord() { ProviderInfo destinationProviderInfo; var destinationLocation = ResolveDestinationLocation(out destinationProviderInfo); var sources = Path.Select(each => { ProviderInfo spi; var sourceFiles = SessionState.Path.GetResolvedProviderPathFromPSPath(each, out spi); return new SourceSet { ProviderInfo = spi, SourcePaths = sourceFiles.ToArray(), }; }).ToArray(); var providerInfos = sources.Select(each => each.ProviderInfo).Distinct().ToArray(); if (providerInfos.Length == 1 && providerInfos[0] == destinationProviderInfo) { WriteVerbose("Using regular copy-item"); base.ProcessRecord(); return; } bool force = Force; var copyOperations = ResolveSourceLocations(sources, destinationLocation).ToArray(); if (copyOperations.Length > 1 && destinationLocation.IsFile) { // source can only be a single file. ThrowTerminatingError(new ErrorRecord(new DirectoryNotFoundException(), "0", ErrorCategory.InvalidArgument, null)); //WriteError(new ErrorRecord(new ClrPlusException("Destination file exists--multiple source files specified."), "ErrorId", ErrorCategory.InvalidArgument, null)); return; } var s = new Stopwatch(); s.Start(); for (var i = 0; i < copyOperations.Length; i++) { var operation = copyOperations[i]; WriteProgress(CreateProgressRecord(1, "Copy", "Copying item {0} of {1}".format(i, copyOperations.Length), 100 * (double)i/copyOperations.Length)); //Console.WriteLine("COPY '{0}' to '{1}'", operation.Source.AbsolutePath, operation.Destination.AbsolutePath); if (!force) { if (operation.Destination.Exists) { ThrowTerminatingError(new ErrorRecord(new ClrPlusException("Destination file '{0}' exists. Must use -force to override".format(operation.Destination.AbsolutePath)), "ErrorId", ErrorCategory.ResourceExists, null)); return; } } using (var inputStream = new ProgressStream(operation.Source.Open(FileMode.Open))) { using (var outputStream = new ProgressStream(operation.Destination.Open(FileMode.Create))) { var inputLength = inputStream.Length; inputStream.BytesRead += (sender, args) => {}; CopyOperation operation1 = operation; outputStream.BytesWritten += (sender, args) => WriteProgress(CreateProgressRecord(2, "Copy", "Copying '{0}' to '{1}'".format(operation1.Source.AbsolutePath, operation1.Destination.AbsolutePath), 100*(double)args.StreamPosition/inputLength, 1)); inputStream.CopyTo(outputStream, 32768); /* Task t = inputStream.CopyToAsync(outputStream, _cancellationToken.Token, false); try { t.RunSynchronously(); } catch (TaskCanceledException e) { return; } */ } } WriteProgress(CreateCompletedProgressRecord(2, "Copy", "Copying '{0}' to '{1}'".format(operation.Source.AbsolutePath, operation.Destination.AbsolutePath), 1)); // WriteVerbose("Copy from {0} to {1}".format(operation.Source.AbsolutePath, operation.Destination.AbsolutePath)); } WriteProgress(CreateCompletedProgressRecord(1, "Copy", "Copy finished")); s.Stop(); WriteVerbose("Completed in {0}".format(s.Elapsed)); }
protected override void ProcessRecord() { ProviderInfo destinationProviderInfo; var destinationLocation = ResolveDestinationLocation(out destinationProviderInfo); var sources = Path.Select(each => { ProviderInfo spi; var sourceFiles = SessionState.Path.GetResolvedProviderPathFromPSPath(each, out spi); return(new SourceSet { ProviderInfo = spi, SourcePaths = sourceFiles.ToArray(), }); }).ToArray(); var providerInfos = sources.Select(each => each.ProviderInfo).Distinct().ToArray(); if (providerInfos.Length == 1 && providerInfos[0] == destinationProviderInfo) { WriteVerbose("Using regular copy-item"); base.ProcessRecord(); return; } bool force = Force; var copyOperations = ResolveSourceLocations(sources, destinationLocation).ToArray(); if (copyOperations.Length > 1 && destinationLocation.IsFile) { // source can only be a single file. ThrowTerminatingError(new ErrorRecord(new DirectoryNotFoundException(), "0", ErrorCategory.InvalidArgument, null)); //WriteError(new ErrorRecord(new ClrPlusException("Destination file exists--multiple source files specified."), "ErrorId", ErrorCategory.InvalidArgument, null)); return; } var s = new Stopwatch(); s.Start(); for (var i = 0; i < copyOperations.Length; i++) { var operation = copyOperations[i]; WriteProgress(CreateProgressRecord(1, "Copy", "Copying item {0} of {1}".format(i, copyOperations.Length), 100 * (double)i / copyOperations.Length)); //Console.WriteLine("COPY '{0}' to '{1}'", operation.Source.AbsolutePath, operation.Destination.AbsolutePath); if (!force) { if (operation.Destination.Exists) { ThrowTerminatingError(new ErrorRecord(new ClrPlusException("Destination file '{0}' exists. Must use -force to override".format(operation.Destination.AbsolutePath)), "ErrorId", ErrorCategory.ResourceExists, null)); return; } } using (var inputStream = new ProgressStream(operation.Source.Open(FileMode.Open))) { using (var outputStream = new ProgressStream(operation.Destination.Open(FileMode.Create))) { var inputLength = inputStream.Length; inputStream.BytesRead += (sender, args) => {}; CopyOperation operation1 = operation; outputStream.BytesWritten += (sender, args) => WriteProgress(CreateProgressRecord(2, "Copy", "Copying '{0}' to '{1}'".format(operation1.Source.AbsolutePath, operation1.Destination.AbsolutePath), 100 * (double)args.StreamPosition / inputLength, 1)); inputStream.CopyTo(outputStream, 32768); /* * Task t = inputStream.CopyToAsync(outputStream, _cancellationToken.Token, false); * try { * t.RunSynchronously(); * } catch (TaskCanceledException e) { * return; * } */ } } WriteProgress(CreateCompletedProgressRecord(2, "Copy", "Copying '{0}' to '{1}'".format(operation.Source.AbsolutePath, operation.Destination.AbsolutePath), 1)); // WriteVerbose("Copy from {0} to {1}".format(operation.Source.AbsolutePath, operation.Destination.AbsolutePath)); } WriteProgress(CreateCompletedProgressRecord(1, "Copy", "Copy finished")); s.Stop(); WriteVerbose("Completed in {0}".format(s.Elapsed)); }
private void StartDownloading() { var file = transferServer.EndExportDatabase(new DownloadDatabaseRequests { User = UserEntity.Current.ToLite(), DownloadStatistics = currentLite }); FileTools.CreateParentDirectory(DisconnectedClient.DownloadBackupFile); pbDownloading.Minimum = 0; pbDownloading.Maximum = file.Length; Task.Factory.StartNew(() => { using (var ps = new ProgressStream(file.Stream)) { ps.ProgressChanged += (s, args) => Dispatcher.Invoke(() => pbDownloading.Value = ps.Position); using (FileStream fs = File.OpenWrite(DisconnectedClient.DownloadBackupFile)) ps.CopyTo(fs); } Dispatcher.Invoke(() => { MessageBox.Show(Window.GetWindow(this), "You have successfully downloaded a local database. \r\nThe application will turn off now.\r\nNext time you start it up, choose Run disconnected.", "Download complete", MessageBoxButton.OK); }); Environment.Exit(0); }); }
public static bool InstallGame(string gameTitle, string gameVersion, ProgressDelegate listener, ICancellable cancelObject) { var downloadPath = GetDownloadPath(gameTitle, gameVersion); var installPath = GetInstallPath(gameTitle, gameVersion); if (File.Exists(downloadPath)) { Logger.Log("Installing game ({0} {1})", gameTitle, gameVersion); try { using (var zipFile = new ZipFile(downloadPath)) { // Delete old install if (Directory.Exists(installPath)) { Directory.Delete(installPath, true); } Directory.CreateDirectory(installPath); // Extract new install int totalFiles = zipFile.Entries.Count; int filesInstalled = 0; int lastProgress = 0; listener.Invoke(0); foreach (var entry in zipFile.Entries) { // Extract the file var entryInstallPath = Path.Combine(installPath, entry.FileName); if (entry.IsDirectory) { Directory.CreateDirectory(entryInstallPath); } else { Directory.CreateDirectory(Path.GetDirectoryName(entryInstallPath)); using (var file = File.OpenWrite(entryInstallPath)) { try { using (var reader = new ProgressStream(entry.OpenReader(), -1, delegate { // TODO: Emit progress during installation of large individual files? }, cancelObject)) { try { reader.CopyTo(file); try { if (Program.Platform == Platform.Linux || Program.Platform == Platform.OSX) { MakeFileExecutable(entryInstallPath); } } catch (Exception e) { Logger.Log("Caught Exception: {0}", e.ToString()); Logger.Log("Failed to set file permissions on {0}", entryInstallPath); } } finally { reader.Close(); } } } finally { file.Close(); } } } // Check for cancellation if (cancelObject.Cancelled) { throw new IOCancelledException(); } // Notify the progress listener filesInstalled++; int progress = (filesInstalled * 100) / totalFiles; if (progress != lastProgress) { listener.Invoke(progress); lastProgress = progress; } } } return(true); } catch (Exception e) { Logger.Log("Caught Exception: {0}", e.ToString()); if (Directory.Exists(installPath)) { Directory.Delete(installPath, true); } return(false); } } return(false); }
public static bool DownloadGame(string gameTitle, string gameVersion, string url, string username, string password, ProgressDelegate listener, ICancellable cancelObject, out bool o_authFailure, out string o_customMessage) { if (url == null) { o_authFailure = false; o_customMessage = null; return(false); } var downloadPath = GetDownloadPath(gameTitle, gameVersion); Logger.Log("Downloading game ({0} {1}) from {2}", gameTitle, gameVersion, downloadPath); try { var request = HttpWebRequest.Create(url); request.Timeout = 15000; if (username != null && password != null) { request.Credentials = new NetworkCredential(username, password); } using (var response = request.GetResponse()) { // Read the message o_customMessage = response.Headers.Get("X-IndieLauncher-Message"); if (o_customMessage != null) { Logger.Log("URL returned message: {0}", o_customMessage); } // Read the content using (var stream = new ProgressStream(response.GetResponseStream(), response.ContentLength, listener, cancelObject)) { try { // Delete old download if (File.Exists(downloadPath)) { File.Delete(downloadPath); } // Create new download Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); using (var output = File.OpenWrite(downloadPath)) { try { stream.CopyTo(output); } finally { output.Close(); } } } finally { stream.Close(); } } } o_authFailure = false; return(true); } catch (Exception e) { Logger.Log("Caught Exception: {0}", e.ToString()); if (File.Exists(downloadPath)) { File.Delete(downloadPath); } if (e is WebException) { WebException we = (WebException)e; if (we.Response != null) { o_customMessage = we.Response.Headers.Get("X-IndieLauncher-Message"); if (o_customMessage != null) { Logger.Log("URL returned message: {0}", o_customMessage); } if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Unauthorized) { o_authFailure = true; Logger.Log("URL returned HTTP Unauthorized"); } else { o_authFailure = false; } } else { o_customMessage = null; o_authFailure = false; } } else { o_customMessage = null; o_authFailure = false; } return(false); } }
public static bool ExtractEmbeddedGame(ProgressDelegate listener, ICancellable cancelObject) { string gameTitle, gameVersion, gameURL, username, password; if (GetEmbeddedGameInfo(out gameTitle, out gameVersion, out gameURL, out username, out password) && gameVersion != null) { Logger.Log("Extracting embedded game ({0} {1})", gameTitle, gameVersion); var downloadPath = GetDownloadPath(gameTitle, gameVersion); try { var assembly = Assembly.GetExecutingAssembly(); var stream = assembly.GetManifestResourceStream("EmbeddedGame." + Program.Platform + ".zip"); if (stream == null) { stream = assembly.GetManifestResourceStream("EmbeddedGame.zip"); } if (stream != null) { using ( stream ) { try { using (var progressStream = new ProgressStream(stream, -1, listener, cancelObject)) { // Delete old download if (File.Exists(downloadPath)) { File.Delete(downloadPath); } // Create new download try { Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); using (var output = File.OpenWrite(downloadPath)) { try { progressStream.CopyTo(output); } finally { output.Close(); } } } finally { progressStream.Close(); } } } finally { stream.Close(); } } return(true); } return(false); } catch (Exception e) { Logger.Log("Caught Exception: {0}", e.ToString()); if (File.Exists(downloadPath)) { File.Delete(downloadPath); } return(false); } } return(false); }
public static bool DownloadGame(string gameTitle, string gameVersion, string url, string username, string password, ProgressDelegate listener, ICancellable cancelObject, out bool o_authFailure) { if (url == null) { o_authFailure = false; return(false); } var downloadPath = GetDownloadPath(gameTitle, gameVersion); try { var request = HttpWebRequest.Create(url); request.Timeout = 15000; if (username != null && password != null) { request.Credentials = new NetworkCredential(username, password); } using (var response = request.GetResponse()) { using (var stream = new ProgressStream(response.GetResponseStream(), response.ContentLength, listener, cancelObject)) { try { // Delete old download if (File.Exists(downloadPath)) { File.Delete(downloadPath); } // Create new download Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); using (var output = File.OpenWrite(downloadPath)) { try { stream.CopyTo(output); } finally { output.Close(); } } } finally { stream.Close(); } } } o_authFailure = false; return(true); } catch (IOException) { if (File.Exists(downloadPath)) { File.Delete(downloadPath); } o_authFailure = false; return(false); } catch (WebException e) { if (File.Exists(downloadPath)) { File.Delete(downloadPath); } if (((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized) { o_authFailure = true; } else { o_authFailure = false; } return(false); } }
protected override void ProcessRecord() { ProviderInfo destinationProviderInfo; var destinationPath = SessionState.Path.GetResolvedProviderPathFromPSPath(Destination, out destinationProviderInfo); var sources = Path.Select(each => { ProviderInfo spi; var sourceFiles = SessionState.Path.GetResolvedProviderPathFromPSPath(each, out spi); return new SourceSet { ProviderInfo = spi, SourcePaths = sourceFiles.ToArray(), }; }).ToArray(); var providerInfos = sources.Select(each => each.ProviderInfo).Distinct().ToArray(); if (providerInfos.Length > 1 && providerInfos[0] == destinationProviderInfo) { Console.WriteLine("Using regular copy-item"); base.ProcessRecord(); return; } bool force = Force; // resolve where files are going to go. var destinationLocation = GetLocationResolver(destinationProviderInfo).GetLocation(destinationPath[0]); var copyOperations = ResolveSourceLocations(sources, destinationLocation).ToArray(); if (copyOperations.Length > 1 && destinationLocation.IsFile) { // source can only be a single file. throw new CoAppException("Destination file exists--multiple source files specified."); } foreach (var operation in copyOperations) { Console.WriteLine("COPY '{0}' to '{1}'", operation.Source.AbsolutePath, operation.Destination.AbsolutePath); if (!force) { if (operation.Destination.Exists) { throw new CoAppException("Destination file '{0}' exists. Must use -force to override".format(operation.Destination.AbsolutePath)); } } using (var inputStream = new ProgressStream(operation.Source.Open(FileMode.Open))) { using (var outputStream = new ProgressStream(operation.Destination.Open(FileMode.Create))) { inputStream.BytesRead += (sender, args) => {}; outputStream.BytesWritten += (sender, args) => {}; inputStream.CopyTo(outputStream); } } } Console.WriteLine("Done."); }