示例#1
0
        /// <summary>
        /// IProgress の
        /// IteratorTasks → System.Threading.Tasks。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="progress"></param>
        /// <returns></returns>
        public static System.IProgress <T> ToTpl <T>(this IProgress <T> progress)
        {
            var p = new System.Progress <T>();

            p.ProgressChanged += (sender, x) => progress.Report(x);
            return(p);
        }
示例#2
0
        public static async System.Threading.Tasks.Task Test()
        {
            string url = "https://speed.hetzner.de/100MB.bin";

            // url = "https://speed.hetzner.de/1GB.bin";
            // url = "https://speed.hetzner.de/10GB.bin";

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()
            {
                Timeout = System.TimeSpan.FromDays(1)
            })
            {
                using (System.IO.Stream stream = System.IO.File.OpenWrite(@"D:\foo.bin"))
                {
                    System.Progress <float> cb = new System.Progress <float>(
                        delegate(float value)
                    {
                        System.Console.WriteLine("Progress: {0}%", value);
                    }
                        );

                    await client.DownloadAsync(url, stream, cb, System.Threading.CancellationToken.None);
                }
            }
        }
        private async void button_Generate_Click(object sender, RoutedEventArgs e)
        {
            this.cancellationTokenSource = new System.Threading.CancellationTokenSource();
            this.viewModel.IsGenerating  = true;

            ICollection <RDAFileListItem> enabledItems = viewModel.RDAFileList.Items.Where((item) => item.IsEnabled).ToList();

            int numSteps = enabledItems.Count * 2; // reading

            numSteps += 1;                         // writing

            this.statusBar_progressBar_Progress.Minimum = 0;
            this.statusBar_progressBar_Progress.Maximum = numSteps;
            this.statusBar_progressBar_Progress.Value   = 0;

            var archiveFiles = new AnnoRDA.FileDB.Writer.ArchiveFileMap();
            var fileSystem   = new AnnoRDA.FileSystem();
            var fileLoader   = new AnnoRDA.Loader.ContainerFileLoader();

            try {
                foreach (var rdaFile in enabledItems)
                {
                    this.statusBar_textBlock_Message.Text = System.String.Format("Loading {0}", rdaFile.Name);
                    archiveFiles.Add(rdaFile.LoadPath, rdaFile.Name);

                    var progress = new System.Progress <string>((string fileName) => {
                        this.statusBar_textBlock_Message.Text = System.String.Format("Loading {0}: {1}", rdaFile.Name, fileName);
                    });
                    var containerFileSystem = await Task.Run(() => fileLoader.Load(rdaFile.LoadPath, progress, this.cancellationTokenSource.Token));

                    this.statusBar_progressBar_Progress.Value += 1;

                    this.statusBar_textBlock_Message.Text = System.String.Format("Loading {0}", rdaFile.Name);
                    await Task.Run(() => fileSystem.OverwriteWith(containerFileSystem, null, this.cancellationTokenSource.Token));

                    this.statusBar_progressBar_Progress.Value += 1;
                }

                this.statusBar_textBlock_Message.Text = "Writing...";

                using (var outputStream = new System.IO.FileStream(this.viewModel.OutputFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
                    using (var writer = new AnnoRDA.FileDB.Writer.FileDBWriter(outputStream, false)) {
                        await Task.Run(() => writer.WriteFileDB(fileSystem, archiveFiles));
                    }
                }
                this.statusBar_progressBar_Progress.Value += 1;

                this.statusBar_textBlock_Message.Text = "Done";
            } catch (System.OperationCanceledException) {
                this.statusBar_textBlock_Message.Text = "Canceled";
            } finally {
                this.viewModel.IsGenerating = false;
                this.cancellationTokenSource.Dispose();
                this.cancellationTokenSource = null;
            }
        }
示例#4
0
        public static async System.Threading.Tasks.Task DownloadAsync(this System.Net.Http.HttpClient client
                                                                      , string requestUri
                                                                      , System.IO.Stream destination
                                                                      , System.IProgress <float> progress = null
                                                                      , System.Threading.CancellationToken cancellationToken = default)
        {
            // Get the http headers first to examine the content length
            using (System.Net.Http.HttpResponseMessage response = await client.GetAsync(
                       requestUri,
                       System.Net.Http.HttpCompletionOption.ResponseHeadersRead)
                   )
            {
                long?contentLength = response.Content.Headers.ContentLength;

                using (System.IO.Stream download = await response.Content.ReadAsStreamAsync())
                {
                    // Ignore progress reporting when no progress reporter was
                    // passed or when the content length is unknown
                    if (progress == null || !contentLength.HasValue)
                    {
                        await download.CopyToAsync(destination);

                        return;
                    }

                    // Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
                    System.Progress <long> relativeProgress = new System.Progress <long>(
                        delegate(long totalBytes)
                    {
                        if (contentLength.Value == 0)
                        {
                            progress.Report(99.99999f);
                            return;
                        }

                        float reportedValue = (float)totalBytes * 100.0f / contentLength.Value;
                        if (reportedValue == 100.0f)
                        {
                            reportedValue = 99.99999f;
                        }

                        progress.Report(reportedValue);
                    }
                        );

                    // Use extension method to report progress while downloading
                    await download.CopyToAsync(destination, 81920, relativeProgress, cancellationToken);

                    progress.Report(100.0f);
                } // End Using download
            }     // End Using response
        }         // End Task DownloadAsync
示例#5
0
文件: Video.cs 项目: tikz/VideoUpload
        public async Task UploadVideoAsync()
        {
            var baseFileName = dashTitle;
            var fileName     = baseFileName;

            int i = 2;

            while (FileExistsInCloud(fileName + outputExt))
            {
                fileName = baseFileName + "-" + i;
                i++;
            }

            var videoObject = new Google.Apis.Storage.v1.Data.Object
            {
                Bucket      = bucketName,
                Name        = fileName + outputExt,
                ContentType = "video/webm"
            };

            var metadataDict = new Dictionary <string, string>
            {
                { "title", titleText },
                { "endpoint", fileName },
                { "image_endpoint", HashFile(imageFilename) },
            };

            videoObject.Metadata = metadataDict;
            endpoint             = fileName;

            using (var stream = new System.IO.FileStream(outputFile, System.IO.FileMode.Open))
            {
                form.UploadProgressBar.Maximum = (int)stream.Length;

                var uploadObjectOptions = new Google.Cloud.Storage.V1.UploadObjectOptions
                {
                    ChunkSize = Google.Cloud.Storage.V1.UploadObjectOptions.MinimumChunkSize
                };

                var progressReporter = new System.Progress <Google.Apis.Upload.IUploadProgress>(OnUploadProgress);
                await storage.UploadObjectAsync(
                    videoObject,
                    stream,
                    uploadObjectOptions,
                    progress : progressReporter
                    );
            }
        }
        private async void button_Generate_Click(object sender, RoutedEventArgs e)
        {
            this.cancellationTokenSource = new System.Threading.CancellationTokenSource();
            this.viewModel.IsGenerating = true;

            ICollection<RDAFileListItem> enabledItems = viewModel.RDAFileList.Items.Where((item) => item.IsEnabled).ToList();

            int numSteps = enabledItems.Count * 2; // reading
            numSteps += 1; // writing

            this.statusBar_progressBar_Progress.Minimum = 0;
            this.statusBar_progressBar_Progress.Maximum = numSteps;
            this.statusBar_progressBar_Progress.Value = 0;

            var archiveFiles = new AnnoRDA.FileDB.Writer.ArchiveFileMap();
            var fileSystem = new AnnoRDA.FileSystem();
            var fileLoader = new AnnoRDA.Loader.ContainerFileLoader();

            try {
                foreach (var rdaFile in enabledItems) {
                    this.statusBar_textBlock_Message.Text = System.String.Format("Loading {0}", rdaFile.Name);
                    archiveFiles.Add(rdaFile.LoadPath, rdaFile.Name);

                    var progress = new System.Progress<string>((string fileName) => {
                        this.statusBar_textBlock_Message.Text = System.String.Format("Loading {0}: {1}", rdaFile.Name, fileName);
                    });
                    var containerFileSystem = await Task.Run(() => fileLoader.Load(rdaFile.LoadPath, progress, this.cancellationTokenSource.Token));
                    this.statusBar_progressBar_Progress.Value += 1;

                    this.statusBar_textBlock_Message.Text = System.String.Format("Loading {0}", rdaFile.Name);
                    await Task.Run(() => fileSystem.OverwriteWith(containerFileSystem, null, this.cancellationTokenSource.Token));
                    this.statusBar_progressBar_Progress.Value += 1;
                }

                this.statusBar_textBlock_Message.Text = "Writing...";

                using (var outputStream = new System.IO.FileStream(this.viewModel.OutputFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
                    using (var writer = new AnnoRDA.FileDB.Writer.FileDBWriter(outputStream, false)) {
                        await Task.Run(() => writer.WriteFileDB(fileSystem, archiveFiles));
                    }
                }
                this.statusBar_progressBar_Progress.Value += 1;

                this.statusBar_textBlock_Message.Text = "Done";

            } catch(System.OperationCanceledException) {
                this.statusBar_textBlock_Message.Text = "Canceled";

            } finally {
                this.viewModel.IsGenerating = false;
                this.cancellationTokenSource.Dispose();
                this.cancellationTokenSource = null;
            }
        }
示例#7
0
        public void StartupApp(object sender, StartupEventArgs e)
        {
            //Determine if the permissionChange is succesfull after launcher update
            bool isGoodUpdate = false;

            foreach (string a in e.Args)
            {
                if (a.StartsWith("--patch-result="))
                {
                    string code = a.Substring("--patch-result=".Length);
                    //If the code !=0 -> there is something wrong with the patching of the launcher
                    if (code != "0")
                    {
                        MessageBox.Show(string.Format("Failed to update the launcher (code {0}).\n\nPlease close any applications related to Renegade-X and try again.", code), "Patch failed", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else//Otherwise -> change folderpermissions and afterwards launch the launcher
                    {
                        try {
                            SetFullControlPermissionsToEveryone(GameInstallation.GetRootPath());
                            isGoodUpdate = true; //Set isGoodUpdate to true to indicate correct permissionChange
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
                else if (a.StartsWith("--firstInstall")) //Init the first install
                {
                    Installer x = new Installer();
                    x.Show();
                    x.FirstInstall();
                }
                else if (a.StartsWith("--UpdateGame="))//Manually opdate the game to a given URL.
                {
                    // Close any other instances of the RenX-Launcher
                    if (InstanceHandler.IsAnotherInstanceRunning())
                    {
                        InstanceHandler.KillDuplicateInstance();
                    }

                    var    targetDir      = GameInstallation.GetRootPath();
                    var    applicationDir = System.IO.Path.Combine(GameInstallation.GetRootPath(), "patch");
                    String patchUrl       = a.Substring("--UpdateGame=".Length);
                    var    patchVersion   = VersionCheck.GetLatestGameVersionName();

                    var progress = new System.Progress <RXPatchLib.DirectoryPatcherProgressReport>();
                    var cancellationTokenSource = new System.Threading.CancellationTokenSource();

                    var patcher = new RXPatchLib.RXPatcher();
                    System.Threading.Tasks.Task task = patcher.ApplyPatchFromWeb(patchUrl, targetDir, applicationDir, progress, cancellationTokenSource.Token, null); // no verificaiton on instructions.json, as we're bypassing standard version checking

                    var window = new Views.ApplyUpdateWindow(task, patcher, progress, patchVersion, cancellationTokenSource, Views.ApplyUpdateWindow.UpdateWindowType.Update);
                    window.ShowDialog();

                    VersionCheck.UpdateGameVersion();
                }
            }

            if (LauncherTwo.Properties.Settings.Default.UpgradeRequired)
            {
                LauncherTwo.Properties.Settings.Default.Upgrade();
                LauncherTwo.Properties.Settings.Default.UpgradeRequired = false;
                LauncherTwo.Properties.Settings.Default.Save();
            }

            /* Commented out untill I found a better way to intergrate it in the installation
             * if (!GameInstallation.IsRootPathPlausible())
             * {
             *  var result = MessageBox.Show("The game path seems to be incorrect. Please ensure that the launcher is placed in the correct location. If you proceed, files in the following location might be affected:\n\n" + GameInstallation.GetRootPath() + "\n\nAre you sure want to proceed?", "Invalid game path", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
             *  if (result != MessageBoxResult.Yes)
             *  {
             *      Shutdown();
             *      return;
             *  }
             * }
             */
            //If no args are present, or a permissionChange update was executed -> normally start the launcher
            if (e.Args.Length == 0 || isGoodUpdate)
            {
                if (InstanceHandler.IsAnotherInstanceRunning())
                {
                    MessageBox.Show("Error:\nUnable to start Renegade-X Launcher: Another instance is already running!",
                                    "Renegade-X Launcher", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                    Current.Shutdown();
                }

                new MainWindow().Show();
            }

            /*else
             * {
             *  Application.Current.Shutdown();
             * }*/
        }