public Task EnableMod(GenericMod mod) { return(_busy.Task(async() => { if (_enabler == null || mod.IsEnabled) { return; } var conflicts = await _enabler.CheckConflictsAsync(mod); if (conflicts.Length > 0 && ModernDialog.ShowMessage( conflicts.Select(x => $@"• “{Path.GetFileName(x.RelativeName)}” has already been altered by the “{x.ModName}” mod;") .JoinToString("\n").ToSentence () + $"\n\nEnabling {BbCodeBlock.Encode(mod.DisplayName)} may have adverse effects. Are you sure you want to enable this mod?", "Conflict", MessageBoxButton.YesNo, "genericMods.conflict") != MessageBoxResult.Yes) { return; } try { using (var waiting = WaitingDialog.Create("Enabling mod…")) { await _enabler.EnableAsync(mod, waiting, waiting.CancellationToken); Changed?.Invoke(this, EventArgs.Empty); if (waiting.CancellationToken.IsCancellationRequested) { waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…")); await _enabler.DisableAsync(mod); } } } catch (Exception e) { NonfatalError.Notify("Can’t enable mod", e); } })); }
public async Task <byte[]> GetModel(string key) { if (key != ExtraModels.KeyCrewExtra) { return(null); } var temporary = FilesStorage.Instance.GetTemporaryFilename("Crew.kn5"); if (!File.Exists(temporary)) { using (var dialog = new WaitingDialog()) { dialog.Report(ControlsStrings.Common_Downloading); var data = await CmApiProvider.GetDataAsync("static/get/cs_crew", dialog, dialog.CancellationToken); if (data == null) { return(null); } await Task.Run(() => { using (var stream = new MemoryStream(data, false)) using (var archive = new ZipArchive(stream)) { archive.GetEntry("Crew.kn5").ExtractToFile(temporary); } }); } } return(await FileUtils.ReadAllBytesAsync(temporary).ConfigureAwait(false)); }
private async Task SelectDifferent(string presetFilename = null) { if (!SettingsHolder.CustomShowroom.CustomShowroomPreviews) { return; } using (var waiting = WaitingDialog.Create("Scanning…")) { var list = Entries.ToList(); var cancellation = waiting.CancellationToken; await Task.Run(() => { var checksum = CmPreviewsTools.GetChecksum(presetFilename); for (var i = 0; i < list.Count; i++) { if (cancellation.IsCancellationRequested) { return; } var entry = list[i]; waiting.Report(new AsyncProgressEntry(entry.Car.DisplayName, i, list.Count)); var selected = entry.Car.EnabledOnlySkins.Where(x => GetChecksum(x.PreviewImage) != checksum).ToList(); ActionExtension.InvokeInMainThread(() => entry.SelectedSkins = selected); } }); } }
public static async Task UpdateAsync(TrackObjectBase track) { if (!File.Exists(track.MapImage)) { ModernDialog.ShowMessage("Map not found"); return; } try { using (WaitingDialog.Create("Saving…")) { var maps = track.MainTrackObject.MultiLayouts?.Select(x => x.MapImage).ToArray() ?? new[] { track.MapImage }; await Task.Run(() => { using (var renderer = new TrackOutlineRenderer(maps, track.MapImage, track.PreviewImage) { LoadPreview = false }) { renderer.Initialize(); renderer.Width = CommonAcConsts.TrackOutlineWidth; renderer.Height = CommonAcConsts.TrackOutlineHeight; TrackOutlineRendererTools.LoadSettings(track, renderer); using (var holder = FileUtils.RecycleOriginal(track.OutlineImage)) { renderer.Shot(holder.Filename); } } }); } } catch (Exception e) { NonfatalError.Notify("Can’t update outline", e); } }
private void ReAttachCommandClicked(object sender, EventArgs e) { var command = sender as OleMenuCommand; if (command == null) { ReAttachUtils.ShowError("ReAttach failed.", "Click was sent from non-ole command."); return; } var index = command.CommandID.ID - ReAttachConstants.ReAttachCommandId; var unAttachedTargets = _history.GetUnAttached(); var target = index < unAttachedTargets.Length ? unAttachedTargets[index] : null; if (target == null) { return; } if (_options.BuildBeforeReAttach) { TryBuildSolution(); } if (!EnsureDebuggerService()) { ReAttachUtils.ShowError("ReAttach failed.", "Unable to obtain ref to debugger service."); return; } var result = _debugger.ReAttach(target); if (result == ReAttachResult.NotStarted) { var dialog = new WaitingDialog(_debugger, target); dialog.ShowModal(); result = dialog.Result; } switch (result) { case ReAttachResult.Success: break; case ReAttachResult.ElevationRequired: ReAttachUtils.ShowElevationDialog(); break; case ReAttachResult.NotStarted: ReAttachUtils.ShowError("ReAttach failed.", "Process not started."); break; case ReAttachResult.Cancelled: break; case ReAttachResult.Failed: ReAttachUtils.ShowError("ReAttach failed.", "Failed reattaching to process."); break; } }
public async Task <byte[]> GetModel(string key) { if (key != ExtraModels.KeyCrewExtra) { return(null); } using (var dialog = new WaitingDialog()) { dialog.Report(ControlsStrings.Common_Downloading); var data = await CmApiProvider.GetStaticDataBytesAsync("cs_crew", TimeSpan.FromDays(3), dialog, dialog.CancellationToken); if (data == null) { return(null); } return(await Task.Run(() => { using (var stream = new MemoryStream(data, false)) using (var archive = new ZipArchive(stream)) { return archive.GetEntry("Crew.kn5")?.Open().ReadAsBytesAndDispose(); } })); } }
private async void ShotAsync(Action <IProgress <Tuple <string, double?> >, CancellationToken> action) { if (_busy) { return; } _busy = true; try { using (var waiting = new WaitingDialog { WindowStartupLocation = WindowStartupLocation.CenterScreen, Owner = null }) { waiting.Report(AsyncProgressEntry.Indetermitate); var cancellation = waiting.CancellationToken; Renderer.IsPaused = true; try { await Task.Run(() => { // ReSharper disable once AccessToDisposedClosure action(waiting, cancellation); }); } finally { Renderer.IsPaused = false; } } } catch (Exception e) { NonfatalError.Notify("Can’t build image", e); } finally { _busy = false; UpdateSize(); } }
public async Task <bool> TryToPack(AcCommonObjectPackerParams packerParams) { try { using (var waiting = packerParams.Progress == null ? WaitingDialog.Create("Packing…") : null) { var progress = waiting ?? packerParams.Progress; var cancellation = waiting?.CancellationToken ?? packerParams.Cancellation; await Task.Run(() => { var destination = packerParams.Destination ?? Path.Combine(Location, $"{Id}-{(this as IAcObjectVersionInformation)?.Version ?? "0"}-{DateTime.Now.ToUnixTimestamp()}.zip"); using (var output = File.Create(destination)) { Pack(output, packerParams, new Progress <string>(x => progress?.Report(AsyncProgressEntry.FromStringIndetermitate($"Packing: {x}…"))), cancellation); } if (cancellation.IsCancellationRequested) { return; } if (packerParams.ShowInExplorer) { WindowsHelper.ViewFile(destination); } }); } return(true); } catch (Exception e) { NonfatalError.Notify("Can’t pack", e); return(false); } }
public void PrepareFullDetail(params IResourceInfo[] torrents) { if (torrents.Any(s => !s.IsHashLoaded)) { using (var dlg = new WaitingDialog()) { var queue = torrents.Where(s => !s.IsHashLoaded).ToArray(); dlg.Task = Task.Factory.StartNew(() => { foreach (var item in queue) { try { item.Provider.LoadFullDetail(item); } catch (Exception) { } } }); dlg.ShowDialog(); } } }
public static async Task Run(TrackObjectBase track) { var modelsFilename = track.ModelsFilename; Logging.Debug(modelsFilename); string kn5Filename = null; if (!File.Exists(modelsFilename)) { modelsFilename = null; kn5Filename = Path.Combine(track.Location, track.Id + ".kn5"); if (!File.Exists(kn5Filename)) { ModernDialog.ShowMessage("Model not found"); return; } } TrackMapPreparationRenderer renderer = null; try { using (WaitingDialog.Create("Loading model…")) { renderer = modelsFilename == null ? new TrackMapPreparationRenderer(await Task.Run(() => Kn5.FromFile(kn5Filename))) : new TrackMapPreparationRenderer(await Task.Run(() => TrackComplexModelDescription.CreateLoaded(modelsFilename))); } var wrapper = new TrackMapRendererWrapper(track, renderer); wrapper.Form.Icon = AppIconService.GetAppIcon(); wrapper.Run(); } finally { renderer?.Dispose(); } }
void IUserPresetable.ImportFromPresetData(string data) { if (_enabler == null || Enabled == null || Disabled == null) { return; } _busy.Task(async() => { await Task.Delay(10); var names = data.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var enabled = Enabled.OfType <GenericMod>().OrderByDescending(x => x.AppliedOrder).ToList(); try { using (var waiting = WaitingDialog.Create("Loading mod profile…")) { for (var i = 0; i < enabled.Count; i++) { var mod = enabled[i]; waiting.Report(mod.DisplayName, i, enabled.Count); if (waiting.CancellationToken.IsCancellationRequested) { return; } await _enabler.DisableAsync(mod, null, waiting.CancellationToken); if (waiting.CancellationToken.IsCancellationRequested) { waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…")); await _enabler.EnableAsync(mod); } } for (var i = 0; i < names.Length; i++) { var mod = _enabler.GetByName(names[i]); if (mod == null) { continue; } waiting.Report(mod.DisplayName, i, enabled.Count); if (waiting.CancellationToken.IsCancellationRequested) { return; } await _enabler.EnableAsync(mod, null, waiting.CancellationToken); if (waiting.CancellationToken.IsCancellationRequested) { waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…")); await _enabler.DisableAsync(mod); } } } } catch (Exception e) { NonfatalError.Notify("Can’t load mod profile", e); } }).Forget(); }
/// <summary> /// 最简单的Http请求(操作类)应答处理函数,需要自己扩展 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="control"></param> /// <param name="response"></param> /// <param name="context"></param> public static void CommOpResponseCommHandler <T>(this Control control, HttpResponse response, object context) where T : BaseOpResult { control.Dispatcher.BeginInvoke(new Action <HttpResponse>((result) => { var strHandleMsg = ""; try { var requestUrl = response.RequestMessage?.RequestUri; if (null == result) { strHandleMsg = string.Format("服务处理{0}失败,应答数据为空!", requestUrl?.AbsolutePath); WaitingDialog.ChangeStateMsg(strHandleMsg); SLogger.Err(result.ToString()); //MessageBox.Show(string.Format("服务处理{0}失败,应答数据为空!", requestUrl?.AbsolutePath)); return; } if (result.StatusCode == HttpStatusCode.OK) { var opResult = JsonHelper.DeserializeTo <T>(result.ResponseContent); if (opResult.ResultCode != QueryResultCode.Succeed) { // 操作失败 //MessageBox.Show(string.Format("服务{0}处理失败,原因:{1}", requestUrl?.AbsolutePath, opResult.RetMsg)); strHandleMsg = string.Format("服务{0}处理失败,原因:{1}", requestUrl?.AbsolutePath, opResult.RetMsg); WaitingDialog.ChangeStateMsg(strHandleMsg); SLogger.Err(result.ToString()); return; } else { // 操作成功 var succeedMsg = opResult.RetMsg; WaitingDialog.ChangeStateMsg(succeedMsg); } } else { strHandleMsg = string.Format("后台请求失败,原因:{0}", result.ResponseContent); WaitingDialog.ChangeStateMsg(strHandleMsg); SLogger.Err(result.ToString()); return; } } catch (Exception ex) { strHandleMsg = string.Format("软件处理出错,msg:{0}", ex.Message); WaitingDialog.ChangeStateMsg(strHandleMsg); SLogger.Err(result.ToString(), ex); return; } }), DispatcherPriority.DataBind, new object[] { response }); }
async void IAcErrorFixer.Run(AcError error) { AcErrorSolutionSelector selector; using (WaitingDialog.Create("Looking for solutions…")) { selector = await AcErrorSolutionSelector.Create(error); } selector.ShowDialog(); }
public static async Task FixLightingAsync(ShowroomObject showroom) { try { using (WaitingDialog.Create("Updating model…")) { await Task.Run(() => FixLighting(showroom)); } } catch (Exception e) { NonfatalError.Notify("Can’t update model", e); } }
public override async Task Drive(Game.BasicProperties basicProperties, Game.AssistsProperties assistsProperties, Game.ConditionProperties conditionProperties, Game.TrackProperties trackProperties) { var selectedCar = CarsManager.Instance.GetById(basicProperties.CarId ?? ""); var selectedTrack = TracksManager.Instance.GetLayoutById(basicProperties.TrackId ?? "", basicProperties.TrackConfigurationId); IEnumerable <Game.AiCar> botCars; try { using (var waiting = new WaitingDialog()) { if (selectedCar == null || !selectedCar.Enabled) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SelectNonDisabled, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } if (selectedTrack == null) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SelectTrack, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } botCars = await RaceGridViewModel.GenerateGameEntries(waiting.CancellationToken); if (waiting.CancellationToken.IsCancellationRequested) { return; } if (botCars == null || !botCars.Any()) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SetOpponent, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } } } catch (Exception e) when(e.IsCanceled()) { return; } catch (Exception e) { NonfatalError.Notify("Can’t create race grid", e); return; } basicProperties.Ballast = RaceGridViewModel.PlayerBallast; basicProperties.Restrictor = RaceGridViewModel.PlayerRestrictor; await StartAsync(new Game.StartProperties { BasicProperties = basicProperties, AssistsProperties = assistsProperties, ConditionProperties = conditionProperties, TrackProperties = trackProperties, ModeProperties = GetModeProperties(botCars) }); }
public void EndWaitingDialog(WaitingDialogResult r) { WaitingDialog.Close(); if (r == WaitingDialogResult.OutOfMemory) { MessageBox.Show("The repository is too large or there is not enough space in device.", "", MessageBoxButton.OK, MessageBoxImage.Error); } else if (r == WaitingDialogResult.TooMuchCommits) { MessageBox.Show("The repository has too much commits.\nLimit is 10 000 commits.", "", MessageBoxButton.OK, MessageBoxImage.Error); } }
private WaitingDialog ProcessTask(Action action, Action completeAction, string title, string message) { ButtonsEnabled = false; var dialog = new WaitingDialog(); dialog.OnClose += (o, result) => { ButtonsEnabled = true; completeAction(); dialog.Dispose(); }; dialog.Show(DialogPlaceHolder, action, title, message); return(dialog); }
private static async Task RunInner(TrackObjectBase track, bool aiLane) { string modelsFilename = null, kn5Filename = null, aiLaneFilename = null; if (!aiLane) { modelsFilename = track.ModelsFilename; if (!File.Exists(modelsFilename)) { modelsFilename = null; kn5Filename = Path.Combine(track.Location, track.Id + ".kn5"); if (!File.Exists(kn5Filename)) { ModernDialog.ShowMessage("Model not found"); return; } } } else { aiLaneFilename = track.AiLaneFastFilename; if (!File.Exists(aiLaneFilename)) { ModernDialog.ShowMessage("AI lane not found"); return; } } await PrepareAsync(); TrackMapPreparationRenderer renderer = null; try { using (WaitingDialog.Create("Loading model…")) { renderer = aiLaneFilename == null ? modelsFilename == null ? new TrackMapPreparationRenderer(await Task.Run(() => Kn5.FromFile(kn5Filename))) : new TrackMapPreparationRenderer(await Task.Run(() => TrackComplexModelDescription.CreateLoaded(modelsFilename))) : new TrackMapPreparationRenderer(await Task.Run(() => AiSpline.FromFile(aiLaneFilename))); } var wrapper = new TrackMapRendererWrapper(track, renderer); wrapper.Form.Icon = AppIconService.GetAppIcon(); wrapper.Run(); } catch (Exception e) { NonfatalError.Notify("Can’t update map", e); } finally { renderer?.Dispose(); } }
private static LapTimesExtraTool CreateSidekickFixTool(Func <string> appDirectoryCallback) { return(new LapTimesExtraTool("Fix lap times", "Older CM versions could break some records, sorry about it. But now, you can use this button to quickly fix them!", new AsyncCommand(async() => { try { var fixedCount = 0; using (var waiting = WaitingDialog.Create("Fixing values")) { var directory = Path.Combine(appDirectoryCallback(), "personal_best"); if (Directory.Exists(directory)) { var files = await Task.Run(() => new DirectoryInfo(directory).GetFiles("*_pb.ini")); for (var i = 0; i < files.Length; i++) { var file = files[i]; if (file.Length != 11) { continue; } var bytes = File.ReadAllBytes(file.FullName); if (bytes.Length != 11 || bytes[0] != 0x80 || bytes[1] != 3 || bytes[2] != (byte)'L') { continue; } waiting.Report(file.Name, i, files.Length); var value = BitConverter.ToInt64(bytes, 3); using (var writer = new BinaryWriter(File.Create(file.FullName))) { writer.Write(new byte[] { 0x80, 3, (byte)'L' }); writer.Write(Encoding.ASCII.GetBytes(value.As <string>())); writer.Write((byte)'\n'); writer.Write((byte)'.'); } fixedCount++; await Task.Yield(); } } } Toast.Show("Records fixed", fixedCount > 0 ? PluralizingConverter.PluralizeExt(fixedCount, "{0} error") + " fixed" : "No errors found"); } catch (Exception e) { NonfatalError.Notify("Can’t fix records", e); } }))); }
public async Task ReplaceSound(CarObject donor) { if (string.Equals(donor.Id, Id, StringComparison.OrdinalIgnoreCase)) { NonfatalError.Notify(ToolsStrings.Car_ReplaceSound_CannotReplace, "Source and destination are the same."); return; } try { using (WaitingDialog.Create("Replacing…")) { await Task.Run(() => ReplaceSound(donor, Location)); } } catch (Exception e) { NonfatalError.Notify(ToolsStrings.Car_ReplaceSound_CannotReplace, ToolsStrings.Car_ReplaceSound_CannotReplace_Commentary, e); } }
public async Task RemoveEntryAsync(LapTimeEntry entry) { if (EnabledSources.Any(x => x.ReadOnly)) { NonfatalError.Notify("Can’t remove entry from read-only sources", $"Please, disable {EnabledSources.Where(x => x.ReadOnly).Select(x => x.DisplayName).JoinToReadableString()}.", solutions: new[] { new NonfatalErrorSolution("Disable read-only sources", null, token => { foreach (var source in EnabledSources) { source.IsEnabled = false; } RaiseEntriesChanged(); return(Task.Delay(0)); }), }); return; } var car = CarsManager.Instance.GetById(entry.CarId)?.DisplayName ?? entry.CarId; var track = TracksManager.Instance.GetLayoutByKunosId(entry.TrackId)?.LayoutName ?? entry.TrackId; if (ModernDialog.ShowMessage($"Are you sure you want to remove {car} on {track} lap time?", "Remove Lap Time", MessageBoxButton.YesNo) != MessageBoxResult.Yes) { return; } try { using (WaitingDialog.Create("Deleting…")) { var changed = false; foreach (var source in EnabledSources) { changed |= await source.RemoveAsync(entry.CarId, entry.TrackId); } if (changed) { Logging.Debug("Removed"); RaiseEntriesChanged(); } } } catch (Exception e) { NonfatalError.Notify("Can’t remove entry", e); } }
protected override async Task ExecuteInner() { try { using (var waiting = new WaitingDialog()) { waiting.Report("Solving the issue…"); await _execute(waiting.CancellationToken); } } catch (TaskCanceledException) { return; } catch (Exception e) { NonfatalError.Notify("Can’t solve the issue", e); return; } if (_entry != null) { NonfatalError.Instance.Errors.Remove(_entry); } }
public static async Task RunAsync([NotNull] PythonAppObject app) { IReadOnlyList <PythonAppWindow> list; using (WaitingDialog.Create("Searching for app windows…")) { list = await app.Windows.GetValueAsync(); } if (list == null || list.Count == 0) { ShowMessage( "No app windows found. You can add lines like “# app window: Window Name” to your code to help CM figure out their names.", "No app windows found", MessageBoxButton.OK); return; } await new AppIconEditor(list).ShowDialogAsync(); }
//************************************************************************ /// <summary> /// ハンドリングしたメソッド実行し、実行時間が長い場合、処理中ダイアログを表示する。 /// 認証エラーが発生した場合、ログインダイアログを表示する。 /// </summary> /// <param name="input">IMethodInvocation</param> /// <param name="getNext">GetNextHandlerDelegate</param> /// <returns>IMethodReturn</returns> //************************************************************************ private IMethodReturn InvokeMethod(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { IMethodReturn returnMessage = null; // フォームを取得 var form = Form.ActiveForm; if (form != null) { // ダイアログを作成 using (var dlg = new WaitingDialog()) { // ハンドリングしたメソッドを非同期実行 IAsyncResult ar = getNext().BeginInvoke(input, getNext, (asyncResult) => { // 結果を取得 returnMessage = getNext().EndInvoke(asyncResult); // UIスレッドで処理を実行 form.Invoke((MethodInvoker)dlg.Close); }, null); // ダイアログ表示待ち if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(Properties.Settings.Default.DialogWaitTime))) { dlg.ShowDialog(); } // 結果がまだ無い場合の対処 while (returnMessage == null) { Thread.Sleep(10); } } } else { returnMessage = getNext()(input, getNext); } return(returnMessage); }
private static async Task <IReadOnlyList <UpdatePreviewError> > Run([NotNull] CarObject car, [CanBeNull] string skinId, [CanBeNull] IReadOnlyList <ToUpdatePreview> toUpdate, [CanBeNull] string presetFilename) { var carKn5 = FileUtils.GetMainCarFilename(car.Location, car.AcdData); if (!File.Exists(carKn5)) { ModernDialog.ShowMessage("Model not found"); return(null); } await PrepareAsync(); Kn5 kn5; using (var waiting = new WaitingDialog()) { waiting.Report("Loading model…"); kn5 = await Task.Run(() => Kn5.FromFile(carKn5)); } using (var renderer = new DarkKn5ObjectRenderer(CarDescription.FromKn5(kn5, car.Location, car.AcdData)) { AutoRotate = false, AutoAdjustTarget = false, AsyncTexturesLoading = true, AsyncOverridesLoading = true, AutoloadCarLights = false, AutoloadShowroomLights = false }) { var wrapper = new CmPreviewsFormWrapper(car, renderer, skinId, presetFilename); if (toUpdate != null) { wrapper.SetToUpdate(toUpdate); } wrapper.Form.Icon = AppIconService.GetAppIcon(); wrapper.Run(); return(wrapper.GetErrors()); } }
private async void pi_del_MouseUp(object sender, MouseButtonEventArgs e) { if (null == this.grid_data.SelectedItem) { return; } var data = this.grid_data.SelectedItem as AirwayEntity; SAssert.MustTrue(null != data, string.Format("绑定数据异常!")); var promptResult = MessageBox.Show(string.Format("确认删除记录?"), "操作确认", MessageBoxButton.OKCancel); if (promptResult == MessageBoxResult.OK) { WaitingDialog.Show(); // 删除记录 await NHttpClientDAL.GetAsync(string.Format("api/DelAirwayInfo/${0}", data.Fid), new HttpResponseHandler(this.CommOpResponseCommHandler <BaseOpResult>)); } }
protected override async Task ExecuteInner() { try { using (var waiting = new WaitingDialog()) { waiting.Report("Solving the issue…"); await _execute(waiting.CancellationToken); } } catch (TaskCanceledException) { return; } catch (Exception e) { NonfatalError.Notify("Can’t solve the issue", e); return; } Solved = true; if (_entry != null) { NonfatalError.Instance.Errors.Remove(_entry); } }
/// <summary> /// Opens a new path /// </summary> /// <param name="dir"></param> public void OpenFiles(string dir) { //initialize a new instance of EntitySelector _entitySelector = new EntitySelector(dir); //create a new instance of WaitingDialog _waitingDialog = new WaitingDialog(); //Test if dir is empty or null and set loading to true if (string.IsNullOrEmpty(dir)) { return; } //Read the files and set them as source of the data grid SetLoading(true); _entitySelector.SelectEntityContents(); _entityContentList = _entitySelector.GetEntityContents(); DgListFileContent.ItemsSource = null; DgListFileContent.ItemsSource = _entityContentList; SetLoading(false); }
public Task DisableMod(GenericMod mod) { return(_busy.Task(async() => { if (_enabler == null || !mod.IsEnabled) { return; } try { using (var waiting = WaitingDialog.Create("Disabling mod…")) { await _enabler.DisableAsync(mod, waiting, waiting.CancellationToken); Changed?.Invoke(this, EventArgs.Empty); if (waiting.CancellationToken.IsCancellationRequested) { waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…")); await _enabler.EnableAsync(mod); } } } catch (Exception e) { NonfatalError.Notify("Can’t disable mod", e); } })); }
public static async Task Run(TrackObjectBase track) { var modelsFilename = track.ModelsFilename; string kn5Filename = null; if (!File.Exists(modelsFilename)) { modelsFilename = null; kn5Filename = Path.Combine(track.Location, track.Id + ".kn5"); if (!File.Exists(kn5Filename)) { ModernDialog.ShowMessage("Model not found"); return; } } Kn5 kn5; using (var waiting = new WaitingDialog()) { waiting.Report("Loading model…"); kn5 = await Task.Run(() => modelsFilename != null ? Kn5.FromModelsIniFile(modelsFilename) : Kn5.FromFile(kn5Filename)); } using (var renderer = new TrackMapPreparationRenderer(kn5)) { var wrapper = new TrackMapRendererWrapper(track, renderer); wrapper.Form.Icon = AppIconService.GetAppIcon(); wrapper.Run(); } }
public override async Task Drive(Game.BasicProperties basicProperties, Game.AssistsProperties assistsProperties, Game.ConditionProperties conditionProperties, Game.TrackProperties trackProperties) { var selectedCar = CarsManager.Instance.GetById(basicProperties.CarId); var selectedTrack = TracksManager.Instance.GetLayoutById(basicProperties.TrackId, basicProperties.TrackConfigurationId); IEnumerable<Game.AiCar> botCars; try { using (var waiting = new WaitingDialog()) { if (selectedCar == null || !selectedCar.Enabled) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SelectNonDisabled, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } if (selectedTrack == null) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SelectTrack, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } botCars = await RaceGridViewModel.GenerateGameEntries(waiting.CancellationToken); if (waiting.CancellationToken.IsCancellationRequested) return; if (botCars == null || !botCars.Any()) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SetOpponent, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } } } catch (TaskCanceledException) { return; } await StartAsync(new Game.StartProperties { BasicProperties = basicProperties, AssistsProperties = assistsProperties, ConditionProperties = conditionProperties, TrackProperties = trackProperties, ModeProperties = GetModeProperties(botCars) }); }
/// <summary> /// Loads the subscriptions details. /// </summary> private void LoadSubscriptionsDetails() { this.Invoke((MethodInvoker)delegate { // File is not more than 10kb. using (WaitingDialog waitingDialog = new WaitingDialog("Please wait while we get subscription details")) { waitingDialog.ShowInTaskbar = false; waitingDialog.StartPosition = FormStartPosition.CenterParent; try { this.Enabled = false; if (cbxSubscriptions.SelectedValue != null) { string selectedItem = cbxSubscriptions.SelectedValue.ToString(); // Some fix to overcome anonymous object string subscriptionID = selectedItem.Split(' ').Count() > 1 ? selectedItem.Split(' ')[3].Trim(' ', ',') : selectedItem; Dictionary<string, string> locations = null; List<string> hostedServices = null; List<string> storageNames = null; do { waitingDialog.ShowDialog(this); locations = CloudDeploymentTasks.ListLocationsForSubscription(subscriptionID, new X509Certificate2(Convert.FromBase64String(this.managementCertificateBase64)), "2011-10-01"); if (locations != null) { this.cbxLocations.DataSource = locations.ToList(); this.cbxLocations.DisplayMember = "value"; this.cbxLocations.ValueMember = "key"; } hostedServices = CloudDeploymentTasks.ListHostedServicesForSubscription(subscriptionID, new X509Certificate2(Convert.FromBase64String(this.managementCertificateBase64)), "2011-10-01"); if (hostedServices != null) { this.cbxHostedNames.DataSource = hostedServices; this.cbxHostedNames.SelectedIndex = -1; } storageNames = CloudDeploymentTasks.ListStorageAccountsForSubscription(subscriptionID, new X509Certificate2(Convert.FromBase64String(this.managementCertificateBase64)), "2011-10-01"); if (storageNames != null) { this.cbxStorageNames.DataSource = storageNames; this.cbxStorageNames.SelectedIndex = -1; } } while (locations == null && hostedServices == null && storageNames == null); } } finally { this.Enabled = true; } } }); }
private void OnActRescanVolumeActivated(object sender, System.EventArgs args) { TreeIter iter; if (!tvVolumes.GetSelectedIter(out iter)) return; Volume oldVolume = tvVolumes.GetVolume(iter); WaitFunc<PlatformIO.DriveInfo> IsVolumeConnected = delegate(out PlatformIO.DriveInfo dinf) { foreach (PlatformIO.DriveInfo di in PlatformIO.DriveInfo.GetDrives()) { if (di.IsReady && di.IsMounted && (di.DriveType.ToVolumeDriveType() == oldVolume.DriveType) && (di.VolumeLabel == oldVolume.Title)) { dinf = di; return true; } } dinf = null; return false; }; bool proceed = true; PlatformIO.DriveInfo drive; if (!IsVolumeConnected(out drive)) { string message = string.Format(S._("Please insert volume '<b>{0}</b>'."), Util.Escape(oldVolume.Title)); var wd = new WaitingDialog<PlatformIO.DriveInfo>(IsVolumeConnected, message); wd.Title = S._("Waiting for volume"); if (wd.Run() == (int)ResponseType.Ok) { proceed = true; drive = wd.Value; } else { proceed = false; } wd.Destroy(); } if (proceed) { VolumeScanner vs = new VolumeScanner(database, drive); vs.VolumeEditor.Load(oldVolume); // remove old volume from the volume treeview and purge all associated data vs.NewVolumeAdded += (object o, NewVolumeAddedEventArgs a) => { PurgeVolume(iter); }; // add new volume to the volume treeview AddNewVolumeAddedEventHandler(vs); } }
public async Task ReplaceSound(CarObject donor) { if (string.Equals(donor.Id, Id, StringComparison.OrdinalIgnoreCase)) { NonfatalError.Notify(ToolsStrings.Car_ReplaceSound_CannotReplace, "Source and destination are the same."); return; } try { using (var waiting = new WaitingDialog()) { waiting.Report(); var guids = donor.GuidsFilename; var soundbank = donor.SoundbankFilename; var newGuilds = GuidsFilename; var newSoundbank = SoundbankFilename; await Task.Run(() => { var destinations = new[] { newGuilds, newSoundbank }.Where(File.Exists).Select(x => new { Original = x, Backup = FileUtils.EnsureUnique($"{x}.bak") }).ToList(); foreach (var oldFile in destinations) { File.Move(oldFile.Original, oldFile.Backup); } try { if (File.Exists(guids) && File.Exists(soundbank)) { File.Copy(soundbank, newSoundbank); File.WriteAllText(newGuilds, File.ReadAllText(guids).Replace(donor.Id, Id)); } else if (File.Exists(soundbank) && donor.Author == AcCommonObject.AuthorKunos) { File.Copy(soundbank, newSoundbank); File.WriteAllText(newGuilds, File.ReadAllLines(FileUtils.GetSfxGuidsFilename(AcRootDirectory.Instance.RequireValue)) .Where(x => !x.Contains(@"} bank:/") || x.Contains(@"} bank:/common") || x.EndsWith(@"} bank:/" + donor.Id)) .Where(x => !x.Contains(@"} event:/") || x.Contains(@"} event:/cars/" + donor.Id + @"/")) .JoinToString(Environment.NewLine).Replace(donor.Id, Id)); } else { throw new InformativeException(ToolsStrings.Car_ReplaceSound_WrongCar, ToolsStrings.Car_ReplaceSound_WrongCar_Commentary); } } catch (Exception) { foreach (var oldFile in destinations) { if (File.Exists(oldFile.Original)) { File.Delete(oldFile.Original); } File.Move(oldFile.Backup, oldFile.Original); } throw; } FileUtils.Recycle(destinations.Select(x => x.Backup).ToArray()); }); } } catch (Exception e) { NonfatalError.Notify(ToolsStrings.Car_ReplaceSound_CannotReplace, ToolsStrings.Car_ReplaceSound_CannotReplace_Commentary, e); } }
public static async Task JoinInvitation([NotNull] string ip, int port, [CanBeNull] string password) { OnlineManager.EnsureInitialized(); var list = OnlineManager.Instance.List; var source = new FakeSource(ip, port); var wrapper = new OnlineSourceWrapper(list, source); ServerEntry server; using (var waiting = new WaitingDialog()) { waiting.Report(ControlsStrings.Common_Loading); await wrapper.EnsureLoadedAsync(); server = list.GetByIdOrDefault(source.Id); if (server == null) { throw new Exception(@"Unexpected"); } } if (password != null) { server.Password = password; } var content = new OnlineServer(server) { Margin = new Thickness(0, 0, 0, -38), ToolBar = { FitWidth = true }, // Values taken from ModernDialog.xaml // TODO: Extract them to some style? Title = { FontSize = 24, FontWeight = FontWeights.Light, Margin = new Thickness(6, 0, 0, 8) } }; content.Title.SetValue(TextOptions.TextFormattingModeProperty, TextFormattingMode.Ideal); var dlg = new ModernDialog { ShowTitle = false, Content = content, MinHeight = 400, MinWidth = 450, MaxHeight = 99999, MaxWidth = 700, Padding = new Thickness(0), ButtonsMargin = new Thickness(8), SizeToContent = SizeToContent.Manual, ResizeMode = ResizeMode.CanResizeWithGrip, LocationAndSizeKey = @".OnlineServerDialog" }; dlg.SetBinding(Window.TitleProperty, new Binding { Path = new PropertyPath(nameof(server.DisplayName)), Source = server }); dlg.ShowDialog(); await wrapper.ReloadAsync(true); }