private void okButton_Click(object sender, EventArgs e) { if (IsValid()) { bool result = false; var settings = _mapper.Map <BotSettingViewModel, BotSettings>(_botSettings); if (radioButtonCreateNew.Checked) { result = _templateService.Insert(settings, txtNewTemplate.Text); } if (radioButtonOverwriteExisting.Checked) { result = _templateService.Update(settings, (Guid)cmbExistingTemplate.SelectedValue); } if (!result) { _mbs.ShowError("An error occured while saving the bot settings"); } else { this.DialogResult = DialogResult.OK; } } }
private void OkToDeleteCustomerMessageSink(Boolean okToDeleteCustomer) { if (okToDeleteCustomer) { try { if (DataAccess.DataService.DeleteCustomer(CurrentCustomer.CustomerId.DataValue)) { //now we need to tell SearchCustomersViewModel to refresh its list of //customers as we deleted the customer that was selected CurrentCustomer = null; matchedCustomersCollectionView.MoveCurrentToPosition(-1); DoSearchCommand.Execute(null); messageBoxService.ShowInformation("Sucessfully deleted the Customer"); } else { messageBoxService.ShowError("There was a problem deleting the Customer"); } } catch { messageBoxService.ShowError("There was a problem deleting the Customer"); } } else { messageBoxService.ShowError("Can't delete Customer as it is currently being edited"); } }
public void CheckAndUpdate() { CheckDbExists(); currentDbVersion = Converter.ToVersion(dbService.SettingsGetValue(SettingsType.DBVersion)); if (appVersion > currentDbVersion) { var confirm = messageBoxService.AskWarningQuestion(Resources.Resources.VersionsMismatchWarningQuestionText, currentDbVersion.ToString(), appVersion.ToString()); if (confirm) { DoMigrations(); } else { messageBoxService.ShowError(Resources.Resources.VersionsMismatchErrorText, appVersion.ToString(), currentDbVersion.ToString()); throw new Exception("DB version and App version is different"); } } else if (appVersion < currentDbVersion) { messageBoxService.ShowError(Resources.Resources.VersionsMismatchDbVersionGreaterErrorText, currentDbVersion.ToString(), appVersion.ToString()); throw new Exception("DB version is greater than App version. This is impossible =)"); } }
/// <summary> /// Executes the AddNewAssemblyCommand /// </summary> private void ExecuteAddNewAssemblyCommand() { //Ask the user where they want to open the file from, and open it try { openFileService.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; openFileService.FileName = String.Empty; openFileService.Filter = "Dll files (*.dll)|*.dll"; bool?result = openFileService.ShowDialog(null); if (result.HasValue && result.Value) { FileInfo file = new FileInfo(openFileService.FileName); if (file.Extension.ToLower().Equals(".dll")) { this.referencedAssemblies.Add(file); } else { messageBoxService.ShowError(String.Format("The file {0} is not a Dll", file.Name)); } } } catch (Exception ex) { messageBoxService.ShowError("An error occurred trying to Open the file\r\n" + ex.Message); } }
/// <summary> /// Saves the List<ImageViewModel> to a XML file using XLINQ /// </summary> private void ExecuteSaveToFileCommand(Object args) { saveFileService.InitialDirectory = @"C:\"; saveFileService.OverwritePrompt = true; saveFileService.Filter = ".xml | XML Files"; var result = saveFileService.ShowDialog(null); if (result.HasValue && result.Value == true) { try { if (imageDiskOperations.Save(saveFileService.FileName, loadedImages.AsEnumerable())) { messageBoxService.ShowInformation(string.Format("Successfully saved images to file\r\n{0}", saveFileService.FileName)); } } catch (Exception ex) { messageBoxService.ShowError( string.Format("An error occurred saving images to file\r\n{0}", ex.Message)); } } }
private async Task <object> ExecutePickInputJarFileCommandAsync(object param) { IsBusy = true; try { _openFileService.Filter = "Jar Files (*.jar)|*.jar"; _openFileService.InitialDirectory = @"c:\"; _openFileService.FileName = ""; var dialogResult = _openFileService.ShowDialog(null); if (dialogResult.Value) { if (!_openFileService.FileName.ToLower().EndsWith(".jar")) { _messageBoxService.ShowError($"{_openFileService.FileName} is not a JAR file"); return(Task.FromResult <object>(null)); } _jarFile = new FileInfo(_openFileService.FileName); JarFilePath = _jarFile.Name; var rawBytesLength = File.ReadAllBytes(_jarFile.FullName).Length; await _dataBricksFileUploadService.UploadFileAsync(_jarFile, rawBytesLength, (newStatus) => this.Status = newStatus); bool uploadedOk = await IsDbfsFileUploadedAndAvailableAsync(_jarFile, rawBytesLength); if (uploadedOk) { //2.0/jobs/runs/submit //poll for success using jobs/runs/get, store that in the JSON var runId = await SubmitJarJobAsync(_jarFile); if (!runId.HasValue) { IsBusy = false; _messageBoxService.ShowError(this.Status = $"Looks like there was a problem with calling Spark API '2.0/jobs/runs/submit'"); } else { await PollForRunIdAsync(runId.Value); } } else { IsBusy = false; _messageBoxService.ShowError("Looks like the Jar file did not upload ok....Boo"); } } } catch (Exception ex) { _messageBoxService.ShowError(ex.Message); } finally { IsBusy = false; } return(Task.FromResult <object>(null)); }
/// <summary> /// Creates a new InMemoryViewModel by reading the persisted XML file from disk /// </summary> private void HydrateViewModelFromXml() { //Ask the user where they want to open the file from, and open it try { openFileService.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; openFileService.FileName = String.Empty; openFileService.Filter = "Xml files (*.xml)|*.xml"; bool?result = openFileService.ShowDialog(null); if (result.HasValue && result.Value) { //open to XML PesistentVM pesistentVM = ViewModelPersistence.HydratePersistedViewModel(openFileService.FileName); //check we got something, and recreate the full weight InMemoryViewModel from //the lighter weight XML read PesistentVM if (pesistentVM != null) { CurrentVM = new InMemoryViewModel(); //Start out with PropertiesViewModel shown PropertiesViewModel propertiesViewModel = new PropertiesViewModel(); propertiesViewModel.IsCloseable = false; CurrentVM.PropertiesVM = propertiesViewModel; //and now read in other data CurrentVM.ViewModelName = pesistentVM.VMName; CurrentVM.CurrentViewModelType = pesistentVM.VMType; CurrentVM.ViewModelNamespace = pesistentVM.VMNamespace; //and add in the individual properties foreach (var prop in pesistentVM.VMProperties) { CurrentVM.PropertiesVM.PropertyVMs.Add(new SinglePropertyViewModel { PropertyType = prop.PropertyType, PropName = prop.PropName, UseDataWrapper = prop.UseDataWrapper }); } HasContent = true; } else { messageBoxService.ShowError(String.Format("Could not open the ViewModel {0}", openFileService.FileName)); } } } catch (Exception ex) { messageBoxService.ShowError("An error occurred trying to Opening the ViewModel\r\n" + ex.Message); } }
private bool IsValid() { var errors = new List <string>(); if (_accounts.Count == 0) { errors.Add("Please specify 3Commas API Credentials and select your 3Commas Exchange Account."); } else if (_settings.ExchangeAccountId == null) { errors.Add("3Commas Exchange Account not selected."); } if (!View.IsBinanceSelected && !View.IsHuobiSelected) { errors.Add("Choose your preferred Exchange."); } if (View.IsBinanceSelected && (String.IsNullOrWhiteSpace(_keys.ApiKeyBinance) || String.IsNullOrWhiteSpace(_keys.SecretBinance))) { errors.Add("API Credentials for Binance missing"); } if (View.IsHuobiSelected && (String.IsNullOrWhiteSpace(_keys.ApiKeyHuobi) || String.IsNullOrWhiteSpace(_keys.SecretHuobi))) { errors.Add("API Credentials for Huobi missing"); } if (string.IsNullOrWhiteSpace(_settings.Botname)) { errors.Add("Bot name missing"); } if (string.IsNullOrWhiteSpace(_settings.QuoteCurrency)) { errors.Add("Quote Currency missing"); } if (View.StartConditionsCount == 0) { errors.Add("Deal Start Condition missing"); } if (_settings.StopLossEnabled) { var maxDeviation = CalculateMaxSoDeviation(); if (_settings.StopLossPercentage <= maxDeviation) { errors.Add($"Stop Loss should be below the last safety order ({maxDeviation})"); } } if (errors.Any()) { _mbs.ShowError(String.Join(Environment.NewLine, errors), "Validation Error"); } return(!errors.Any()); }
private void ExecuteSaveDiagramCommand(object parameter) { if (!DiagramViewModel.Items.Any()) { messageBoxService.ShowError("There must be at least one item in order save a diagram"); return; } IsBusy = true; DiagramItem wholeDiagramToSave = null; Task <int> task = Task.Factory.StartNew <int>(() => { if (SavedDiagramId != null) { int currentSavedDiagramId = (int)SavedDiagramId.Value; wholeDiagramToSave = databaseAccessService.FetchDiagram(currentSavedDiagramId); //If we have a saved diagram, we need to make sure we clear out all the removed items that //the user deleted as part of this work sesssion foreach (var itemToRemove in itemsToRemove) { DeleteFromDatabase(wholeDiagramToSave, itemToRemove); } //start with empty collections of connections and items, which will be populated based on current diagram wholeDiagramToSave.ConnectionIds = new List <int>(); wholeDiagramToSave.DesignerItems = new List <DiagramItemData>(); } else { wholeDiagramToSave = new DiagramItem(); } //ensure that itemsToRemove is cleared ready for any new changes within a session itemsToRemove = new List <SelectableDesignerItemViewModelBase>(); SavePersistDesignerItem(wholeDiagramToSave, DiagramViewModel); wholeDiagramToSave.Id = databaseAccessService.SaveDiagram(wholeDiagramToSave); return(wholeDiagramToSave.Id); }); task.ContinueWith((ant) => { int wholeDiagramToSaveId = ant.Result; if (!savedDiagrams.Contains(wholeDiagramToSaveId)) { List <int> newDiagrams = new List <int>(savedDiagrams); newDiagrams.Add(wholeDiagramToSaveId); SavedDiagrams = newDiagrams; } IsBusy = false; messageBoxService.ShowInformation(string.Format("Finished saving Diagram Id : {0}", wholeDiagramToSaveId)); }, TaskContinuationOptions.OnlyOnRanToCompletion); }
private void OkRemovePropertyTypeMessageSink(Boolean OkToRemoveSelectedProperty) { if (OkToRemoveSelectedProperty) { propertyTypes.Remove(propertyTypesCV.CurrentItem as String); propertyTypesCV.MoveCurrentToPosition(-1); propertyTypesCV.MoveCurrentTo(null); } else { messageBoxService.ShowError( "Can't delete the current Property Type as it currently being used"); } }
public void HandleNavigationCallback(NavigationResult navigationResult) { if (navigationResult.Error != null) { messageBoxService.ShowError(("There was an error trying to display the view you requested")); } else { if (!navigationResult.Result.HasValue || !navigationResult.Result.Value) { messageBoxService.ShowError(("There was an error trying to display the view you requested")); } } }
private void ExecuteSaveFormTemplateCommand(object parameter) { messageBoxService.ShowError("Saving not implemented."); //System.Diagnostics.Debug.WriteLine("Reached ExecuteSaveFormTemplateCommand in MainWindowVM.cs"); //if (!DesignerVM.Items.Any()) //{ // It works! // messageBoxService.ShowError("There must be at least one item in order save a template."); // return; //} // We're about to do some heavy work, so mark that we're busy //IsBusy = true; // Original code used tasks - presuming asynchronous work? //System.Diagnostics.Debug.WriteLine("Saving template ..."); // Implement FormTemplate saving here //DesignerVM.ExportItemsCommand.Execute(null); // All done saving //IsBusy = false; //System.Diagnostics.Debug.WriteLine("Template saved."); // messageBoxService.ShowInformation(string.Format("Template saved")); }
/// <summary> /// Assigns the property value to the property of every source element. /// </summary> /// <param name="value">Property value to be assigned.</param> public override void SetPropertyValue(object value) { Double?valueD = null; // empty string values are treated as null... if (String.IsNullOrEmpty(value as string)) { value = null; } if (String.IsNullOrWhiteSpace(value as string)) { value = null; } try { if (value != null) { valueD = Convert.ToDouble(value); } } catch { IMessageBoxService messageBox = this.GlobalServiceProvider.Resolve <IMessageBoxService>(); messageBox.ShowError("Could not set new value: Conversion failed"); return; } using (Transaction transaction = this.Store.TransactionManager.BeginTransaction("Update property value - " + this.PropertyName)) { PropertyGridEditorViewModel.SetPropertyValues(this.Elements, this.PropertyName, valueD); transaction.Commit(); } }
/// <summary> /// Adds ingredients from recipe to shoppinglist and recipe to foodplan. /// </summary> /// <param name="recipe">Recipe to add</param> /// <param name="date">Date the recipe shall be added to the foodplan</param> public async void Add(Recipe recipe, DateTime date) { if (recipe?.Ingredients?.Count > 0) { if (_foodPlan.RecipeList != null) { foreach (var rec in _foodPlan.RecipeList) { if (rec.Item2.Date == date.Date) { _msgBoxService.ShowError("Opskrift eksisterer allerede på dato"); return; } } } foreach (var ingredient in recipe.Ingredients) { try { _shoppingListModel.AddItem(new Item() { Name = ingredient.Name }); } catch (Exception e) { Log.File.Exception(e); throw; } } } _foodplanCollector.AddRecipeTupleToFoodplan(_loginModel.FoodplanId, new Tuple <Recipe, DateTime>(recipe, date)); await Update(); }
/// <inheritdoc /> protected override async Task InitializeAsync() { XTimingLyricInventoryImporter li = new XTimingLyricInventoryImporter(); var vendorLinks = await GetVendorUrls(); if (!vendorLinks.Any()) { return; } foreach (var vendorLink in vendorLinks) { try { var xml = await _downloadService.GetFileAsStringAsync(new Uri(vendorLink.Url)); var response = await li.Import(xml); SongInventories.Add(response); } catch (Exception e) { Log.Error(e, $"An error occurred retrieving the inventory from: {vendorLink}"); _messageBoxService.ShowError($"Unable to retrieve inventory from {vendorLink.Name}\nEnsure you have an active internet connection.", "Error Retrieving Inventory"); } } SelectedInventory = SongInventories.FirstOrDefault(); // new Uri("https://www.xlightsfaces.com/wp-content/uploads/xlights_music_free.xml")); }
private async Task ExecuteBulkOperation(string inProgressText, List <BotViewModel> bots, Func <BotViewModel, Task> updateOperation) { var cancellationTokenSource = new CancellationTokenSource(); var loadingView = new ProgressView.ProgressView(inProgressText, cancellationTokenSource, bots.Count); loadingView.Show(this); int i = 0; await bots.ParallelForEachAsync( async bot => { await updateOperation(bot); i++; loadingView.SetProgress(i); }, 5, cancellationTokenSource.Token).ConfigureAwait(true); loadingView.Close(); if (cancellationTokenSource.IsCancellationRequested) { _logger.LogInformation("Operation cancelled"); _mbs.ShowError("Operation cancelled!", ""); } else { _mbs.ShowInformation("Operation finished. See output section for details."); } _logger.LogInformation("Refreshing Bots"); await tableControl.RefreshData(_keys); }
public void OnRibbonRegionLoaded(bool e) { if (!viewInjectionService.AddViewToRegion("MainRibbonRegion", "UserRibbonView", new UserRibbonView())) { messageBoxService.ShowError(viewInjectionService.Error); } }
private bool IsValid() { var errors = new List <string>(); if (chkChangeIsEnabled.Checked && cmbIsEnabled.SelectedItem == null) { errors.Add("New value for \"Enabled\" missing."); } if (chkChangeUpperLimit.Checked && numUpperLimit.Value == 0) { errors.Add("New value for \"Upper Limit Price\" missing."); } if (chkChangeLowerLimit.Checked && numLowerLimit.Value == 0) { errors.Add("New value for \"Lower Limit Price\" missing."); } if (chkChangeQuantityPerGrid.Checked && numQuantityPerGrid.Value == 0) { errors.Add("New value for \"Quantity per Grid\" missing."); } if (chkChangeGridQuantity.Checked && numGridQuantity.Value == 0) { errors.Add("New value for \"Grid Quantity\" missing."); } if (errors.Any()) { _mbs.ShowError(String.Join(Environment.NewLine, errors), "Validation Error"); } return(!errors.Any()); }
public async void OnEdit() { var ids = View.SelectedBotIds; if (!ids.Any()) { _mbs.ShowInformation("No Bots selected"); return; } var botsToEdit = _bots.Where(x => ids.Contains(x.Id)).ToList(); if (botsToEdit.Any(x => x.Type != "Bot::SingleBot")) { _mbs.ShowError("Sorry, Bulk Edit only works for Simple Bots, not advanced."); return; } var dlg = new EditDialog.EditDialog(botsToEdit.Count); EditDto editData = new EditDto(); dlg.EditDto = editData; var dr = dlg.ShowDialog(View); if (dr == DialogResult.OK) { var loadingView = new ProgressView(botsToEdit, editData, _keys, _logger); loadingView.ShowDialog(View); _logger.LogInformation("Refreshing Bots"); await RefreshBots(); } }
private bool IsValid() { var errors = new List <string>(); if (chkChangeIsEnabled.Checked && cmbIsEnabled.SelectedItem == null) { errors.Add("New value for \"Enabled\" missing."); } if (chkChangeName.Checked && string.IsNullOrWhiteSpace(txtName.Text)) { errors.Add("New value for \"Name\" missing."); } if (chkChangeTakeProfitType.Checked && cmbTakeProfitType.SelectedItem == null) { errors.Add("New value for \"Take Profit Type\" missing."); } if (chkChangeStartOrderType.Checked && cmbStartOrderType.SelectedItem == null) { errors.Add("New value for \"Start Order Type\" missing."); } if (chkChangeBaseOrderSizeType.Checked && cmbBaseOrderVolumeType.SelectedItem == null) { errors.Add("New value for \"Base Order Type\" missing."); } if (chkChangeSafetyOrderSizeType.Checked && cmbSafetyOrderVolumeType.SelectedItem == null) { errors.Add("New value for \"Safety Order Type\" missing."); } if (chkChangeBaseOrderSize.Checked && numBaseOrderVolume.Value == 0) { errors.Add("New value for \"Base order size\" missing."); } if (chkChangeSafetyOrderSize.Checked && numSafetyOrderVolume.Value == 0) { errors.Add("New value for \"Safety order size\" missing."); } if (chkChangeTrailingEnabled.Checked && cmbTtpEnabled.SelectedItem == null) { errors.Add("New value for \"TTP Enabled\" missing."); } if (chkDisableAfterDealsCount.Checked && cmbDisableAfterDealsCount.SelectedItem == null) { errors.Add("New value for \"Open deals & stop\" missing."); } if (chkChangeDealStartCondition.Checked && !_startConditions.Any()) { errors.Add("New value for \"Deal Start Condition\" missing."); } if (chkChangeLeverageType.Checked && cmbLeverageType.SelectedItem == null) { errors.Add("New value for \"Leverage Type\" missing."); } if (errors.Any()) { _mbs.ShowError(String.Join(Environment.NewLine, errors), "Validation Error"); } return(!errors.Any()); }
private void DefinePropertyNameMessageSink(SinglePropertyViewModel currentPropVM) { if (currentPropVM.PropName == String.Empty) { return; } Int32 existingProperties = PropertyVMs.Count(x => x.PropName == currentPropVM.PropName); if (existingProperties > 1 && PropertyVMs.Count > 1) { PropertyVMs.Remove(currentPropVM); messageBoxService.ShowError("That Property Name is in use elsewhere, please retry"); } }
/// <summary> /// Occurs when an un handled Exception occurs for the Dispatcher /// </summary> private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { Exception ex = e.Exception; messageBoxService.ShowError("Application error : " + ex.Message); e.Handled = true; }
/// <summary> /// Shows a Save/Generate messagebox /// </summary> /// <param name="success">true if operation was successful</param> /// <param name="filename">the filename</param> /// <param name="operation">the operation type</param> private void ShowSaveOrGenMessage(Boolean success, String filename, SaveOrGenerate operation) { if (!success) { messageBoxService.ShowError( String.Format("There was a problem {0} the\r\nViewModel file : {1}", operation == SaveOrGenerate.Save ? "Saving" : "Generating", filename)); } else { messageBoxService.ShowInformation( String.Format("Successfully {0} the\r\nViewModel file : {1}", operation == SaveOrGenerate.Save ? "Saved" : "Generated", filename)); } }
public bool Insert(BotSettings settings, string name) { try { settings.Id = Guid.NewGuid(); settings.Name = name; settings.UpdatedAt = DateTime.Now; _settings.Add(settings); Save(); return(true); } catch (Exception e) { _mbs.ShowError(e.ToString()); return(false); } }
private void RegistrationForm_Register(object sender, EventArgs e) { try { model.AddUser(registrationForm.FirstName, registrationForm.SecondName, registrationForm.Email, registrationForm.Password); messageService.ShowMessage("Регистрация прошла успешно!"); } catch (EmptyParameterException ex) { registrationForm.IsSuccessful = false; messageService.ShowError(ex.Message); } catch (AlreadyExistsUserClientException ex) { registrationForm.IsSuccessful = false; messageService.ShowError(ex.Message); } }
public static void ShowError(this IMessageBoxService service, string message, string title = "Error") { if (service == null) { throw new ArgumentNullException(nameof(service)); } service.ShowError(null, message, title); }
public override bool TryValidate(IMessageBoxService messageBoxService) { if (string.IsNullOrEmpty(Value)) { messageBoxService.ShowError("'Logger to Match' must be specified."); return(false); } return(base.TryValidate(messageBoxService)); }
public override bool TryValidate(IMessageBoxService messageBoxService) { if (string.IsNullOrEmpty(Value)) { messageBoxService.ShowError("A name must be assigned to this appender."); return(false); } foreach (XmlNode appender in mConfiguration.Log4NetNode.SelectNodes("appender")) { if (!Equals(appender, mConfiguration.OriginalNode) && appender.Attributes[Log4NetXmlConstants.Name]?.Value == Value) { messageBoxService.ShowError("Name must be unique."); return(false); } } return(base.TryValidate(messageBoxService)); }
public override bool TryValidate(IMessageBoxService messageBoxService) { if (!int.TryParse(Value, out int _)) { messageBoxService.ShowError("Max size roll backups must be a valid integer."); return(false); } return(base.TryValidate(messageBoxService)); }
public override bool TryValidate(IMessageBoxService messageBoxService) { if (string.IsNullOrEmpty(Value)) { messageBoxService.ShowError("An application name must be assigned to this appender."); return(false); } return(base.TryValidate(messageBoxService)); }
public AddEditOrderViewModel() { this.DisplayName = "Customer Orders"; #region Obtain Services try { messageBoxService = Resolve<IMessageBoxService>(); } catch { Logger.Error("Error resolving services"); throw new ApplicationException("Error resolving services"); } #endregion //Save Order to customer Command saveOrderCommand = new SimpleCommand { CanExecuteDelegate = x => CanExecuteSaveOrderCommand, ExecuteDelegate = x => ExecuteSaveOrderCommand() }; //Edit Order editOrderCommand = new SimpleCommand { CanExecuteDelegate = x => CanExecuteEditOrderCommand, ExecuteDelegate = x => ExecuteEditOrderCommand() }; //Cancel Edit cancelOrderCommand = new SimpleCommand { CanExecuteDelegate = x => CanExecuteCancelOrderCommand, ExecuteDelegate = x => ExecuteCancelOrderCommand() }; try { //fetch all Products Products = DataAccess.DataService.FetchAllProducts().ConvertAll( new Converter<Product, ProductModel>(ProductModel.ProductToProductModel)); productsCV = CollectionViewSource.GetDefaultView(Products); productsCV.CurrentChanged += ProductsCV_CurrentChanged; productsCV.MoveCurrentToPosition(-1); } catch { messageBoxService.ShowError("There was a problem fetching the products"); } }