private void UploadWorker_DoWork(object sender, DoWorkEventArgs e) { IList<BlackBoxReport> reports = (IList<BlackBoxReport>)e.Argument; SteppedProgressManager overallProgress = new SteppedProgressManager(); for (int i = 0; i < reports.Count; ++i) { ProgressManager reportProgress = new ProgressManager(); overallProgress.Steps.Add(new SteppedProgressManagerStep(reportProgress, 1.0f / reports.Count)); BlackBoxReportUploader uploader = new BlackBoxReportUploader(reports[i]); UploadWorker.ReportProgress((int)(overallProgress.Progress * 100), S._("Checking for status of report {0}...", reports[i].Name)); if (!uploader.IsNew) continue; if (UploadWorker.CancellationPending) throw new OperationCanceledException(); UploadWorker.ReportProgress((int)(overallProgress.Progress * 100), S._("Compressing Report {0}: {1:#0.00%}", reports[i].Name, 0)); uploader.Submit(delegate(object from, EraserProgressChangedEventArgs e2) { reportProgress.Completed = (int)(e2.Progress.Progress * reportProgress.Total); SteppedProgressManager reportSteps = (SteppedProgressManager)e2.Progress; int step = reportSteps.Steps.IndexOf(reportSteps.CurrentStep); UploadWorker.ReportProgress((int)overallProgress.Progress, step == 0 ? S._("Compressing Report {0}: {1:#0.00%}", reports[i].Name, reportSteps.Progress) : S._("Uploading Report {0}: {1:#0.00%}", reports[i].Name, reportSteps.Progress)); if (UploadWorker.CancellationPending) throw new OperationCanceledException(); }); } }
protected void OnProgressChanged(ProgressManager progress) { if (ProgressChanged != null) { ProgressChanged(progress); } }
private void OnProgressChanged(ProgressManager progress) { if (ProgressChanged != null) { ProgressChanged(progress); } }
private void uploader_ProgressChanged(ProgressManager progress) { if (progress != null) { ReportProgress(ProgressType.UPDATE_PROGRESSBAR_ProgressManager, progress); } }
private static GameObject ShowBlockingProgressUiFor(ViewStack self, string blockingProgressViewPrefabName, ProgressManager prManager) { GameObject prGo = self.ShowView(blockingProgressViewPrefabName); ProgressUi prUi = prGo.GetComponentInChildren <ProgressUi>(); prUi.onProgressUiComplete += () => { prGo.GetViewStack().SwitchBackToLastView(prGo); }; prUi.progressManager = prManager; return(prGo); }
/// <summary> /// Initialize other class instances in Start() to ensure the instance always has a value /// Start is always called after Awake - where all instances are created /// </summary> void Start() { progress = ProgressManager.Instance; }
private void CopyDirectory(DirectoryInfo info) { //Check the the destination is not a subfolder of the source. if (PathUtil.IsRootedAt(info, Destination)) { Logger.Log(S._("The destination directory cannot be within the source directory."), LogLevel.Error); return; } //We need to get the files from the list of streams List <StreamInfo> streams = GetPaths(); List <FileInfo> files = new List <FileInfo>( streams.Distinct(new StreamInfoFileEqualityComparer()). Select(x => x.File)); long totalSize = streams.Sum(x => x.Length); foreach (FileInfo file in files) { //Compute the total size of the file on the disk (including ADSes) List <StreamInfo> fileStreams = new List <StreamInfo>(file.GetADSes()); fileStreams.Add(new StreamInfo(file.FullName)); long fileSize = fileStreams.Sum(x => x.Length); SteppedProgressManager fileProgress = new SteppedProgressManager(); Progress.Steps.Add(new SteppedProgressManagerStep(fileProgress, fileSize / (float)totalSize, S._("Securely moving files and folders..."))); //Add the copying step to the file progress. ProgressManager copyProgress = new ProgressManager(); int totalPasses = 1 + EffectiveMethod.Passes; fileProgress.Steps.Add(new SteppedProgressManagerStep(copyProgress, 1f / totalPasses)); try { //Compute the path to the new directory. DirectoryInfo sourceDirectory = file.Directory; DirectoryInfo destDirectory = new DirectoryInfo( SourceToDestinationPath(file.DirectoryName)); //Make sure all necessary folders exist before the copy. if (!destDirectory.Exists) { destDirectory.Create(); } //Then copy the file. file.CopyTo(System.IO.Path.Combine(destDirectory.FullName, file.Name), delegate(long TotalFileSize, long TotalBytesTransferred) { return(CopyProgress(copyProgress, file, TotalFileSize, TotalBytesTransferred)); }); } catch (OperationCanceledException) { //The copy was cancelled: Complete the copy part. copyProgress.MarkComplete(); //We need to erase the partially copied copy of the file. SteppedProgressManager destroyProgress = new SteppedProgressManager(); Progress.Steps.Add(new SteppedProgressManagerStep(destroyProgress, 0.5f, S._("Erasing incomplete destination file"))); EraseFile(file, destroyProgress); //Rethrow the exception. throw; } //We copied the file over; erase the source file SteppedProgressManager eraseProgress = new SteppedProgressManager(); fileProgress.Steps.Add(new SteppedProgressManagerStep(eraseProgress, (totalPasses - 1) / (float)totalPasses, S._("Erasing source files..."))); EraseFile(file, eraseProgress); } //Then copy the timestamps from the source folders and delete the source. ProgressManager folderDeleteProgress = new ProgressManager(); Progress.Steps.Add(new SteppedProgressManagerStep(folderDeleteProgress, 0.0f, S._("Removing folders..."))); Action <DirectoryInfo> CopyTimesAndDelete = null; CopyTimesAndDelete = delegate(DirectoryInfo subDirectory) { foreach (DirectoryInfo child in subDirectory.GetDirectories()) { CopyTimesAndDelete(child); } //Update progress. folderDeleteProgress.Tag = subDirectory.FullName; //Get the directory which we copied to and copy the file times to the //destination directory DirectoryInfo destDirectory = new DirectoryInfo( SourceToDestinationPath(subDirectory.FullName)); if (!destDirectory.Exists) { destDirectory.Create(); } destDirectory.CopyTimes(subDirectory); //Then delete the source directory. IFileSystem fsManager = Host.Instance.FileSystems[ VolumeInfo.FromMountPoint(Path)]; fsManager.DeleteFolder(subDirectory, true); }; CopyTimesAndDelete(info); }
private void UploadProgressChanged(ProgressManager progress) { if (Engine.ConfigUI.ShowTrayUploadProgress) { UploadInfo uploadInfo = UploadManager.GetInfo(Id); if (uploadInfo != null) { uploadInfo.UploadPercentage = (int)progress.Percentage; MyWorker.ReportProgress((int)ProgressType.ChangeTrayIconProgress, progress); } } }
private void Compress(SteppedProgressManager progress, ProgressChangedEventHandler progressChanged) { using (FileStream archiveStream = new FileStream(ReportBaseName + ".tar", FileMode.Create, FileAccess.Write)) { TarArchive archive = TarArchive.CreateOutputTarArchive(archiveStream); foreach (FileInfo file in Report.Files) { TarEntry entry = TarEntry.CreateEntryFromFile(file.FullName); entry.Name = Path.GetFileName(entry.Name); archive.WriteEntry(entry, false); } archive.Close(); } ProgressManager step = new ProgressManager(); progress.Steps.Add(new SteppedProgressManagerStep(step, 0.5f, "Compressing")); using (FileStream bzipFile = new FileStream(ReportBaseName + ".tbz", FileMode.Create)) using (FileStream tarStream = new FileStream(ReportBaseName + ".tar", FileMode.Open, FileAccess.Read, FileShare.Read, 262144, FileOptions.DeleteOnClose)) using (BZip2OutputStream bzipStream = new BZip2OutputStream(bzipFile, 262144)) { int lastRead = 0; byte[] buffer = new byte[524288]; while ((lastRead = tarStream.Read(buffer, 0, buffer.Length)) != 0) { bzipStream.Write(buffer, 0, lastRead); step.Completed = tarStream.Position; step.Total = tarStream.Length; if (progressChanged != null) progressChanged(this, new ProgressChangedEventArgs(progress, null)); } } }
public bool Upload(Stream stream, string url) { try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url); request.Proxy = Options.ProxySettings; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password); request.KeepAlive = false; request.UsePassive = !Options.Account.IsActive; using (stream) using (Stream requestStream = request.GetRequestStream()) { ProgressManager progress = new ProgressManager(stream.Length); byte[] buffer = new byte[BufferSize]; int bytesRead; while ((bytesRead = stream.Read(buffer, 0, BufferSize)) > 0) { requestStream.Write(buffer, 0, bytesRead); progress.UpdateProgress(bytesRead); OnProgressChanged(progress); } } WriteOutput("Upload: " + url); return true; } catch (Exception ex) { WriteOutput(string.Format("Error: {0} - Upload: {1}", ex.Message, url)); } return false; }
private bool TransferData(Stream dataStream, Stream requestStream) { dataStream.Position = 0; ProgressManager progress = new ProgressManager(dataStream.Length); int length = (int)Math.Min(BufferSize, dataStream.Length); byte[] buffer = new byte[length]; int bytesRead; while ((bytesRead = dataStream.Read(buffer, 0, length)) > 0) { if (stopUpload) return false; requestStream.Write(buffer, 0, bytesRead); if (progress.ChangeProgress(bytesRead)) { OnProgressChanged(progress); } } return true; }
private static BCFZIP ReadRawData(string bcfPath, out Dictionary <string, Dictionary <string, VisualizationInfo> > tempVisInfoHolder, out Dictionary <string, Dictionary <string, byte[]> > tempFileContentHoder, out Dictionary <string, Dictionary <string, ComponentExtensionInfo> > tempExtInfoHolder) { BCFZIP bcfZip = new BCFZIP(bcfPath); tempVisInfoHolder = new Dictionary <string, Dictionary <string, VisualizationInfo> >(); tempFileContentHoder = new Dictionary <string, Dictionary <string, byte[]> >(); tempExtInfoHolder = new Dictionary <string, Dictionary <string, ComponentExtensionInfo> >(); try { using (ZipArchive archive = ZipFile.OpenRead(bcfPath)) { ProgressManager.InitializeProgress("Gathering information from the BCF file...", archive.Entries.Count); double value = 0; foreach (ZipArchiveEntry entry in archive.Entries) { value++; ProgressManager.StepForward(); string topicId = entry.ExtractGuidFolderName(); if (entry.FullName.EndsWith(".bcfp", StringComparison.OrdinalIgnoreCase)) { XmlSerializer serializer = new XmlSerializer(typeof(ProjectExtension)); XmlReader reader = XmlReader.Create(entry.Open()); if (serializer.CanDeserialize(reader)) { bcfZip.ProjectFile = (ProjectExtension)serializer.Deserialize(reader); continue; } } else if (entry.FullName.EndsWith(".version", StringComparison.OrdinalIgnoreCase)) { XmlSerializer serializer = new XmlSerializer(typeof(Version)); XmlReader reader = XmlReader.Create(entry.Open()); if (serializer.CanDeserialize(reader)) { bcfZip.VersionFile = (Version)serializer.Deserialize(reader); continue; } } else if (entry.FullName.EndsWith(".color", StringComparison.OrdinalIgnoreCase)) { XmlSerializer serializer = new XmlSerializer(typeof(RevitExtensionInfo)); XmlReader reader = XmlReader.Create(entry.Open()); if (serializer.CanDeserialize(reader)) { bcfZip.ExtensionColor = (RevitExtensionInfo)serializer.Deserialize(reader); continue; } } else if (!string.IsNullOrEmpty(topicId) && entry.FullName.EndsWith(".bcf", StringComparison.OrdinalIgnoreCase)) { XmlSerializer serializer = new XmlSerializer(typeof(Markup)); XmlReader reader = XmlReader.Create(entry.Open()); if (serializer.CanDeserialize(reader)) { Markup markup = (Markup)serializer.Deserialize(reader); bcfZip.Markups.Add(markup); } } else if (!string.IsNullOrEmpty(topicId) && entry.FullName.EndsWith(".bcfv", StringComparison.OrdinalIgnoreCase)) { XmlSerializer serializer = new XmlSerializer(typeof(VisualizationInfo)); XmlReader reader = XmlReader.Create(entry.Open()); if (serializer.CanDeserialize(reader)) { VisualizationInfo visInfo = (VisualizationInfo)serializer.Deserialize(reader); if (tempVisInfoHolder.ContainsKey(topicId)) { if (!tempVisInfoHolder[topicId].ContainsKey(entry.Name)) { tempVisInfoHolder[topicId].Add(entry.Name, visInfo); } } else { Dictionary <string, VisualizationInfo> visInfoDictionary = new Dictionary <string, VisualizationInfo>(); visInfoDictionary.Add(entry.Name, visInfo); tempVisInfoHolder.Add(topicId, visInfoDictionary); } } } else if (!string.IsNullOrEmpty(topicId) && entry.FullName.EndsWith(".bcfvx", StringComparison.OrdinalIgnoreCase)) { XmlSerializer serializer = new XmlSerializer(typeof(ComponentExtensionInfo)); XmlReader reader = XmlReader.Create(entry.Open()); if (serializer.CanDeserialize(reader)) { ComponentExtensionInfo extInfo = (ComponentExtensionInfo)serializer.Deserialize(reader); if (tempExtInfoHolder.ContainsKey(topicId)) { if (!tempExtInfoHolder[topicId].ContainsKey(entry.Name)) { tempExtInfoHolder[topicId].Add(entry.Name, extInfo); } } else { Dictionary <string, ComponentExtensionInfo> extInfoDictionary = new Dictionary <string, ComponentExtensionInfo>(); extInfoDictionary.Add(entry.Name, extInfo); tempExtInfoHolder.Add(topicId, extInfoDictionary); } } } else { using (MemoryStream ms = new MemoryStream()) { entry.Open().CopyTo(ms); byte[] byteArray = ms.ToArray(); if (tempFileContentHoder.ContainsKey(topicId)) { if (!tempFileContentHoder[topicId].ContainsKey(entry.Name)) { tempFileContentHoder[topicId].Add(entry.Name, byteArray); } } else { Dictionary <string, byte[]> fileContents = new Dictionary <string, byte[]>(); fileContents.Add(entry.Name, byteArray); tempFileContentHoder.Add(topicId, fileContents); } } } } ProgressManager.FinalizeProgress(); } } catch (Exception ex) { MessageBox.Show("Failed to read data from BCF.\n" + ex.Message, "Read Raw Data", MessageBoxButton.OK, MessageBoxImage.Warning); } return(bcfZip); }
protected override Task ExecuteAsync(CancellationToken cancellationToken) { var progress = new ProgressManager(this); return(ExecuteAsync(progress, cancellationToken)); }
static void Main(string[] args) { var manager = new ProgressManager(); manager.Add(new SimplyProgressive(100, (e, token) => { var total = 100; var value = 0; var r = new Random(); while (value < 100) { Thread.Sleep(r.Next(200, 800)); value += r.Next(1, 30); e.Report(new ProgressValueChangedEventArgs(total, Math.Min(total, value), null)); } e.Report(new ProgressValueChangedEventArgs(total, total, null)); Console.WriteLine("A完成"); })).Start(CancellationToken.None); manager.Add(new SimplyProgressive(100, (e, token) => { var total = 100; var value = 0; var r = new Random(); while (value < 100) { Thread.Sleep(r.Next(200, 800)); value += r.Next(1, 30); e.Report(new ProgressValueChangedEventArgs(total, Math.Min(total, value), null)); } e.Report(new ProgressValueChangedEventArgs(total, total, null)); Console.WriteLine("B完成"); })).Start(CancellationToken.None); manager.Add(new SimplyProgressive(100, (e, token) => { var total = 100; var value = 0; var r = new Random(); while (value < 100) { Thread.Sleep(r.Next(200, 800)); value += r.Next(1, 30); e.Report(new ProgressValueChangedEventArgs(total, Math.Min(total, value), null)); } e.Report(new ProgressValueChangedEventArgs(total, total, null)); Console.WriteLine("C完成"); })).Start(CancellationToken.None); manager.Add(new SimplyProgressive(100, (e, token) => { var total = 100; var value = 0; var r = new Random(); while (value < 100) { Thread.Sleep(r.Next(200, 800)); value += r.Next(1, 30); e.Report(new ProgressValueChangedEventArgs(total, Math.Min(total, value), null)); } e.Report(new ProgressValueChangedEventArgs(total, total, null)); Console.WriteLine("D完成"); })).Start(CancellationToken.None); manager.ProgressValueChanged += Manager_ProgressValueChanged; manager.Start(CancellationToken.None).Wait(); Console.WriteLine("完成"); Console.ReadLine(); }
public static void SetSkin(Skin newSkin) { Debug.Log("setskin"); if (IsUnlocked(newSkin) && theme.horizonSkin != newSkin) { GameObject go = null; foreach (Theme t in _instance.themes) { if (t.horizonSkin == newSkin) { ProgressManager.GetProgress().unlocks.currentSkin = newSkin; skin = newSkin; //Destroy(theme.gameObject); theme = new Theme(); foreach (Transform child in _instance.transform) { Destroy(child.gameObject); } go = Instantiate(_instance.themePrefab, new Vector3(0f, 0f, 0f), Quaternion.identity); go.gameObject.transform.parent = _instance.transform; go.gameObject.transform.localPosition = Vector3.zero; // set theme element to fitting theme Theme compTheme = go.GetComponent <Theme>(); compTheme = t; // set all quad materials to fitting color MeshRenderer[] mrs = go.GetComponentsInChildren <MeshRenderer>(); foreach (MeshRenderer mr in mrs) { WaveSetter wave = mr.GetComponent <WaveSetter>(); int id = wave.id; switch (id) { case 1: mr.material.color = t.horizonColor1; break; case 2: mr.material.color = t.horizonColor2; break; case 3: mr.material.color = t.horizonColor3; break; case 4: mr.material.color = t.horizonColor4; break; case 5: mr.material.color = t.horizonColor5; break; } } theme = t; CamColorSetter.BgColorUpdate(); Debug.Log("Skin " + skin + " was set"); ProgressManager.SaveProgressData(); break; } } } else { Debug.Log("Skin is not unlocked"); } }
private void TranscodeFile(UploadResult result) { StreamableTranscodeResponse transcodeResponse = JsonConvert.DeserializeObject<StreamableTranscodeResponse>(result.Response); if (!string.IsNullOrEmpty(transcodeResponse.Shortcode)) { ProgressManager progress = new ProgressManager(100); if (AllowReportProgress) { OnProgressChanged(progress); } while (!StopUploadRequested) { string statusJson = SendRequest(HttpMethod.GET, URLHelpers.CombineURL(Host, "videos", transcodeResponse.Shortcode)); StreamableStatusResponse response = JsonConvert.DeserializeObject<StreamableStatusResponse>(statusJson); if (response.status > 2) { Errors.Add(response.message); result.IsSuccess = false; break; } else if (response.status == 2) { if (AllowReportProgress) { long delta = 100 - progress.Position; progress.UpdateProgress(delta); OnProgressChanged(progress); } result.IsSuccess = true; if (UseDirectURL && response.files != null && response.files.mp4 != null && !string.IsNullOrEmpty(response.files.mp4.url)) { result.URL = URLHelpers.ForcePrefix(response.files.mp4.url); } else { result.URL = URLHelpers.ForcePrefix(response.url); } break; } if (AllowReportProgress) { long delta = response.percent - progress.Position; progress.UpdateProgress(delta); OnProgressChanged(progress); } Thread.Sleep(100); } } else { Errors.Add("Could not create video"); result.IsSuccess = false; } }
private void ImportLibri(UnitOfWork uof, Deposito deposito, System.Collections.Generic.List <Categoria> listCategorie) { DataTable dt = ReadDatatable(enNomeTabellaExcel.LIBRI.ToString()); var list = dt.AsEnumerable().Select(a => new { // assuming column 0's type is Nullable<long> CodiceABarre = a.Field <string>(0), Titolo = a.Field <string>(1), Autore = a.Field <string>(2), Genere = a.Field <string>(3), Edizione = a.Field <string>(4), Quantita = int.Parse(a.Field <string>(5)), Edizione2 = a.Field <string>(6), Ordine = a.Field <string>(7), Varie1 = a.Field <string>(8), Settore = a.Field <string>(9), PrezzoVendita = decimal.Parse(a.Field <string>(10)), Categoria = "Libri - Altro", }).ToList(); ProgressManager.Instance().Messaggio = "Libri"; ProgressManager.Instance().Value = 0; ProgressManager.Instance().Max = list.Count(); foreach (var item in list.ToList()) { var magItem = new Magazzino(); var articolo = new Articolo(); articolo.Condizione = enCondizioneArticolo.Nuovo; articolo.Prezzo = (item.PrezzoVendita); articolo.CodiceABarre = item.CodiceABarre; var categoriaSel = listCategorie.Where(a => a.Nome.ToUpper() == item.Categoria.ToUpper()).FirstOrDefault(); if (categoriaSel == null) { throw new MessageException(string.Format("Negli strumenti non è specificata una categoria corretta per l'articolo {0}", item.CodiceABarre)); } articolo.CategoriaID = categoriaSel.ID; articolo.Titolo = (item.Autore + " " + item.Titolo + " " + item.Genere + " " + item.Edizione + " " + item.Edizione2).Trim().Replace(" ", " "); articolo.Libro = new Libro { Autore = item.Autore, Edizione = item.Edizione, Edizione2 = item.Edizione2, Genere = item.Genere, Ordine = item.Ordine, Settore = item.Settore }; articolo.Note1 = item.Varie1; articolo.TagImport = "MulinoLibri"; articolo.Condizione = enCondizioneArticolo.NonSpecificato; magItem.Qta = item.Quantita; magItem.Articolo = articolo; magItem.Deposito = deposito; uof.MagazzinoRepository.Add(magItem); ProgressManager.Instance().Value++; } }
public void Start() { if (!CanStart) { return; } IsActive = true; IsSuccessful = false; IsCanceled = false; IsFailed = false; Task.Run(async() => { _cancellationTokenSource = new CancellationTokenSource(); ProgressOperation = ProgressManager?.CreateOperation(); try { // If download option is not set - get the best download option VideoOption ??= await _downloadService.TryGetBestVideoDownloadOptionAsync( Video.Id, Format, QualityPreference ); // It's possible that video has no streams if (VideoOption == null) { throw new InvalidOperationException($"Video '{Video.Id}' contains no streams."); } await _downloadService.DownloadAsync( VideoOption, SubtitleOption, FilePath, ProgressOperation, _cancellationTokenSource.Token ); if (_settingsService.ShouldInjectTags) { await _taggingService.InjectTagsAsync( Video, Format, FilePath, _cancellationTokenSource.Token ); } IsSuccessful = true; } catch (OperationCanceledException) { IsCanceled = true; } catch (Exception ex) { IsFailed = true; // Short error message for expected errors, full for unexpected FailReason = ex is YoutubeExplodeException ? ex.Message : ex.ToString(); } finally { IsActive = false; _cancellationTokenSource?.Dispose(); _cancellationTokenSource = null; ProgressOperation?.Dispose(); } }); }
public void Download(Eraser.Util.ProgressChangedEventHandler handler) { if (DownloadedFile != null && DownloadedFile.Length > 0) throw new InvalidOperationException("The Download method cannot be called " + "before the Download method has been called."); lock (TempPathLock) { if (TempPath == null) { TempPath = new DirectoryInfo(Path.GetTempPath()); TempPath = TempPath.CreateSubdirectory("eraser" + Environment.TickCount.ToString( CultureInfo.InvariantCulture)); } } ProgressManager progress = new ProgressManager(); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Link); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { progress.Total = response.ContentLength; ContentDisposition contentDisposition = null; foreach (string header in response.Headers.AllKeys) if (header.ToUpperInvariant() == "CONTENT-DISPOSITION") contentDisposition = new ContentDisposition(response.Headers[header]); DownloadedFile = new FileInfo(Path.Combine( TempPath.FullName, string.Format(CultureInfo.InvariantCulture, "{0:00}-{1}", ++DownloadFileIndex, contentDisposition == null ? Path.GetFileName(Link.GetComponents(UriComponents.Path, UriFormat.Unescaped)) : contentDisposition.FileName))); using (Stream responseStream = response.GetResponseStream()) using (FileStream fileStream = DownloadedFile.OpenWrite()) { int lastRead = 0; byte[] buffer = new byte[16384]; while ((lastRead = responseStream.Read(buffer, 0, buffer.Length)) != 0) { fileStream.Write(buffer, 0, lastRead); progress.Completed = fileStream.Position; if (handler != null) handler(this, new ProgressChangedEventArgs(progress, null)); } } progress.MarkComplete(); if (handler != null) handler(this, new ProgressChangedEventArgs(progress, null)); } } catch (Exception e) { if (handler != null) handler(this, new ProgressChangedEventArgs(progress, e)); } }
private void EraseFilesystemObject(Task task, FileSystemObjectTarget target) { long dataTotal = 0; List<string> paths = target.GetPaths(out dataTotal); ErasureMethod method = target.Method; TaskEventArgs eventArgs = new TaskEventArgs(task); SteppedProgressManager progress = new SteppedProgressManager(); target.Progress = progress; task.Progress.Steps.Add(new SteppedProgressManager.Step(progress, 1.0f / task.Targets.Count)); for (int i = 0; i < paths.Count; ++i) { ProgressManager step = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(step, 1.0f / paths.Count, S._("Erasing files..."))); task.OnProgressChanged(target, new ProgressChangedEventArgs(step, new TaskProgressChangedEventArgs(paths[i], 0, method.Passes))); StreamInfo info = new StreamInfo(paths[i]); FileSystem fsManager = FileSystemManager.Get( VolumeInfo.FromMountpoint(info.DirectoryName)); if (!info.Exists) { task.Log.LastSessionEntries.Add(new LogEntry(S._("The file {0} was not erased " + "as the file does not exist.", paths[i]), LogLevel.Notice)); continue; } bool isReadOnly = false; try { if (isReadOnly = info.IsReadOnly) info.IsReadOnly = false; if ((info.Attributes & FileAttributes.Compressed) != 0 || (info.Attributes & FileAttributes.Encrypted) != 0 || (info.Attributes & FileAttributes.SparseFile) != 0) { task.Log.LastSessionEntries.Add(new LogEntry(S._("The file {0} could " + "not be erased because the file was either compressed, encrypted or " + "a sparse file.", info.FullName), LogLevel.Error)); } fsManager.EraseFileSystemObject(info, method, delegate(long lastWritten, long totalData, int currentPass) { if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); step.Completed += lastWritten; step.Total = totalData; task.OnProgressChanged(target, new ProgressChangedEventArgs(step, new TaskProgressChangedEventArgs(info.FullName, currentPass, method.Passes))); }); FileInfo fileInfo = info.File; if (fileInfo != null) fsManager.DeleteFile(fileInfo); step.Completed = step.Total = 1; } catch (UnauthorizedAccessException) { task.Log.LastSessionEntries.Add(new LogEntry(S._("The file {0} could not " + "be erased because the file's permissions prevent access to the file.", info.FullName), LogLevel.Error)); } catch (FileLoadException) { if (!ManagerLibrary.Settings.ForceUnlockLockedFiles) throw; List<System.Diagnostics.Process> processes = new List<System.Diagnostics.Process>(); foreach (OpenHandle handle in OpenHandle.Items) if (handle.Path == paths[i]) processes.Add(System.Diagnostics.Process.GetProcessById(handle.ProcessId)); StringBuilder processStr = new StringBuilder(); foreach (System.Diagnostics.Process process in processes) processStr.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0}, ", process.MainModule.FileName); task.Log.LastSessionEntries.Add(new LogEntry(S._( "Could not force closure of file \"{0}\" (locked by {1})", paths[i], processStr.ToString().Remove(processStr.Length - 2)), LogLevel.Error)); } finally { if (isReadOnly && info.Exists && !info.IsReadOnly) info.IsReadOnly = isReadOnly; } } if (target is FolderTarget) { ProgressManager step = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(step, 0.0f, S._("Removing folders..."))); FolderTarget fldr = (FolderTarget)target; FileSystem fsManager = FileSystemManager.Get(VolumeInfo.FromMountpoint(fldr.Path)); Action<DirectoryInfo> eraseEmptySubFolders = null; eraseEmptySubFolders = delegate(DirectoryInfo info) { foreach (DirectoryInfo subDir in info.GetDirectories()) eraseEmptySubFolders(subDir); task.OnProgressChanged(target, new ProgressChangedEventArgs(step, new TaskProgressChangedEventArgs(info.FullName, 0, 0))); FileSystemInfo[] files = info.GetFileSystemInfos(); if (files.Length == 0) fsManager.DeleteFolder(info); }; eraseEmptySubFolders(new DirectoryInfo(fldr.Path)); if (fldr.DeleteIfEmpty) { DirectoryInfo info = new DirectoryInfo(fldr.Path); task.OnProgressChanged(target, new ProgressChangedEventArgs(step, new TaskProgressChangedEventArgs(info.FullName, 0, 0))); bool isVolumeRoot = info.Parent == null; foreach (VolumeInfo volume in VolumeInfo.Volumes) foreach (string mountPoint in volume.MountPoints) if (info.FullName == mountPoint) isVolumeRoot = true; if (!isVolumeRoot && info.Exists && info.GetFiles("*", SearchOption.AllDirectories).Length == 0) fsManager.DeleteFolder(info); } } if (target is RecycleBinTarget) { ProgressManager step = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(step, 0.0f, S._("Emptying recycle bin..."))); task.OnProgressChanged(target, new ProgressChangedEventArgs(step, new TaskProgressChangedEventArgs(string.Empty, 0, 0))); ShellApi.EmptyRecycleBin(EmptyRecycleBinOptions.NoConfirmation | EmptyRecycleBinOptions.NoProgressUI | EmptyRecycleBinOptions.NoSound); } target.Progress = null; }
private void EraseUnusedSpace(Task task, UnusedSpaceTarget target, TaskProgressManager progress) { if (!AdvApi.IsAdministrator()) { if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version >= new Version(6, 0)) { throw new UnauthorizedAccessException(S._("The program does not have the " + "required permissions to erase the unused space on disk. Run the program " + "as an administrator and retry the operation.")); } else throw new UnauthorizedAccessException(S._("The program does not have the " + "required permissions to erase the unused space on disk")); } if (VolumeInfo.FromMountpoint(target.Drive).HasQuota) task.Log.LastSessionEntries.Add(new LogEntry(S._("The drive which is having its " + "unused space erased has disk quotas active. This will prevent the complete " + "erasure of unused space and will pose a security concern"), LogLevel.Warning)); ErasureMethod method = target.Method; DirectoryInfo info = new DirectoryInfo(target.Drive); VolumeInfo volInfo = VolumeInfo.FromMountpoint(target.Drive); FileSystem fsManager = FileSystemManager.Get(volInfo); if (target.EraseClusterTips) { progress.Event.CurrentTargetStatus = S._("Searching for files' cluster tips..."); progress.Event.CurrentTargetTotalPasses = method.Passes; progress.Event.CurrentItemProgress = -1.0f; progress.Event.TimeLeft = new TimeSpan(0, 0, -1); ProgressManager tipProgress = new ProgressManager(); tipProgress.Start(); ClusterTipsSearchProgress searchProgress = delegate(string path) { progress.Event.CurrentItemName = path; task.OnProgressChanged(progress.Event); if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); }; ClusterTipsEraseProgress eraseProgress = delegate(int currentFile, int totalFiles, string currentFilePath) { tipProgress.Total = totalFiles; tipProgress.Completed = currentFile; progress.Event.CurrentTargetStatus = S._("Erasing cluster tips..."); progress.Event.CurrentItemName = currentFilePath; progress.Event.CurrentItemProgress = tipProgress.Progress; progress.Event.CurrentTargetProgress = progress.Event.CurrentItemProgress / 10; progress.Event.TimeLeft = tipProgress.TimeLeft; task.OnProgressChanged(progress.Event); if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); }; fsManager.EraseClusterTips(VolumeInfo.FromMountpoint(target.Drive), method, task.Log, searchProgress, eraseProgress); } info = info.CreateSubdirectory(Path.GetFileName( FileSystem.GenerateRandomFileName(info, 18))); try { if (Eraser.Util.File.IsCompressed(info.FullName)) Eraser.Util.File.SetCompression(info.FullName, false); progress.Event.CurrentTargetStatus = S._("Erasing unused space..."); progress.Event.CurrentItemName = target.Drive; task.OnProgressChanged(progress.Event); while (volInfo.AvailableFreeSpace > 0) { string currFile = FileSystem.GenerateRandomFileName(info, 18); using (FileStream stream = new FileStream(currFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, 8, FileOptions.WriteThrough)) { long streamLength = Math.Min(ErasureMethod.FreeSpaceFileUnit, volInfo.AvailableFreeSpace); while (true) try { stream.SetLength(streamLength); break; } catch (IOException) { if (streamLength > volInfo.ClusterSize) streamLength -= volInfo.ClusterSize; else throw; } method.Erase(stream, long.MaxValue, PrngManager.GetInstance(ManagerLibrary.Settings.ActivePrng), delegate(long lastWritten, long totalData, int currentPass) { progress.Completed = Math.Min(progress.Total, progress.Completed + lastWritten); progress.Event.CurrentItemPass = currentPass; progress.Event.CurrentItemProgress = progress.Progress; if (target.EraseClusterTips) progress.Event.CurrentTargetProgress = (float) (0.1f + progress.Event.CurrentItemProgress * 0.8f); else progress.Event.CurrentTargetProgress = (float) (progress.Event.CurrentItemProgress * 0.9f); progress.Event.TimeLeft = progress.TimeLeft; task.OnProgressChanged(progress.Event); if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); } ); } } progress.Event.CurrentItemName = S._("Old resident file system table files"); task.OnProgressChanged(progress.Event); fsManager.EraseOldFileSystemResidentFiles(volInfo, info, method, null); } finally { progress.Event.CurrentTargetStatus = S._("Removing temporary files..."); task.OnProgressChanged(progress.Event); fsManager.DeleteFolder(info); } progress.Event.CurrentTargetStatus = S._("Erasing unused directory structures..."); ProgressManager fsEntriesProgress = new ProgressManager(); fsEntriesProgress.Start(); fsManager.EraseDirectoryStructures(volInfo, delegate(int currentFile, int totalFiles) { if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); fsEntriesProgress.Total = totalFiles; fsEntriesProgress.Completed = currentFile; progress.Event.TimeLeft = fsEntriesProgress.TimeLeft; progress.Event.CurrentItemProgress = fsEntriesProgress.Progress; progress.Event.CurrentTargetProgress = (float)( 0.9 + progress.Event.CurrentItemProgress / 10); task.OnProgressChanged(progress.Event); } ); }
public static ProgressState.SavableVegetableList GetVegetablesOnLevel(int index) { return(ProgressManager.GetVegetablesOnLevel(index)); }
public ImplementationHandler(ImplementationRegistrationOptions registrationOptions, ProgressManager progressManager) { _options = registrationOptions; ProgressManager = progressManager; }
// private InterstitialAd interstitial; void Start() { shI = GetComponent<ShareInfo>(); shI.text = "Look, there's an amazing game! You can play it too!\n https://play.google.com/store/apps/details?id=com.azinecllc.flyingadventures"; halfFadeTimeWFS = new WaitForSeconds(fadeTime / 2); fadeTimeWFS = new WaitForSeconds(fadeTime); wfeof = new WaitForEndOfFrame(); levelEndWaitTimeWFS = new WaitForSeconds(levelEndWaitTime); pm = gameObject.GetComponent<ProgressManager>(); anim = FadePlane.GetComponent<Animator>(); anim.SetFloat("speedMultiplier", 1 / fadeTime); StartCoroutine(WaitForSplash()); if (GameObject.FindGameObjectsWithTag(UI.tag).Length > 1) { Destroy(GameObject.FindGameObjectsWithTag(UI.tag)[1]); } if (GameObject.FindGameObjectsWithTag("es").Length > 1) { Destroy(GameObject.FindGameObjectsWithTag("es")[1]); } if (GameObject.FindGameObjectsWithTag(gameObject.tag).Length > 1) { Destroy(gameObject); } }
private void TranscodeFile(string key, UploadResult result) { Dictionary<string, string> args = new Dictionary<string, string>(); if (NoResize) args.Add("noResize", "true"); if (IgnoreExisting) args.Add("noMd5", "true"); string url = CreateQuery("https://upload.gfycat.com/transcodeRelease/" + key, args); string transcodeJson = SendRequest(HttpMethod.GET, url); GfycatTranscodeResponse transcodeResponse = JsonConvert.DeserializeObject<GfycatTranscodeResponse>(transcodeJson); if (transcodeResponse.IsOk) { ProgressManager progress = new ProgressManager(10000); if (AllowReportProgress) { OnProgressChanged(progress); } while (!StopUploadRequested) { string statusJson = SendRequest(HttpMethod.GET, "https://upload.gfycat.com/status/" + key); GfycatStatusResponse response = JsonConvert.DeserializeObject<GfycatStatusResponse>(statusJson); if (response.Error != null) { Errors.Add(response.Error); result.IsSuccess = false; break; } else if (response.GfyName != null) { result.IsSuccess = true; result.URL = "https://gfycat.com/" + response.GfyName; break; } if (AllowReportProgress && progress.UpdateProgress((progress.Length - progress.Position) / response.Time)) { OnProgressChanged(progress); } Thread.Sleep(100); } } else { Errors.Add(transcodeResponse.Error); result.IsSuccess = false; } }
public MyDocumentSymbolHandler(ProgressManager progressManager) : base(new DocumentSymbolRegistrationOptions() { DocumentSelector = DocumentSelector.ForLanguage("csharp") }, progressManager) { }
public DefinitionHandler(DefinitionRegistrationOptions registrationOptions, ProgressManager progressManager) { _options = registrationOptions; ProgressManager = progressManager; }
public MyWorkspaceSymbolsHandler(ProgressManager progressManager, ILogger <MyWorkspaceSymbolsHandler> logger) : base(new WorkspaceSymbolRegistrationOptions() { }, progressManager) { this.logger = logger; }
public ExecuteCommandHandler(ExecuteCommandRegistrationOptions registrationOptions, ProgressManager progressManager) { _options = registrationOptions; ProgressManager = progressManager; }
public override async Task <Container <SymbolInformation> > Handle(WorkspaceSymbolParams request, CancellationToken cancellationToken) { using var reporter = ProgressManager.WorkDone(request, new WorkDoneProgressBegin() { Cancellable = true, Message = "This might take a while...", Title = "Some long task....", Percentage = 0 }); using var partialResults = ProgressManager.For(request, cancellationToken); if (partialResults != null) { await Task.Delay(2000, cancellationToken); reporter.OnNext(new WorkDoneProgressReport() { Cancellable = true, Percentage = 20 }); await Task.Delay(500, cancellationToken); reporter.OnNext(new WorkDoneProgressReport() { Cancellable = true, Percentage = 40 }); await Task.Delay(500, cancellationToken); reporter.OnNext(new WorkDoneProgressReport() { Cancellable = true, Percentage = 50 }); await Task.Delay(500, cancellationToken); partialResults.OnNext(new[] { new SymbolInformation() { ContainerName = "Partial Container", Deprecated = true, Kind = SymbolKind.Constant, Location = new Location() { Range = new OmniSharp.Extensions.LanguageServer.Protocol.Models.Range(new Position(2, 1), new Position(2, 10)) { } }, Name = "Partial name" } }); reporter.OnNext(new WorkDoneProgressReport() { Cancellable = true, Percentage = 70 }); await Task.Delay(500, cancellationToken); reporter.OnNext(new WorkDoneProgressReport() { Cancellable = true, Percentage = 90 }); partialResults.OnCompleted(); return(new SymbolInformation[] { }); } try { return(new[] { new SymbolInformation() { ContainerName = "Container", Deprecated = true, Kind = SymbolKind.Constant, Location = new Location() { Range = new OmniSharp.Extensions.LanguageServer.Protocol.Models.Range(new Position(1, 1), new Position(1, 10)) { } }, Name = "name" } }); } finally { reporter.OnNext(new WorkDoneProgressReport() { Cancellable = true, Percentage = 100 }); } }
public void LevelBeaten() { Debug.Log(TAG + "level beaten menu."); int curFolder = levelManager.GetCurFolder(); int curLevel = levelManager.GetCurLevelNum(); bool isCustom = levelManager.GetIsCustom(); tutorialManager.FadeOut(); Level[] levels; if (isCustom) { levels = levelManager.GetCustomLevels(curFolder); } else { levels = levelManager.GetLevels(); } //If still levels left if (levels.Length > curLevel + 1) { menuAllLevelsBeaten.SetActive(false); menuLevelBeaten.SetActive(true); levelBeatenAni.Play("fadeInComplete"); ProgressManager.CheckLevelBeaten(curFolder, curLevel); return; } //if this was the last level //check if there are more chapters //don't do it for custom chapters if (levelManager.GetIsCustom()) { menuAllLevelsBeaten.SetActive(false); menuLevelBeaten.SetActive(false); backToCustomLevels.SetActive(true); customFolderBeatenAni.Play("fadeInComplete"); return; } if (chapterManager.GetChapters().Length > levelManager.GetCurFolder() + 1) { Debug.Log(TAG + "there are more chapters"); if (mainManager.GetISDemo() && levelManager.GetCurFolder() + 1 > 2) { OpenDemoMenu(); ProgressManager.CheckChapterBeaten(curFolder); return; } folderBeatenText.text = "Chapter " + (curFolder + 1).ToString() + " Complete"; menuLevelBeaten.SetActive(false); menuAllLevelsBeaten.SetActive(true); folderBeatenAni.Play("fadeInComplete"); ProgressManager.CheckChapterBeaten(curFolder); return; } Debug.Log(TAG + "all levels complete"); menuLevelBeaten.SetActive(false); //menuGameOver.SetActive(true); folderBeatenAni.Play("fadeInComplete"); //Show the end credits GameObject g = Instantiate(endCreditsPrefab); menuButton.SetActive(false); resetButton.SetActive(false); g.transform.position = c.transform.position - new Vector3(0, 20, 0); CreditsManager creditManager = g.GetComponent <CreditsManager>(); creditManager.LoadCredits(this, soundManager); creditManager.CreateCreditOb(); }
public async Task <TimeSeries> LoadData(ValidFileInfo fileInfo) { return(await Task.Run(() => { var timeSeries = new TimeSeries { Source = fileInfo.Source }; var stopWatch = new Stopwatch(); stopWatch.Start(); var progressItem = new ProgressManager { TimeStamp = DateTime.UtcNow, Progress = 1, Action = "XmlLoader Load data", Message = $"Xml Loader Load data started {fileInfo.Source}" }; fileInfo.ProgressLogger?.Report(progressItem); using (Stream s = File.OpenRead(fileInfo.Value.FullName)) { var xdoc = XElement.Load(s, LoadOptions.None); foreach (var element in xdoc.Elements()) { //.AsParallel() hold of parallising for the moment. //this can be improved to hold a column mappingname names. var tsdp = new TimeSeriesDataPoint { Date = Utils.ConvertValueToDate(element, "date"), Symbol = Utils.ConvertValueToString(element, "Name"), Close = Utils.ConvertValueToDouble(element, "close"), Source = fileInfo.Source, LastUpdated = "AutoLoad", UpdateDate = DateTime.UtcNow }; timeSeries.Add(tsdp); } stopWatch.Stop(); timeSeries.LoadTime = stopWatch.Elapsed; progressItem = new ProgressManager { TimeStamp = DateTime.UtcNow, Progress = 1, Action = "XmlLoader Load data", Message = $"Xml Loader Load data stopped {fileInfo.Source}" }; fileInfo.ProgressLogger?.Report(progressItem); return timeSeries; } })); //return await Task.Run(() => //{ // var deserializer = new XmlSerializer(typeof(TimeSeries)); // Stream s = File.OpenRead(fileInfo.Value.FullName); // var xdoc = XElement.Load(s, LoadOptions.None); // //s.Position = 0; // //var x = new StreamReader(s); // //var xy = deserializer.Deserialize(x); // using (StreamReader reader = new StreamReader(fileInfo.Value.FullName)) // { // var obj = deserializer.Deserialize(reader); // var xmlData = (List<TimeSeriesDataPoint>)obj; // return new TimeSeries(); // } //}); }
public static GameObject ShowBlockingProgressUiFor(this ViewStack self, ProgressManager prManager) { return(ShowBlockingProgressUiFor(self, "Progress/BlockingProgressOverlay1", prManager)); }
void Start() { ProgressManager manager = GameObject.Find("Player").GetComponent <ProgressManager>(); manager.OnProgressStateChange += ProgressStateChange; }
private void ImportArticoli(UnitOfWork uof, Deposito deposito, System.Collections.Generic.List <Categoria> listCategorie) { DataTable dt = ReadDatatable(enNomeTabellaExcel.artic.ToString()); try { var list = dt.AsEnumerable().Select(a => new { // assuming column 0's type is Nullable<long> CodiceABarre = a.Field <string>(0), Marca = a.Field <string>(1), Articolo = a.Field <string>(2), Varie1 = a.Field <string>(3), Varie2 = a.Field <string>(4), Varie3 = a.Field <string>(5), PrezzoVendita = a.Field <string>(6), PrezzoAcq = a.Field <string>(7), Rivenditore = a.Field <string>(8), Quantita = a.Field <string>(9), Categoria = "<Non Specificato>", }).ToList(); ProgressManager.Instance().Messaggio = "Articoli"; ProgressManager.Instance().Value = 0; ProgressManager.Instance().Max = list.Count(); foreach (var item in list.ToList()) { var magItem = new Magazzino(); var articolo = new Articolo(); articolo.Condizione = enCondizioneArticolo.Nuovo; articolo.Strumento.Marca = item.Marca; articolo.Prezzo = decimal.Parse(item.PrezzoVendita); articolo.CodiceABarre = item.CodiceABarre; var categoriaSel = listCategorie.Where(a => a.Nome.ToUpper() == item.Categoria.ToUpper()).FirstOrDefault(); if (categoriaSel == null) { throw new MessageException(string.Format("Nei libri non è specificata una categoria corretta per l'articolo {0}", item.CodiceABarre)); } articolo.CategoriaID = categoriaSel.ID; articolo.Titolo = item.Marca + " " + item.Articolo; if (!string.IsNullOrEmpty(item.Varie1) && !item.Varie1.Contains("?")) { articolo.Titolo += " " + item.Varie1; } articolo.Strumento.Rivenditore = item.Rivenditore; articolo.Note1 = item.Varie1; articolo.Note2 = item.Varie2; articolo.Note3 = item.Varie3; articolo.Condizione = enCondizioneArticolo.NonSpecificato; articolo.PrezzoAcquisto = decimal.Parse(item.PrezzoAcq); articolo.TagImport = "MulinoArticoli"; magItem.Qta = int.Parse(item.Quantita); magItem.Articolo = articolo; magItem.Deposito = deposito; magItem.PrezzoAcquisto = decimal.Parse(item.PrezzoAcq); //uof.ArticoliRepository.Find(a=>a.) uof.MagazzinoRepository.Add(magItem); ProgressManager.Instance().Value++; } } catch (Exception ex) { throw ex; } }
void Start() { pm = ProgressManager.instance; }
/// <summary> /// Erases the provided stream, and updates progress using the provided /// progress manager. /// </summary> /// <param name="info">The information regarding the stream that needs erasure.</param> /// <param name="progress">The progress manager for the erasure of the current /// stream.</param> protected void EraseStream(StreamInfo info, ProgressManager progress) { //Check that the file exists - we do not want to bother erasing nonexistant files if (!info.Exists) { Logger.Log(S._("The file {0} was not erased as the file does not exist.", info.FileName), LogLevel.Notice); return; } //Get the filesystem provider to handle the secure file erasures IFileSystem fsManager = Host.Instance.FileSystems[ VolumeInfo.FromMountPoint(info.DirectoryName)]; bool isReadOnly = false; try { //Update the task progress IErasureMethod method = EffectiveMethod; //Remove the read-only flag, if it is set. if (isReadOnly = info.IsReadOnly) { info.IsReadOnly = false; } //Define the callback function for progress reporting. ErasureMethodProgressFunction callback = delegate(long lastWritten, long totalData, int currentPass) { if (Task.Canceled) { throw new OperationCanceledException(S._("The task was cancelled.")); } progress.Tag = new int[] { currentPass, method.Passes }; progress.Total = totalData; progress.Completed += lastWritten; }; TryEraseStream(fsManager, method, info, callback); //Remove the file. FileInfo fileInfo = info.File; if (fileInfo != null) { fsManager.DeleteFile(fileInfo); } progress.MarkComplete(); } catch (UnauthorizedAccessException) { Logger.Log(S._("The file {0} could not be erased because the file's " + "permissions prevent access to the file.", info.FullName), LogLevel.Error); } catch (SharingViolationException e) { Logger.Log(S._("The file {0} could not be erased because the file is " + "currently in used by another application.", info.FullName), LogLevel.Error); } finally { //Re-set the read-only flag if the file exists (i.e. there was an error) if (isReadOnly && info.Exists && !info.IsReadOnly) { info.IsReadOnly = isReadOnly; } } }
public JsonResult GetStatus() { return(Json(ProgressManager.GetStats())); }
private void installer_DoWork(object sender, DoWorkEventArgs e) { List<DownloadInfo> downloads = (List<DownloadInfo>)e.Argument; ProgressManager progress = new ProgressManager(); progress.Total = downloads.Count; foreach (DownloadInfo download in downloads) { ++progress.Completed; try { installer_ProgressChanged(download, new ProgressChangedEventArgs(progress, null)); download.Install(); installer_ProgressChanged(download, new ProgressChangedEventArgs(progress, null)); } catch (Exception ex) { installer_ProgressChanged(download, new ProgressChangedEventArgs(progress, ex)); } } e.Result = e.Argument; }
private void OnApplicationQuit() { ProgressManager.SaveProgressData(); PlayGamesPlatform.Instance.SignOut(); }
private void bw_AsyncUploadDoWork(object sender, DoWorkEventArgs e) { try { AsyncUploadHelper upload = (AsyncUploadHelper)e.Argument; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(upload.URL); request.Proxy = Options.ProxySettings; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password); request.KeepAlive = false; request.UsePassive = !Options.Account.IsActive; using (upload.Stream) using (Stream requestStream = request.GetRequestStream()) { ProgressManager progress = new ProgressManager(upload.Stream.Length); byte[] buffer = new byte[BufferSize]; int bytesRead; while ((bytesRead = upload.Stream.Read(buffer, 0, BufferSize)) > 0) { requestStream.Write(buffer, 0, bytesRead); progress.UpdateProgress(bytesRead); upload.BackgroundWorker.ReportProgress((int)progress.Percentage, progress); } } } catch (Exception ex) { DebugHelper.WriteException(ex); } }
public static void SetScene(ActiveScene newScene) { if (!switchingScene) { switchingScene = true; ProgressManager.SaveProgressData(); currentScene = newScene; onSceneChange.Invoke(newScene); switch (newScene) { case ActiveScene.welcome: if (SceneManager.GetActiveScene().name != "Welcome") { _instance.StartCoroutine(_instance.cSetScene("Welcome")); } break; case ActiveScene.home: _instance.StartCoroutine(_instance.cSetScene("Home")); break; case ActiveScene.shop: if (SceneManager.GetActiveScene().name != "Shop") { _instance.StartCoroutine(_instance.cSetScene("Shop")); } break; case ActiveScene.levelselection: if (SceneManager.GetActiveScene().name != "Levelselection") { _instance.StartCoroutine(_instance.cSetScene("Levelselection")); } break; case ActiveScene.tutorial: if (SceneManager.GetActiveScene().name != "Tutorial") { _instance.StartCoroutine(_instance.cSetScene("Tutorial")); } break; case ActiveScene.gopro: if (SceneManager.GetActiveScene().name != "GoPro") { _instance.StartCoroutine(_instance.cSetScene("GoPro")); } break; case ActiveScene.game: if (SceneManager.GetActiveScene().name != "Game") { _instance.StartCoroutine(_instance.cSetScene("Game")); } break; case ActiveScene.settings: if (SceneManager.GetActiveScene().name != "Settings") { _instance.StartCoroutine(_instance.cSetScene("Settings")); } break; case ActiveScene.credits: if (SceneManager.GetActiveScene().name != "Credits") { _instance.StartCoroutine(_instance.cSetScene("Credits")); } break; case ActiveScene.achievements: if (SceneManager.GetActiveScene().name != "Achievements") { #if UNITY_EDITOR _instance.StartCoroutine(_instance.cSetScene("Home")); #elif UNITY_ANDROID Social.localUser.Authenticate((bool success) => { if (success) { _instance.StartCoroutine(_instance.cSetSceneAchievement()); } else { SetScene(ActiveScene.home); } }); #endif } break; case ActiveScene.editor: //if (ProgressManager.GetProgress().proVersion) //{ if (SceneManager.GetActiveScene().name != "EditorSelection" && SceneManager.GetActiveScene().name != "Game") { _instance.StartCoroutine(_instance.cSetScene("EditorSelection")); } else { _instance.StartCoroutine(_instance.cSetScene("Leveleditor")); } // } break; } } }
public void Submit(ProgressChangedEventHandler progressChanged) { SteppedProgressManager overallProgress = new SteppedProgressManager(); Compress(overallProgress, progressChanged); using (FileStream bzipFile = new FileStream(ReportBaseName + ".tbz", FileMode.Open, FileAccess.Read, FileShare.Read, 131072, FileOptions.DeleteOnClose)) using (Stream logFile = Report.DebugLog) { PostDataBuilder builder = new PostDataBuilder(); builder.AddPart(new PostDataField("action", "upload")); builder.AddPart(new PostDataFileField("crashReport", "Report.tbz", bzipFile)); AddStackTraceToRequest(Report.StackTrace, builder); WebRequest reportRequest = HttpWebRequest.Create(BlackBoxServer); reportRequest.ContentType = builder.ContentType; reportRequest.Method = "POST"; reportRequest.Timeout = int.MaxValue; using (Stream formStream = builder.Stream) { ProgressManager progress = new ProgressManager(); overallProgress.Steps.Add(new SteppedProgressManagerStep( progress, 0.5f, "Uploading")); reportRequest.ContentLength = formStream.Length; using (Stream requestStream = reportRequest.GetRequestStream()) { int lastRead = 0; byte[] buffer = new byte[32768]; while ((lastRead = formStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, lastRead); progress.Completed = formStream.Position; progress.Total = formStream.Length; progressChanged(this, new ProgressChangedEventArgs(overallProgress, null)); } } } try { reportRequest.GetResponse(); Report.Submitted = true; } catch (WebException e) { using (Stream responseStream = e.Response.GetResponseStream()) { try { XmlReader reader = XmlReader.Create(responseStream); reader.ReadToFollowing("error"); throw new InvalidDataException(string.Format(CultureInfo.CurrentCulture, "The server encountered a problem while processing the request: {0}", reader.ReadString())); } catch (XmlException) { } } throw new InvalidDataException(((HttpWebResponse)e.Response).StatusDescription); } } }
public static bool IsLevelAvaliable(int index) { return(ProgressManager.IsLevelAvaliable(index)); }
protected bool TransferData(Stream dataStream, Stream requestStream) { if (dataStream.CanSeek) { dataStream.Position = 0; } ProgressManager progress = new ProgressManager(dataStream.Length); int length = (int)Math.Min(BufferSize, dataStream.Length); byte[] buffer = new byte[length]; int bytesRead; while (!StopUploadRequested && (bytesRead = dataStream.Read(buffer, 0, length)) > 0) { requestStream.Write(buffer, 0, bytesRead); if (AllowReportProgress && progress.UpdateProgress(bytesRead)) { OnProgressChanged(progress); } } return !StopUploadRequested; }
public static int GetScoreOnLevel(int index) { return(ProgressManager.GetScoreOnLevel(index)); }
private void uploader_ProgressChanged(ProgressManager progress) { if (progress != null) { Info.Progress = progress; if (threadWorker != null) { threadWorker.InvokeAsync(OnUploadProgressChanged); } else { OnUploadProgressChanged(); } } }
public static void SetScoreOnLevel(int index, int score) { ProgressManager.SetScoreOnLevel(index, score); }
private void EraseUnusedSpace(Task task, UnusedSpaceTarget target) { if (!AdvApi.IsAdministrator()) { if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version >= new Version(6, 0)) { throw new UnauthorizedAccessException(S._("The program does not have the " + "required permissions to erase the unused space on disk. Run the program " + "as an administrator and retry the operation.")); } else throw new UnauthorizedAccessException(S._("The program does not have the " + "required permissions to erase the unused space on disk.")); } if (SystemRestore.GetInstances().Count != 0) { task.Log.LastSessionEntries.Add(new LogEntry(S._("The drive {0} has System " + "Restore or Volume Shadow Copies enabled. This may allow copies of files " + "stored on the disk to be recovered and pose a security concern.", target.Drive), LogLevel.Warning)); } if (VolumeInfo.FromMountpoint(target.Drive).HasQuota) task.Log.LastSessionEntries.Add(new LogEntry(S._("The drive {0} has disk quotas " + "active. This will prevent the complete erasure of unused space and may pose " + "a security concern.", target.Drive), LogLevel.Warning)); ErasureMethod method = target.Method; DirectoryInfo info = new DirectoryInfo(target.Drive); VolumeInfo volInfo = VolumeInfo.FromMountpoint(target.Drive); FileSystem fsManager = FileSystemManager.Get(volInfo); SteppedProgressManager progress = new SteppedProgressManager(); target.Progress = progress; task.Progress.Steps.Add(new SteppedProgressManager.Step( progress, 1.0f / task.Targets.Count)); if (target.EraseClusterTips) { ProgressManager tipSearch = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(tipSearch, 0.0f, S._("Searching for files' cluster tips..."))); tipSearch.Total = 1; ClusterTipsSearchProgress searchProgress = delegate(string path) { if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); task.OnProgressChanged(target, new ProgressChangedEventArgs(tipSearch, new TaskProgressChangedEventArgs(path, 0, 0))); }; ProgressManager tipProgress = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(tipProgress, 0.1f, S._("Erasing cluster tips..."))); ClusterTipsEraseProgress eraseProgress = delegate(int currentFile, int totalFiles, string currentFilePath) { tipSearch.Completed = tipSearch.Total; tipProgress.Total = totalFiles; tipProgress.Completed = currentFile; task.OnProgressChanged(target, new ProgressChangedEventArgs(tipProgress, new TaskProgressChangedEventArgs(currentFilePath, 0, 0))); if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); }; fsManager.EraseClusterTips(VolumeInfo.FromMountpoint(target.Drive), method, task.Log, searchProgress, eraseProgress); } info = info.CreateSubdirectory(Path.GetFileName( FileSystem.GenerateRandomFileName(info, 18))); try { if (Eraser.Util.File.IsCompressed(info.FullName)) Eraser.Util.File.SetCompression(info.FullName, false); ProgressManager mainProgress = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(mainProgress, target.EraseClusterTips ? 0.8f : 0.9f, S._("Erasing unused space..."))); while (volInfo.AvailableFreeSpace > 0) { string currFile = FileSystem.GenerateRandomFileName(info, 18); using (FileStream stream = new FileStream(currFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, 8, FileOptions.WriteThrough)) { mainProgress.Total = mainProgress.Completed + volInfo.AvailableFreeSpace; long streamLength = Math.Min(ErasureMethod.FreeSpaceFileUnit, mainProgress.Total); while (true) try { stream.SetLength(streamLength); break; } catch (IOException) { if (streamLength > volInfo.ClusterSize) streamLength -= volInfo.ClusterSize; else throw; } method.Erase(stream, long.MaxValue, PrngManager.GetInstance(ManagerLibrary.Settings.ActivePrng), delegate(long lastWritten, long totalData, int currentPass) { mainProgress.Completed += lastWritten; task.OnProgressChanged(target, new ProgressChangedEventArgs(mainProgress, new TaskProgressChangedEventArgs(target.Drive, currentPass, method.Passes))); if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); } ); } } mainProgress.Completed = mainProgress.Total; ProgressManager residentProgress = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(residentProgress, 0.05f, S._("Old resident file system table files"))); fsManager.EraseOldFileSystemResidentFiles(volInfo, info, method, delegate(int currentFile, int totalFiles) { residentProgress.Completed = currentFile; residentProgress.Total = totalFiles; task.OnProgressChanged(target, new ProgressChangedEventArgs(residentProgress, new TaskProgressChangedEventArgs(string.Empty, 0, 0))); if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); } ); residentProgress.Completed = residentProgress.Total = 1; } finally { ProgressManager tempFiles = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(tempFiles, 0.0f, S._("Removing temporary files..."))); task.OnProgressChanged(target, new ProgressChangedEventArgs(tempFiles, new TaskProgressChangedEventArgs(string.Empty, 0, 0))); fsManager.DeleteFolder(info); tempFiles.Completed = tempFiles.Total = 1; } ProgressManager structureProgress = new ProgressManager(); progress.Steps.Add(new SteppedProgressManager.Step(structureProgress, 0.05f, S._("Erasing unused directory structures..."))); fsManager.EraseDirectoryStructures(volInfo, delegate(int currentFile, int totalFiles) { if (currentTask.Canceled) throw new OperationCanceledException(S._("The task was cancelled.")); structureProgress.Total = totalFiles; structureProgress.Completed = currentFile; task.OnProgressChanged(target, new ProgressChangedEventArgs(structureProgress, new TaskProgressChangedEventArgs(string.Empty, 0, 0))); } ); structureProgress.Completed = structureProgress.Total; target.Progress = null; }
public static void SetStarsOnLevel(int index, int stars) { ProgressManager.SetStarsOnLevel(index, stars); }