public async void Download(FileDTO file) { var directory = "Downloads"; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var destination = Path.Combine(directory, $"{file.Id.ToString()}{Path.GetExtension(file.Name)}"); for (int part = 1; part <= file.Parts; part++) { var filePartResponse = await _httpManager.GetAsync <FilePartDTO>($"api/Files/{file.Id}/DownloadPart/{part}"); if (filePartResponse.Error != null) { Failed?.Invoke(filePartResponse.Error.ErrorDescription); return; } using (var fs = new FileStream(destination, FileMode.Append, FileAccess.Write, FileShare.Write)) { fs.Write(filePartResponse.Data.Content, 0, filePartResponse.Data.Content.Length); //fs.BeginWrite( // filePartResponse.Data.Content, // 0, // filePartResponse.Data.Content.Length, // new AsyncCallback((a) => { PartDownloaded(part); }), // null); PartDownloaded(part); } } }
public async Task HandleLines() { try { var strm = NativeClient.GetStream(); using var reader = new StreamReader(strm, Encoding.UTF8); string line; while ((line = await reader.ReadLineAsync()) != null) { LineReceived?.Invoke(this, line); } } catch (IOException ex) { //Logger?.Log?.Error("HandleLines::IOException", ex); Failed?.Invoke(this, new MessageEventArgs(ex.Message)); } catch (InvalidOperationException ex) { Logger?.Log?.Error("HandleLines::InvalidOperationException", ex); Failed?.Invoke(this, new MessageEventArgs(ex.Message)); } Disconnected?.Invoke(this, null !); await Task.Delay(1000); }
public void Clean() { if (baseDirectory == null) { throw new ArgumentException("A directory have to be selected"); } try { Starting?.Invoke(this, EventArgs.Empty); var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() => ParseDirectory(baseDirectory), CancellationToken.None, TaskCreationOptions.None, taskScheduler).ContinueWith((t) => { Completed?.Invoke(this, EventArgs.Empty); }, taskScheduler); } catch (Exception ex) { Failed?.Invoke(this, ex); } }
// ダウンロード完了 private void OnDownloadCompleted(Task <DownloadOperation> prevTask) { if (prevTask.IsFaulted) { Debug.WriteLine("キャッシュ失敗"); Failed?.Invoke(this, EventArgs.Empty); return; } Debug.WriteLine("キャッシュ完了"); if (prevTask.Result != null) { var op = DownloadOperation; if (op.Progress.Status == BackgroundTransferStatus.Completed) { if (op.Progress.TotalBytesToReceive == op.Progress.BytesReceived) { Debug.WriteLine("キャッシュ済み: " + op.ResultFile.Name); Completed?.Invoke(this, EventArgs.Empty); } else { Debug.WriteLine("キャッシュキャンセル: " + op.ResultFile.Name); Canceled?.Invoke(this, EventArgs.Empty); } } else { Debug.WriteLine($"キャッシュ失敗: {op.ResultFile.Name} "); Failed?.Invoke(this, EventArgs.Empty); } } }
private async void OnSave() { var editingAccDocumentItem = Mapper.Map <EditableAccDocumentItem, AccDocumentItem>(AccDocumentItem); try { if (EditMode) { await _accDocumentItemsService.UpdateAccDocumentItemAsync(editingAccDocumentItem); } else { await _accDocumentItemsService.AddAccDocumentItemAsync(editingAccDocumentItem); } Done?.Invoke(); } catch (Exception ex) { Failed?.Invoke(ex); } finally { AccDocumentItem = null; } }
private async void OnSave() { var editingCurrency = Mapper.Map <EditableCurrency, Currency>(Currency); try { if (EditMode) { await _currenciesService.UpdateCurrencyAsync(editingCurrency); } else { await _currenciesService.AddCurrencyAsync(editingCurrency); } Done?.Invoke(); } catch (Exception ex) { Failed.Invoke(ex); } finally { Currency = null; } }
private async void OnSaveAdd() { var editingSL = Mapper.Map <EditableSL, SL>(SL); foreach (var sLStandardDescriptions in SLStandardDescriptionListViewModel.SLStandardDescriptions) { sLStandardDescriptions.SLId = SL.SLId; } editingSL.SLStandardDescriptions = SLStandardDescriptionListViewModel.SLStandardDescriptions; try { if (EditMode) { await _sLsService.UpdateSLAsync(editingSL); } else { await _sLsService.AddSLAsync(editingSL); } Done?.Invoke(); } catch (Exception ex) { Failed?.Invoke(ex); } finally { AddSLRequested(new SL()); } }
/// <inheritdoc /> public void Update(float delta) { if (finished || Objectives.Count == 0) { return; } var win = true; var loose = false; foreach (IObjective objective in Objectives) { // Update objective objective.Update(delta); // Check Objective state win = win && objective.Complete; loose = loose || objective.Fail; } // Game Complete if (!finished && win) { Completed?.Invoke(this, EventArgs.Empty); finished = true; } // Game Over if (!finished && loose) { Failed?.Invoke(this, EventArgs.Empty); finished = true; } }
public static bool InitVirusTotal(string key) { VirusTotal vt = null; FileReport report = null; try { Task.Run(async() => { vt = new VirusTotal(key); report = await vt.GetFileReportAsync("b82758fc5f737a58078d3c60e2798a70d895443a86aa39adf52dec70e98c2bed"); }).Wait(); } catch (Exception ex) { Failed?.Invoke(ex.InnerException?.Message); return(false); } if (report == null || report.MD5 != "0bf60adb1435639a42b490e7e80d25c7") { return(false); } vTotal = vt; Context.VirusTotalEnabled = true; return(true); }
private async void OnSave() { var editingRelatedPerson = Mapper.Map <EditableRelatedPerson, RelatedPerson>(RelatedPerson); try { if (EditMode) { await _relatedPeopleService.UpdateRelatedPersonAsync(editingRelatedPerson); } else { await _relatedPeopleService.AddRelatedPersonAsync(editingRelatedPerson); } Done?.Invoke(); } catch (Exception ex) { Failed?.Invoke(ex); } finally { RelatedPerson = null; } }
private void BackgroundLoop() { try { while (!tracker.IsDisposed) { if (tracker.TryPopResult(out var bodyFrame)) { using (bodyFrame) { BodyFrameReady?.Invoke(this, new BodyFrameReadyEventArgs(bodyFrame)); } } else { Thread.Sleep(1); } } } catch (ObjectDisposedException) { } catch (Exception exc) { Failed?.Invoke(this, new FailedEventArgs(exc)); } }
public void Deploy( IAuthenticated azure, DeploymentOptions options, IEnumerable <AzureResource> resources) { foreach (AzureResource resource in resources) { Task.Factory.StartNew(async() => { try { Started?.Invoke(this, new DeploymentEventArgs(resource)); await CreateResourceAsync(azure, options, resource.Type); Finished?.Invoke(this, new DeploymentEventArgs(resource)); } catch (Exception ex) { Debug.WriteLine($"Error creating resource of type {resource.Type}: {ex}"); Failed?.Invoke(this, new DeploymentErrorEventArgs(resource, ex)); } }); } }
private void Fail() { App.Current.Dispatcher.Invoke(() => { Failed?.Invoke(this, new EventArgs()); }); }
public static void ClamScanAllFiles() { UpdateProgress2?.Invoke("Asking database for files", null, 0, 0); #if DEBUG stopwatch.Restart(); #endif if (!dbCore.DbOps.GetNotAvFiles(out List <DbFile> files)) { Failed?.Invoke("Could not get files from database."); } #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds to get files from database", stopwatch.Elapsed.TotalSeconds); stopwatch.Restart(); #endif int counter = 0; foreach (DbFile file in files) { UpdateProgress2?.Invoke($"Scanning file {counter} of {files.Count}", null, counter, files.Count); ClamScanFileFromRepo(file); counter++; } #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.ClamScanAllFiles(): Took {0} seconds scan all pending files", stopwatch.Elapsed.TotalSeconds); #endif Finished?.Invoke(); }
public async void OnSave() { var editingStock = Mapper.Map <EditableStock, Stock>(Stock); try { if (EditMode) { await _stocksService.UpdateStockAsync(editingStock); } else { await _stocksService.AddStockAsync(editingStock); } Done?.Invoke(); } catch (Exception ex) { Failed?.Invoke(ex); } finally { Stock = null; } }
private async void OnSave() { var editingSLStandardDescription = Mapper.Map <EditableSLStandardDescription, SLStandardDescription>(SLStandardDescription); try { if (EditMode) { await _sLStandardDescriptionsService.UpdateSLStandardDescriptionAsync(editingSLStandardDescription); } else { await _sLStandardDescriptionsService.AddSLStandardDescriptionAsync(editingSLStandardDescription); } Done?.Invoke(); } catch (Exception ex) { Failed?.Invoke(ex); } finally { SLStandardDescription = null; } }
private async void OnSave() { var editingTypeDocument = Mapper.Map <EditableTypeDocument, TypeDocument>(TypeDocument); if (await _typeDocumentsService.HasTitle(editingTypeDocument.TypeDocumentTitle)) { Information?.Invoke("عنوان تکراری می باشد"); } else { try { if (EditMode) { await _typeDocumentsService.UpdateTypeDocumentAsync(editingTypeDocument); } else { await _typeDocumentsService.AddTypeDocumentAsync(editingTypeDocument); } Done?.Invoke(); } catch (Exception ex) { Failed?.Invoke(ex); } finally { TypeDocument = null; } } }
public override void ResponseReceived(byte[] parameter) { switch ((CommandResponse)parameter[0]) { case CommandResponse.Failed: LogService.Error( string.Format((string)Application.Current.Resources["GatheringComputerInformationFailed"], Encoding.UTF8.GetString(parameter, 1, parameter.Length - 1))); Failed?.Invoke(this, EventArgs.Empty); break; case CommandResponse.Successful: var serializer = new Serializer(typeof(Shared.Commands.ComputerInformation.ComputerInformation)); var computerInformation = serializer.Deserialize <Shared.Commands.ComputerInformation.ComputerInformation>(parameter, 1); computerInformation.Timestamp = computerInformation.Timestamp.ToLocalTime(); LogService.Receive( string.Format( (string)Application.Current.Resources["ComputerInformationSuccessfullyReceived"], computerInformation.ProcessTime)); ComputerInformationReceived?.Invoke(this, computerInformation); break; default: throw new ArgumentOutOfRangeException(); } }
public override void OnError(string deviceAddress, int error, int errorType, string message) { base.OnError(deviceAddress, error, errorType, message); Log.Info("DFU", $"Dfu failcode {error}, type {errorType}, msg: {message}"); Failed?.Invoke(this, message); }
public async void Upload(FileMessageRequest file, Guid roomId) { file.Size = File.OpenRead(file.Path).Length; file.PartSize = BufferSize; file.Parts = (int)Math.Ceiling(file.Size / (double)BufferSize); var response = await _httpManager.PostAsync <FileDTO>($"api/Rooms/{roomId.ToString()}/FileMessages", file); if (response.Error != null) { Failed?.Invoke(response.Error.ErrorDescription); return; } var position = 0; var part = 1; while (position < file.Size) { byte[] buffer; if (position + BufferSize > file.Size) { buffer = new byte[(int)file.Size - position]; } else { buffer = new byte[BufferSize]; } using (BinaryReader reader = new BinaryReader(new FileStream(file.Path, FileMode.Open, FileAccess.Read))) { reader.BaseStream.Seek(position, SeekOrigin.Begin); if (position + BufferSize > file.Size) { reader.Read(buffer, 0, (int)file.Size - position); } else { reader.Read(buffer, 0, BufferSize); } } var request = new FilePartDTO { Content = buffer, PartNumber = part }; var resp = await _httpManager.PostAsync <bool>($"api/Files/{response.Data.Id}", request); if (resp.Error != null) { Failed?.Invoke(resp.Error.ErrorDescription); return; } position += BufferSize; } }
public RecordService CreateRecorder(RecordProps props) { if (_recorder != null) { return(this); } var options = new RecorderOptions { RecorderApi = props.WndHandle.HasValue ? RecorderApi.WindowsGraphicsCapture : RecorderApi.DesktopDuplication, IsHardwareEncodingEnabled = _configService.Config.IsHardwareEncodingEnabled, IsLowLatencyEnabled = _configService.Config.IsLowLatencyEnabled, IsMp4FastStartEnabled = _configService.Config.IsMp4FastStartEnabled, DisplayOptions = new DisplayOptions { Top = props.Sides.Top, Bottom = props.Sides.Bottom, Left = props.Sides.Left, Right = props.Sides.Right, WindowHandle = props.WndHandle ?? IntPtr.Zero, MonitorDeviceName = props.MonitorName }, AudioOptions = new AudioOptions { IsAudioEnabled = _configService.Config.EnableSounds || _configService.Config.EnableMicrophone, IsOutputDeviceEnabled = _configService.Config.EnableSounds, IsInputDeviceEnabled = _configService.Config.EnableMicrophone, AudioOutputDevice = props.AudioOutputDevice, AudioInputDevice = props.AudioInputDevice, Bitrate = AudioBitrate.bitrate_128kbps, Channels = AudioChannels.Stereo }, VideoOptions = new VideoOptions { BitrateMode = BitrateControlMode.Quality, Quality = _configService.Config.Quality, Framerate = _configService.Config.Framerate, IsFixedFramerate = false, EncoderProfile = H264Profile.Main }, MouseOptions = new MouseOptions { IsMousePointerEnabled = _configService.Config.IsMousePointerEnabled, IsMouseClicksDetected = _configService.Config.IsMouseClicksDetected, MouseClickDetectionColor = "#FFFF00", MouseRightClickDetectionColor = "#FFFF00", MouseClickDetectionMode = MouseDetectionMode.Hook } }; _recorder = Recorder.CreateRecorder(options); _recorder.OnRecordingComplete += (sender, args) => Completed?.Invoke(args.FilePath); _recorder.OnRecordingFailed += (sender, args) => Failed?.Invoke(args.Error); _recorder.OnStatusChanged += (sender, args) => StatusChanged?.Invoke(args.Status); _recorder.OnSnapshotSaved += (sender, args) => SnapshotSaved?.Invoke(); return(this); }
internal void OnFailed(object sender, ListingProgressArgs args) { ErrorMessages.Add(string.Format("Listing failed: {0}", args.Exception.Message)); if (Failed != null) { Failed.Invoke(sender, args); } }
protected virtual void OnFailed(Exception ex) { if (Failed == null) { return; } Failed.Invoke(this, new UnitOfWorkFailedEventArgs(ex)); }
protected void Fail() { OnFail(); IsFailed = true; Failed?.Invoke(this); AnyEncounterFailed?.Invoke(this); }
/// <summary> /// Triggers the <see cref="Failed"/> event. /// </summary> protected void OnFailed() { Failed?.Invoke(this, new AuthorizationFailedEventArgs() { Error = Error, ErrorDescription = ErrorDescription, ErrorUri = ErrorUri }); }
public async Task Start(string inputMetamodelPath, string outputRoutePath) { Started?.Invoke(this); Progress?.Invoke(this, new RouteAnalyzerState { Message = "Started" }); if (string.IsNullOrEmpty(inputMetamodelPath)) { Ctx?.SendDebugMessage($"Input metamodel file is not set."); return; } if (!File.Exists(inputMetamodelPath)) { Ctx?.SendDebugMessage($"Input metamodel file does not exist: {inputMetamodelPath}"); return; } var fname = System.IO.Path.GetFileName(inputMetamodelPath); await Task.Run(() => { try { var field = LoadPlanFieldFile(inputMetamodelPath); if (field != null) { Ctx?.SendDebugMessage($"Field is loaded, items: {field.Count}"); } var analyzer = new Analyze(field); var analyzerResult = analyzer.Execute((step, maxSteps) => { var m = GetProgressMessage(step, maxSteps, $"Analyzing {fname}"); Progress?.Invoke(this, new RouteAnalyzerState { Message = $"{m}" }); }); Ctx?.SendDebugMessage($"Found {analyzerResult.NumberOfRoutes} routes."); var json = analyzerResult.ToJson(); if (string.IsNullOrEmpty(json)) { Failed?.Invoke(this, $"Result of the analyze call is empty."); } Ctx?.SendDebugMessage($"Apply recent disabling states."); json = ApplyRouteDisableStates(outputRoutePath, json); json.FixBomIfNeeded(); StringUtilities.WriteAllTextNoBom(outputRoutePath, json, out _); Finished?.Invoke(this); } catch (Exception ex) { FailedEx?.Invoke(this, ex); } }); }
public static void GetAllOSes() { try { #if DEBUG stopwatch.Restart(); #endif dbCore.DbOps.GetAllOSes(out List <DbEntry> oses); #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.GetAllOSes(): Took {0} seconds to get OSes from database", stopwatch.Elapsed.TotalSeconds); #endif if (AddOS != null) { #if DEBUG stopwatch.Restart(); #endif int counter = 0; // TODO: Check file name and existence foreach (DbEntry os in oses) { UpdateProgress?.Invoke("Populating OSes table", $"{os.Developer} {os.Product}", counter, oses.Count); string destination = Path.Combine(Settings.Current.RepositoryPath, os.Mdid[0].ToString(), os.Mdid[1].ToString(), os.Mdid[2].ToString(), os.Mdid[3].ToString(), os.Mdid[4].ToString(), os.Mdid) + ".zip"; AddOS?.Invoke(os); counter++; } #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.GetAllOSes(): Took {0} seconds to add OSes to the GUI", stopwatch.Elapsed.TotalSeconds); #endif } Finished?.Invoke(); } catch (ThreadAbortException) { } catch (Exception ex) { if (Debugger.IsAttached) { throw; } Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); #endif } }
protected virtual void OnError(string msg, AppLoadingException e) { Logger.Warn($"can't load application: {msg}"); Logger.Warn($"message: {e.InnerException}"); Logger.Warn($"source: {e.InnerException.Source}"); Logger.Warn($"stack_trace: {e.InnerException.StackTrace}"); Thread.Sleep(200);//至少等待日志被写入到文件中 Failed?.Invoke(this, new AppLoaderFailedEventArgs(e)); }
public static void GetAllApps() { try { #if DEBUG stopwatch.Restart(); #endif dbCore.DbOps.GetAllApps(out List <DbEntry> apps); #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.GetAllApps(): Took {0} seconds to get apps from database", stopwatch.Elapsed.TotalSeconds); #endif if (AddApp != null) { #if DEBUG stopwatch.Restart(); #endif int counter = 0; // TODO: Check file name and existence foreach (DbEntry app in apps) { UpdateProgress?.Invoke("Populating apps table", $"{app.Developer} {app.Product}", counter, apps.Count); AddApp?.Invoke(app); counter++; } #if DEBUG stopwatch.Stop(); Console.WriteLine("Core.GetAllApps(): Took {0} seconds to add apps to the GUI", stopwatch.Elapsed.TotalSeconds); #endif } Finished?.Invoke(); } catch (ThreadAbortException) {} catch (Exception ex) { if (Debugger.IsAttached) { throw; } Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); #endif } }
public static void InitDB() { CloseDB(); dbCore = null; try { if (string.IsNullOrEmpty(Settings.Current.DatabasePath)) { Failed?.Invoke("No database file specified"); return; } dbCore = new SQLite(); if (File.Exists(Settings.Current.DatabasePath)) { if (!dbCore.OpenDb(Settings.Current.DatabasePath, null, null, null)) { Failed?.Invoke("Could not open database, correct file selected?"); dbCore = null; return; } } else { if (!dbCore.CreateDb(Settings.Current.DatabasePath, null, null, null)) { Failed?.Invoke("Could not create database, correct file selected?"); dbCore = null; return; } if (!dbCore.OpenDb(Settings.Current.DatabasePath, null, null, null)) { Failed?.Invoke("Could not open database, correct file selected?"); dbCore = null; return; } } Finished?.Invoke(); } catch (ThreadAbortException) { } catch (Exception ex) { if (Debugger.IsAttached) { throw; } Failed?.Invoke($"Exception {ex.Message}\n{ex.InnerException}"); #if DEBUG Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException); #endif } }