コード例 #1
0
        public MainViewModel()
        {
            Application.Current.MainWindow.Closing += MainWindow_Closing;
            Application.Current.MainWindow.Closed += MainWindow_Closed;

            try
            {
                _ctx = new UnitOfWork(new IsisContext());
                Workspaces = new ObservableCollection<WorkspaceViewModel>
                {
                    new BerekenModuleViewModel(_ctx),
                    new PrestatieBeheerViewModel(_ctx),
                    new KlantenBeheerViewModel(_ctx),
                    new PersoneelBeheerViewModel(_ctx),
                    new ParameterBeheerViewModel(_ctx)
                };
                SelectedWorkspace = Workspaces.First();
            }
            catch (Exception ex)
            {
                MessageBoxService messageService = new MessageBoxService();
                messageService.ShowMessageBox("ERROR");      //Hack: The first Messagebox closes automatically
                //TODO: Add possiblity to restore database from backup!
                messageService.ShowErrorBox("Er heeft zich een probleem voorgedaan bij het ophalen van de data \n\nError: " + ex.Message);
                logger.Error("Loading Database (startup)", ex);
                Application.Current.Shutdown(-1);
            }
        }
コード例 #2
0
        public virtual bool Leave(bool changes = false, bool errors = false)
        {
            if(Ctx.HasChanges() || changes)
            {
                MessageBoxService messageService = new MessageBoxService();

                var result = messageService.AskForConfirmation("Er zijn nog onopgeslagen wijzigingen.\nWilt u deze wijzingen nog opslaan?", Header);
                if (result == MessageBoxResult.Yes)
                {
                    //Check if there are validation errors!!!
                    try
                    {
                        if (errors)
                            throw new Exception("There is a specific validation error");
                        Ctx.Complete();
                    }
                    catch
                    {
                        messageService.ShowMessageBox("Er bevinden zich nog fouten in de data! Kan dit niet opslaan!");
                        return false;
                    }
                }
                else if (result == MessageBoxResult.No)
                {
                    Ctx.DiscardChanges();
                }
                else
                {
                    return false;
                }
            }

            return true;
        }
コード例 #3
0
		GeneralAppSettingsPageProvider(IThemeServiceImpl themeService, IWindowsExplorerIntegrationService windowsExplorerIntegrationService, IDocumentTabServiceSettings documentTabServiceSettings, DocumentTreeViewSettingsImpl documentTreeViewSettings, IDsDocumentServiceSettings documentServiceSettings, AppSettingsImpl appSettings, MessageBoxService messageBoxService) {
			this.themeService = themeService;
			this.windowsExplorerIntegrationService = windowsExplorerIntegrationService;
			this.documentTabServiceSettings = documentTabServiceSettings;
			this.documentTreeViewSettings = documentTreeViewSettings;
			this.documentServiceSettings = documentServiceSettings;
			this.appSettings = appSettings;
			this.messageBoxService = messageBoxService;
		}
        /// <summary>
        /// Export Grid
        /// </summary>
        /// <param name="fileType"></param>
        public void ExportGrid(ExportType fileType)
        {
            try
            {
                switch (fileType)
                {
                case ExportType.XLSX:
                    SaveFileDialogService.DefaultExt = "xlsx";
                    SaveFileDialogService.Filter     = "Excel 2007+|*.xlsx";
                    break;

                case ExportType.PDF:
                    SaveFileDialogService.DefaultExt = "pdf";
                    SaveFileDialogService.Filter     = "PDF|*.pdf";
                    break;
                }

                if (SaveFileDialogService.ShowDialog())
                {
                    var fileName = SaveFileDialogService.GetFullFileName();
                    ExportGridService.ExportTo(fileType, fileName);
                    if (MessageBoxService.ShowMessage("¿Desea abrir el archivo?", "Operación Exitosa", MessageButton.YesNo) == MessageResult.Yes)
                    {
                        var process = new Process();
                        process.StartInfo.UseShellExecute = true;
                        process.StartInfo.FileName        = fileName;
                        process.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBoxService.ShowMessage(GetStringValue(Next.Enums.Enums.MessageError.ExportError) + ex.Message, ex.Message,
                                              MessageButton.OK, MessageIcon.Error);
            }
        }
コード例 #5
0
        private async void SubstituteDeleteButton_Click(object sender, EventArgs e)
        {
            if (!_substituteDataGridViewService.TryGetSelectedCellIndices(out _, out var rowIndex, true) ||
                !_substituteDataGridViewService.TryParseIntCell(SubstituteColumnName.MedicamentId,
                                                                rowIndex,
                                                                out var substituteMedicamentId))
            {
                return;
            }

            var substituteMedicamentName = _substituteDataGridViewService.GetCellValue(
                SubstituteColumnName.MedicamentName,
                rowIndex);

            if (!MessageBoxService.ShowDeleteQuestion(
                    $"Are you sure you want to delete Medicament '{substituteMedicamentName}'?"))
            {
                return;
            }

            await _substitutesService.DeleteByIdAsync(_medicament.Id, substituteMedicamentId);

            await RefreshSubstituteDataGridViewAsync();
        }
コード例 #6
0
        void AttachedFilesCore(string[] names)
        {
            bool     fileLengthExceed = false;
            FileInfo info;

            foreach (string name in names)
            {
                info = new FileInfo(name);
                if (info.Length > FilesHelper.MaxAttachedFileSize * 1050578)
                {
                    fileLengthExceed = true;
                }
                else
                {
                    FilesInfo.Add(FilesHelper.GetAttachedFileInfo(info.Name, info.DirectoryName));
                }
            }
            if (fileLengthExceed)
            {
                MessageBoxService.ShowMessage(string.Format("The size of one of the files exceeds {0} MB.", FilesHelper.MaxAttachedFileSize), "Error attaching files");
            }
            SetCollectionChange();
            Update();
        }
コード例 #7
0
ファイル: ElementTreeViewModel.cs プロジェクト: Aurbo99/vixen
        /// <summary>
        /// Method to invoke when the PasteAsNew command is executed.
        /// </summary>
        private void PasteAsNew()
        {
            System.Windows.Forms.IDataObject dataObject = System.Windows.Forms.Clipboard.GetDataObject();

            if (dataObject != null && SelectedItems.Count == 1)
            {
                if (dataObject.GetDataPresent(ClipboardFormatName.Name))
                {
                    var parent            = SelectedItem;
                    MessageBoxService mbs = new MessageBoxService();
                    var result            = mbs.GetUserInput("Please enter the new name.", "Paste As New", PropModelServices.Instance().Uniquify(parent.Name));
                    if (result.Result == MessageResult.OK)
                    {
                        DeselectAll();
                        var newElementModels = new List <ElementModelViewModel>();
                        var data             = dataObject.GetData(ClipboardFormatName.Name) as List <ElementModel>;

                        if (data != null)
                        {
                            foreach (var elementModel in data)
                            {
                                var em  = PropModelServices.Instance().CreateElementModelTree(elementModel, parent.ElementModel, result.Response);
                                var evm = ElementModelLookUpService.Instance.GetModels(em.Id);
                                if (evm != null)
                                {
                                    newElementModels.AddRange(evm);
                                }
                            }
                        }

                        OnModelsChanged();
                        SelectModels(newElementModels);
                    }
                }
            }
        }
コード例 #8
0
        private void ExecuteAddNewAssetCM(object parameter)
        {
            IMessageBoxService msg = new MessageBoxService();

            if (parameter.GetType().Equals(typeof(TVAssetViewModel)))
            {
                TVAssetViewModel asset  = parameter as TVAssetViewModel;
                AssetModel       result = msg.OpenAssetDlg(asset.Asset.CustomerID, asset.Asset.ID);
                if (result != null)
                {
                    AddAssetNode(result);
                }
            }
            else
            if (parameter.GetType().Equals(typeof(TVCustomerViewModel)))
            {
                TVCustomerViewModel customer = parameter as TVCustomerViewModel;
                AssetModel          result   = msg.OpenAssetDlg(customer.Customer.ID, 0);
                if (result != null)
                {
                    AddAssetNode(result);
                }
            }
        }
 void ShowMessage(string message)
 {
     MessageBoxService.Show(message);
 }
コード例 #10
0
 void OnShowNotificationCommand(string message)
 {
     MessageBoxService.ShowMessage(message);
 }
 void ShowProductEditForm()
 {
     MessageBoxService.Show(@"You can easily create custom edit forms using the 40+ controls that ship as part of the DevExpress Data Editors Library. To see what you can build, activate the Employees module.",
                            "Edit Products", MessageButton.OK, MessageIcon.Asterisk, MessageResult.OK);
 }
コード例 #12
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            //reset working directory
            Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            //set culture
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            var autoMapper  = new SimpleAutoMapper();
            var dataIO      = new DataIO();
            var messageBox  = new MessageBoxService();
            var mouseHook   = new MouseHook();
            var timerTool   = new TimerTool();
            var autoUpdater = new AutoUpdater(messageBox);
            var clipboard   = new ViewModelClipboard();
            var recent      = new RecentFileManager();
            var mtpManager  = new MTPManager();

            var DependencyDict = new Dictionary <Type, object>()
            {
                { typeof(SimpleAutoMapper), autoMapper },
                { typeof(MessageBoxService), messageBox },
                { typeof(ViewModelClipboard), clipboard },
            };

            var viewModelFactory = new ViewModelFactory(DependencyDict);

            (new ScriptGenerateBootstrap()).SetUp(out IActionToScriptFactory actionToScriptFactory, out IEmulatorToScriptFactory emulatorToScriptFactory);

            var settingVM           = new SettingViewModel(Settings.Default(), autoMapper, mtpManager);
            var macroManagerVM      = new MacroManagerViewModel(dataIO, messageBox, viewModelFactory, recent);
            var scriptApplyFactory  = new ScriptApplyBootStrap(messageBox, mtpManager).GetScriptApplyFactory();
            var scriptGenerator     = new ScriptGenerator(scriptApplyFactory, settingVM, messageBox, emulatorToScriptFactory, actionToScriptFactory);
            var scriptGeneratorVM   = new ScriptGeneratorViewModel(macroManagerVM, scriptGenerator, messageBox);
            var customActionManager = new CustomActionManager(macroManagerVM, viewModelFactory, dataIO, messageBox);

            var timerToolVM      = new TimerToolViewModel(mouseHook, timerTool);
            var resulutionTool   = new ResolutionConverterTool(viewModelFactory);
            var resolutionToolVM = new ResolutionConverterToolViewModel(resulutionTool, macroManagerVM, messageBox);
            var autoLocationVM   = new AutoLocationViewModel(new MouseHook(), new AutoLocation(), macroManagerVM);

            var mainWindowViewModel = new MainWindowViewModel(macroManagerVM, settingVM, autoUpdater, timerToolVM, resolutionToolVM, scriptGeneratorVM, customActionManager, autoLocationVM);

            MainWindow = new MainWindow
            {
                DataContext = mainWindowViewModel
            };

            //Handle arguments
            var agrs = Environment.GetCommandLineArgs();

            if (agrs.Length > 1)
            {
                var filepath = agrs.Where(s => s.Contains(".emm")).First();

                macroManagerVM.SetCurrentMacro(filepath, agrs.Any(s => s.Equals(StaticVariables.NO_SAVE_AGRS)));
            }

            // Select the text in a TextBox when it receives focus.
            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent,
                                              new MouseButtonEventHandler(SelectivelyIgnoreMouseButton));
            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotKeyboardFocusEvent,
                                              new RoutedEventHandler(SelectAllText));
            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.MouseDoubleClickEvent,
                                              new RoutedEventHandler(SelectAllText));

            MainWindow.Show();
        }
コード例 #13
0
        public void Delete()
        {
            try
            {
                Ctx.KlantTypes.Remove(SelectedType);
                Ctx.Complete();
            }
            catch (Exception ex)
            {
                Ctx.DiscardChanges();
                MessageBoxService messageService = new MessageBoxService();
                messageService.ShowErrorBox("Er heeft zich een probleem voorgedaan bij het verwijderen van een bestaande 'Klant Type' (" + SelectedType.Type + " " + SelectedType.Naam + ")\n\nError: " + ex.Message);
            }

            GetData();
        }
コード例 #14
0
 private void ShowInfo()
 {
     this.ShowBusy("The info dialog is showing...");
     MessageBoxService.Info(this, "this is info dialog for fun.", "Info AAA");
 }
コード例 #15
0
        public void Save()
        {
            if (ButtonToevoegenContent == "Annuleren")
            {
                Ctx.Strijkers.Add(SelectedPersoneel);
            }

            try
            {
                Ctx.Complete();
            }
            catch (Exception ex)
            {
                MessageBoxService messageService = new MessageBoxService();
                messageService.ShowErrorBox("Er heeft zich een probleem voorgedaan bij het opslaan van de strijksters \n\nError: " + ex.Message);
            }

            ButtonToevoegenContent = "Toevoegen";
        }
コード例 #16
0
        public void RestoreDatabase()
        {
            OpenFileDialogService openFileDialogService = new OpenFileDialogService();
            string path = openFileDialogService.Open();
            if (!String.IsNullOrWhiteSpace(path))
            {
                try
                {
                    Ctx.RestoreDatabase(path);
                    var message = new MessageBoxService();
                    var result = message.AskForConfirmation("Restore van backup van databank is geslaagd. Om effect te hebben moet u de applicatie herstarten! \nWilt u de applicatie nu herstarten?","Strijkdienst Conny Restore Database", System.Windows.MessageBoxButton.YesNo);
                    if (result == MessageBoxResult.Yes)
                    {
                        System.Windows.Forms.Application.Restart();
                        Process.GetCurrentProcess().Kill();
                    }

                }
                catch
                {
                    //TODO
                }
            }
        }
コード例 #17
0
        public void Add()
        {
            var duplicate = ViewSource.View.Cast<Datum>().FirstOrDefault(d => d.Date.Date == AddDatum.Date.Date);
            if (duplicate == null)
            {
                //Add new date to a new prestatie
                if (_id == 0)
                    NewDates.Add(AddDatum);
                //Add new date to an existing prestatie
                else
                {
                    AddDatum.PrestatieId = _id;
                    _ctx.Datums.Add(AddDatum);
                }

                AddDatum = new Datum { Date = DateTime.Now };
            }
            else
            {
                MessageBoxService messageBoxService = new MessageBoxService();
                messageBoxService.ShowMessageBox("Deze datum is al toegevoegd!");
            }
        }
 public void HelpCommandExecuteFunc()
 {
     MessageBoxService.ShowMessage("Help Command executed");
 }
コード例 #19
0
        protected override void OnSaveToolBarItem()
        {
            ReadData(_activePart);
            if (_activePart.Id > 0)
            {
                var activeUserId = ApplicationSessionService.GetActiveUserId();
                var creationDate = ApplicationSessionService.GetNowDateTime();

                using (var dbContext = new FarnahadManufacturingDbContext())
                {
                    var partInDb = dbContext.Parts
                                   .Include(item => item.PartReorderInformations)
                                   .First(item => item.Id == _activePart.Id);
                    var newCost = _activePart.PartCosts.FirstOrDefault(item => item.CreatedByUserId == 0);
                    if (newCost != null)
                    {
                        newCost.CreatedByUserId = activeUserId;
                        newCost.CreatedDateTime = creationDate;
                        newCost.PartId          = partInDb.Id;
                        partInDb.PartCosts.Add(newCost);
                    }

                    foreach (var defaultLocation in _activePart.PartDefaultLocations)
                    {
                        if (defaultLocation.PartId == 0)
                        {
                            defaultLocation.PartId = _activePart.Id;
                            partInDb.PartDefaultLocations.Add(defaultLocation);
                        }
                        else
                        {
                            var defaultLocationInDb = dbContext.PartDefaultLocations
                                                      .First(item => item.Id == defaultLocation.Id);
                            defaultLocationInDb.LocationGroupId   = defaultLocation.LocationGroupId;
                            defaultLocationInDb.DefaultLocationId = defaultLocation.DefaultLocationId;
                            defaultLocationInDb.Part = partInDb;
                        }
                    }

                    foreach (var trackingPart in _activePart.TrackingParts)
                    {
                        if (trackingPart.PartId == 0)
                        {
                            trackingPart.PartId          = _activePart.Id;
                            trackingPart.CreatedByUserId = activeUserId;
                            trackingPart.CreatedDateTime = creationDate;
                            partInDb.TrackingParts.Add(trackingPart);
                        }
                        else
                        {
                            var trackingPartInDb = dbContext.TrackingParts
                                                   .First(item => item.Id == trackingPart.Id);
                            trackingPartInDb.Description = trackingPart.Description;
                            trackingPartInDb.IsPrimary   = trackingPart.IsPrimary;
                            trackingPartInDb.IsSelected  = trackingPart.IsSelected;
                            trackingPartInDb.NextValue   = trackingPart.NextValue;
                            trackingPartInDb.TrackingId  = trackingPart.TrackingId;
                            trackingPartInDb.Part        = partInDb;
                        }
                    }

                    foreach (var partReorderInformation in _activePart.PartReorderInformations)
                    {
                        if (partReorderInformation.PartId == 0)
                        {
                            partReorderInformation.PartId          = _activePart.Id;
                            partReorderInformation.CreatedByUserId = activeUserId;
                            partReorderInformation.CreatedDateTime = creationDate;
                            partInDb.PartReorderInformations.Add(partReorderInformation);
                        }
                        else
                        {
                            var partReorderInformationInDb = dbContext.PartReorderInformations
                                                             .First(item => item.Id == partReorderInformation.Id);
                            partReorderInformationInDb.LocationGroupId = partReorderInformation.LocationGroupId;
                            partReorderInformationInDb.OrderUpToLevel  = partReorderInformation.OrderUpToLevel;
                            partReorderInformationInDb.ReorderPoint    = partReorderInformation.ReorderPoint;
                            partReorderInformationInDb.Part            = partInDb;
                        }
                    }

                    foreach (var partReorderInformation in partInDb.PartReorderInformations.ToList())
                    {
                        if (_activePart.PartReorderInformations.All(item => item.Id != partReorderInformation.Id))
                        {
                            dbContext.Entry(partReorderInformation).State = EntityState.Deleted;
                        }
                    }

                    //_activePart.Products;

                    partInDb.Title             = _activePart.Title;
                    partInDb.Number            = _activePart.Number;
                    partInDb.UomId             = _activePart.UomId;
                    partInDb.PartType          = _activePart.PartType;
                    partInDb.Description       = _activePart.Description;
                    partInDb.Details           = _activePart.Details;
                    partInDb.IsActive          = _activePart.IsActive;
                    partInDb.PickInPartUomOnly = _activePart.PickInPartUomOnly;
                    partInDb.Picture           = _activePart.Picture;

                    partInDb.RevisionNumber = _activePart.RevisionNumber;
                    partInDb.Upc            = _activePart.Upc;
                    partInDb.AlertNote      = _activePart.AlertNote;
                    partInDb.Length         = _activePart.Length;
                    partInDb.Width          = _activePart.Width;
                    partInDb.Height         = _activePart.Height;
                    partInDb.DistanceUomId  = _activePart.DistanceUomId;
                    partInDb.Weight         = _activePart.Weight;
                    partInDb.WeightUomId    = _activePart.WeightUomId;

                    partInDb.PartAbcCode = _activePart.PartAbcCode;

                    partInDb.LastChangedByUserId = activeUserId;
                    partInDb.LastChangedDateTime = creationDate;

                    dbContext.SaveChanges();

                    IsEditing();
                }
            }
            else
            {
                using (var dbContext = new FarnahadManufacturingDbContext())
                {
                    var activeUserId = ApplicationSessionService.GetActiveUserId();
                    var creationDate = ApplicationSessionService.GetNowDateTime();
                    _activePart.CreatedByUserId     = activeUserId;
                    _activePart.LastChangedByUserId = activeUserId;
                    _activePart.CreatedDateTime     = creationDate;
                    _activePart.LastChangedDateTime = creationDate;
                    foreach (var trackingPart in _activePart.TrackingParts)
                    {
                        dbContext.Trackings.Attach(trackingPart.Tracking);
                        trackingPart.CreatedByUserId = activeUserId;
                        trackingPart.CreatedDateTime = creationDate;
                    }

                    foreach (var partCost in _activePart.PartCosts)
                    {
                        partCost.CreatedByUserId = activeUserId;
                        partCost.CreatedDateTime = creationDate;
                    }

                    foreach (var reorderInformation in _activePart.PartReorderInformations)
                    {
                        reorderInformation.CreatedByUserId = activeUserId;
                        reorderInformation.CreatedDateTime = creationDate;
                    }

                    dbContext.Parts.Add(_activePart);
                    dbContext.SaveChanges();

                    OnAddToolBarItem();
                }
            }

            MessageBoxService.SaveConfirmation(_activePart.Title);
            LoadSearchGridControl();
        }
コード例 #20
0
		public GeneralAppSettingsPage(IThemeServiceImpl themeService, IWindowsExplorerIntegrationService windowsExplorerIntegrationService, IDocumentTabServiceSettings documentTabServiceSettings, DocumentTreeViewSettingsImpl documentTreeViewSettings, IDsDocumentServiceSettings documentServiceSettings, AppSettingsImpl appSettings, MessageBoxService messageBoxService) {
			if (themeService == null)
				throw new ArgumentNullException(nameof(themeService));
			if (windowsExplorerIntegrationService == null)
				throw new ArgumentNullException(nameof(windowsExplorerIntegrationService));
			if (documentTabServiceSettings == null)
				throw new ArgumentNullException(nameof(documentTabServiceSettings));
			if (documentTreeViewSettings == null)
				throw new ArgumentNullException(nameof(documentTreeViewSettings));
			if (documentServiceSettings == null)
				throw new ArgumentNullException(nameof(documentServiceSettings));
			if (appSettings == null)
				throw new ArgumentNullException(nameof(appSettings));
			if (messageBoxService == null)
				throw new ArgumentNullException(nameof(messageBoxService));
			this.themeService = themeService;
			this.windowsExplorerIntegrationService = windowsExplorerIntegrationService;
			this.documentTabServiceSettings = documentTabServiceSettings;
			this.documentTreeViewSettings = documentTreeViewSettings;
			this.documentServiceSettings = documentServiceSettings;
			this.messageBoxService = messageBoxService;

			ThemesVM = new ObservableCollection<ThemeVM>(themeService.VisibleThemes.Select(a => new ThemeVM(a)));
			if (!ThemesVM.Any(a => a.Theme == themeService.Theme))
				ThemesVM.Add(new ThemeVM(themeService.Theme));
			SelectedThemeVM = ThemesVM.FirstOrDefault(a => a.Theme == themeService.Theme);
			Debug.Assert(SelectedThemeVM != null);

			WindowsExplorerIntegration = windowsExplorerIntegrationService.WindowsExplorerIntegration;
			DecompileFullType = documentTabServiceSettings.DecompileFullType;
			RestoreTabs = documentTabServiceSettings.RestoreTabs;
			DeserializeResources = documentTreeViewSettings.DeserializeResources;
			UseMemoryMappedIO = documentServiceSettings.UseMemoryMappedIO;
			UseNewRendererVM = new UseNewRendererVM(appSettings);
		}
コード例 #21
0
        internal void ExecutePackageDownload(string name, PackageVersion package, string downloadPath)
        {
            string msg = String.IsNullOrEmpty(downloadPath) ?
                         String.Format(Resources.MessageConfirmToInstallPackage, name, package.version) :
                         String.Format(Resources.MessageConfirmToInstallPackageToFolder, name, package.version, downloadPath);

            var result = MessageBoxService.Show(msg,
                                                Resources.PackageDownloadConfirmMessageBoxTitle,
                                                MessageBoxButton.OKCancel, MessageBoxImage.Question);

            var pmExt = DynamoViewModel.Model.GetPackageManagerExtension();

            if (result == MessageBoxResult.OK)
            {
                // get all of the dependency version headers
                var dependencyVersionHeaders = package.full_dependency_ids.Select((dep, i) =>
                {
                    try
                    {
                        var depVersion = package.full_dependency_versions[i];
                        return(Model.GetPackageVersionHeader(dep._id, depVersion));
                    }
                    catch
                    {
                        MessageBoxService.Show(
                            String.Format(Resources.MessageFailedToDownloadPackageVersion, dep._id),
                            Resources.PackageDownloadErrorMessageBoxTitle,
                            MessageBoxButton.OK, MessageBoxImage.Error);
                        return(null);
                    }
                }).ToList();

                // if any header download fails, abort
                if (dependencyVersionHeaders.Any(x => x == null))
                {
                    return;
                }

                var localPkgs = pmExt.PackageLoader.LocalPackages;

                var uninstallsRequiringRestart          = new List <Package>();
                var uninstallRequiringUserModifications = new List <Package>();
                var immediateUninstalls = new List <Package>();
                var stdLibPackages      = new List <Package>();

                // if a package is already installed we need to uninstall it, allowing
                // the user to cancel if they do not want to uninstall the package
                var duplicateLocalPackages = dependencyVersionHeaders.Select(dep => localPkgs.FirstOrDefault(v => v.Name == dep.name));
                foreach (var localPkg in duplicateLocalPackages)
                {
                    if (localPkg == null)
                    {
                        continue;
                    }

                    if (localPkg.RootDirectory.Contains(pmExt.PackageLoader.StandardLibraryDirectory))
                    {
                        stdLibPackages.Add(localPkg);
                        continue;
                    }

                    if (localPkg.LoadedAssemblies.Any())
                    {
                        uninstallsRequiringRestart.Add(localPkg);
                        continue;
                    }

                    if (localPkg.InUse(DynamoViewModel.Model))
                    {
                        uninstallRequiringUserModifications.Add(localPkg);
                        continue;
                    }

                    immediateUninstalls.Add(localPkg);
                }

                if (stdLibPackages.Any())
                {// Conflicts with standard library packages
                    string message = "";
                    if (duplicateLocalPackages.Count() == 1 &&
                        duplicateLocalPackages.First().Name == name)
                    {
                        message = duplicateLocalPackages.First().VersionName == package.version ?
                                  String.Format(Resources.MessageSamePackageInStdLib,
                                                DynamoViewModel.BrandingResourceProvider.ProductName,
                                                JoinPackageNames(stdLibPackages))
                                    :
                                  String.Format(Resources.MessageSamePackageDiffVersInStdLib,
                                                DynamoViewModel.BrandingResourceProvider.ProductName,
                                                JoinPackageNames(stdLibPackages));
                    }
                    else
                    {
                        message = String.Format(Resources.MessagePackageDepsInStdLib,
                                                DynamoViewModel.BrandingResourceProvider.ProductName,
                                                name + " " + package.version,
                                                JoinPackageNames(stdLibPackages));
                    }

                    MessageBoxService.Show(message,
                                           Resources.CannotDownloadPackageMessageBoxTitle,
                                           MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // determine if any of the packages contain binaries or python scripts.
                var containsBinariesOrPythonScripts = dependencyVersionHeaders.Any(x =>
                {
                    // The contents (string) property of the PackageVersion object can be null for an empty package
                    // like LunchBox.
                    var are_contents_empty = string.IsNullOrEmpty(x.contents);
                    var contains_binaries  = x.contains_binaries ||
                                             !are_contents_empty && x.contents.Contains(PackageManagerClient.PackageContainsBinariesConstant);
                    var contains_python =
                        !are_contents_empty && x.contents.Contains(PackageManagerClient.PackageContainsPythonScriptsConstant);
                    return(contains_binaries || contains_python);
                });

                // if any do, notify user and allow cancellation
                if (containsBinariesOrPythonScripts)
                {
                    var res = MessageBoxService.Show(Resources.MessagePackageContainPythonScript,
                                                     Resources.PackageDownloadMessageBoxTitle,
                                                     MessageBoxButton.OKCancel, MessageBoxImage.Exclamation);

                    if (res == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }

                // Determine if there are any dependencies that are made with a newer version
                // of Dynamo (this includes the root package)
                var dynamoVersion = VersionUtilities.PartialParse(DynamoViewModel.Model.Version);
                var futureDeps    = dependencyVersionHeaders.Where(dep => VersionUtilities.PartialParse(dep.engine_version) > dynamoVersion);

                // If any of the required packages use a newer version of Dynamo, show a dialog to the user
                // allowing them to cancel the package download
                if (futureDeps.Any())
                {
                    if (MessageBoxService.Show(string.Format(Resources.MessagePackageNewerDynamo, DynamoViewModel.BrandingResourceProvider.ProductName),
                                               string.Format(Resources.PackageUseNewerDynamoMessageBoxTitle, DynamoViewModel.BrandingResourceProvider.ProductName),
                                               MessageBoxButton.OKCancel,
                                               MessageBoxImage.Warning) == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }

                if (uninstallRequiringUserModifications.Any())
                {
                    MessageBoxService.Show(String.Format(Resources.MessageUninstallToContinue,
                                                         DynamoViewModel.BrandingResourceProvider.ProductName,
                                                         JoinPackageNames(uninstallRequiringUserModifications)),
                                           Resources.CannotDownloadPackageMessageBoxTitle,
                                           MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var settings = DynamoViewModel.Model.PreferenceSettings;

                if (uninstallsRequiringRestart.Any())
                {
                    var message = string.Format(Resources.MessageUninstallToContinue2,
                                                DynamoViewModel.BrandingResourceProvider.ProductName,
                                                JoinPackageNames(uninstallsRequiringRestart),
                                                name + " " + package.version);
                    // different message for the case that the user is
                    // trying to install the same package/version they already have installed.
                    if (uninstallsRequiringRestart.Count == 1 &&
                        uninstallsRequiringRestart.First().Name == name &&
                        uninstallsRequiringRestart.First().VersionName == package.version)
                    {
                        message = String.Format(Resources.MessageUninstallSamePackage, name + " " + package.version);
                    }
                    var dialogResult = MessageBoxService.Show(message,
                                                              Resources.CannotDownloadPackageMessageBoxTitle,
                                                              MessageBoxButton.YesNo, MessageBoxImage.Error);

                    if (dialogResult == MessageBoxResult.Yes)
                    {
                        // mark for uninstallation
                        uninstallsRequiringRestart.ForEach(x => x.MarkForUninstall(settings));
                    }
                    return;
                }

                if (immediateUninstalls.Any())
                {
                    // if the package is not in use, tell the user we will be uninstall it and give them the opportunity to cancel
                    if (MessageBoxService.Show(String.Format(Resources.MessageAlreadyInstallDynamo,
                                                             DynamoViewModel.BrandingResourceProvider.ProductName,
                                                             JoinPackageNames(immediateUninstalls)),
                                               Resources.DownloadWarningMessageBoxTitle,
                                               MessageBoxButton.OKCancel, MessageBoxImage.Warning) == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }

                // add custom path to custom package folder list
                if (!String.IsNullOrEmpty(downloadPath))
                {
                    if (!settings.CustomPackageFolders.Contains(downloadPath))
                    {
                        settings.CustomPackageFolders.Add(downloadPath);
                    }
                }

                // form header version pairs and download and install all packages
                dependencyVersionHeaders
                .Select((dep, i) => {
                    return(new PackageDownloadHandle()
                    {
                        Id = dep.id,
                        VersionName = dep.version,
                        Name = dep.name
                    });
                })
                .ToList()
                .ForEach(x => DownloadAndInstall(x, downloadPath));
            }
        }
コード例 #22
0
        private void Delete()
        {
            string LastMessage;

            try
            {
                if (Kontrah != null)
                {
                    List <IHP_KONTRAHENT_ARCH> IHP_KONTRAHS_ARCH = context.IHP_KONTRAHENT_ARCH.Where(x => x.ID_IHP_KONTRAHENT.Equals(_kontrah.ID_IHP_KONTRAHENT)).ToList();


                    if (context.IHP_NAGLDOK.Any(o => o.ID_IHP_KONTRAHENT == Kontrah.ID_IHP_KONTRAHENT))

                    {
                        MessageBoxService.Show("Kontrahent wykorzystany w dokumencie!");
                        return;
                    }
                    //if (context.IHP_WAZENIE.Any(o => o.ID_IHP_KONTRAHENT == Kontrah.ID_IHP_KONTRAHENT))

                    //{

                    //    MessageBoxService.Show("Kontrahent wykorzystany w ważeniu!");
                    //    return;
                    //}
                    context.IHP_KONTRAHENT_ARCH.RemoveRange(IHP_KONTRAHS_ARCH);
                    context.IHP_KONTRAHENT.Remove(_kontrah);
                    context.SaveChanges();
                    Clear();
                    LoadCollection();
                    SentKontraharch();
                }
            }
            catch (DbUpdateException Ex)
            {
                LogManager.WriteLogMessage(LogManager.LogType.Error, String.Format("DbUpdateException \"{0}\"  :", Ex.InnerException.Message));
                throw Ex;
            }
            catch (SqlException exc)
            {
                //here you might still get some exceptions but not about validation.

                LogManager.WriteLogMessage(LogManager.LogType.Error, String.Format("SqlException \"{0}\"  :", exc.Message));


                //sometimes you may want to throw the exception to upper layers for handle it better over there!
                throw;
            }

            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    LogManager.WriteLogMessage(LogManager.LogType.Error, String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        LogManager.WriteLogMessage(LogManager.LogType.Error, String.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                throw;
            }
            catch (Exception ex)
            {
                LastMessage = ex.ToString();
                if (LastMessage == String.Empty)
                {
                    LastMessage = ex.InnerException.ToString();
                }
                LogManager.WriteLogMessage(LogManager.LogType.Error, LastMessage);
                throw ex;
            }
        }
コード例 #23
0
 public IMessageBoxService GetMessageBoxService()
 {
     return(MessageBoxService.GetInstance());
 }
コード例 #24
0
ファイル: App.xaml.cs プロジェクト: yaneshtyagi/2day
        private async Task BootstrapFrame(LaunchActivatedEventArgs launchActivatedEventArgs, IActivatedEventArgs activatedEventArgs, string addTaskTitle = null)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                try
                {
                    ApplicationView appView = ApplicationView.GetForCurrentView();
                    this.mainview = appView;
                    SetupTitleBar(appView);
                    SetupStatusBar(appColor);

                    appView.SetPreferredMinSize(new Size(Constants.AppMinWidth, Constants.AppMinHeight));

                    this.bootstraper = new Bootstraper(ApplicationVersion.GetAppVersion());

                    InitializeViewLocator();

                    await this.bootstraper.ConfigureAsync(rootFrame);

                    this.navigationService = Ioc.Resolve <INavigationService>();
                    this.platformService   = Ioc.Resolve <IPlatformService>();

                    this.suspensionManager = new SuspensionManager(Ioc.Resolve <IPersistenceLayer>(), Ioc.Resolve <ISynchronizationManager>(), Ioc.Resolve <ITileManager>());

                    rootFrame.Navigated        += this.OnNavigated;
                    rootFrame.NavigationFailed += this.OnNavigationFailed;

                    // Place the frame in the current Window
                    Window.Current.Content = rootFrame;

                    if (rootFrame.Content == null)
                    {
                        Type   startupPage         = typeof(MainPage);
                        object navigationParameter = launchActivatedEventArgs?.Arguments;

                        var startupManager = Ioc.Resolve <IStartupManager>();
                        if (startupManager.IsFirstLaunch)
                        {
                            startupPage = typeof(WelcomePage);
                        }
                        else if (!String.IsNullOrWhiteSpace(addTaskTitle))
                        {
                            startupPage         = typeof(WelcomePage);
                            navigationParameter = new TaskCreationParameters {
                                Title = addTaskTitle
                            };
                        }

                        SystemNavigationManager.GetForCurrentView().BackRequested += this.OnBackRequested;
                        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
                        Window.Current.VisibilityChanged += this.OnVisibilityChanged;

                        // When the navigation stack isn't restored navigate to the first page,
                        // configuring the new page by passing required information as a navigation parameter
                        rootFrame.Navigate(startupPage, navigationParameter);
                    }

                    if (launchActivatedEventArgs != null)
                    {
                        LauncherHelper.TryHandleArgs(launchActivatedEventArgs.Arguments);
                    }
                    else if (activatedEventArgs != null)
                    {
                        LauncherHelper.TryHandleArgs(activatedEventArgs);
                    }

                    // Ensure the current window is active
                    Window.Current.Activate();
                }
                catch (Exception ex)
                {
                    var messageBoxService = new MessageBoxService(new NavigationService(rootFrame));
                    await messageBoxService.ShowAsync("Error", "2Day was unable to start please send a screenshot of this page to the development team. Details: " + ex);

                    DeviceFamily deviceFamily = DeviceFamily.Unkown;
                    if (this.platformService != null)
                    {
                        deviceFamily = this.platformService.DeviceFamily;
                    }

                    var trackingManager = new TrackingManager(true, deviceFamily);
                    trackingManager.Exception(ex, "Bootstrap", true);
                }
            }
            else
            {
                if (launchActivatedEventArgs != null)
                {
                    LauncherHelper.TryHandleArgs(launchActivatedEventArgs.Arguments);
                }
                else if (activatedEventArgs != null)
                {
                    LauncherHelper.TryHandleArgs(activatedEventArgs);
                }
            }
        }
コード例 #25
0
        private async void EditButton_Click(object sender, EventArgs e)
        {
            if (!_dataGridViewService.TryGetSelectedCellIndices(out var columnIndex, out var rowIndex, true))
            {
                return;
            }

            if (columnIndex == -1)
            {
                MessageBoxService.ShowIncorrectSelectionWarning("Select cell you want to edit.");
                return;
            }

            var columnName = _dataGridViewService.GetColumnName(columnIndex);

            if (columnName == ColumnName.Id)
            {
                MessageBoxService.ShowIncorrectSelectionWarning("You can't edit id.");
                return;
            }

            if (!_dataGridViewService.TryParseIntCell(ColumnName.Id, rowIndex, out var medicamentId))
            {
                return;
            }
            var medicament = await _medicamentsService.ReadByIdAsync(medicamentId);

            switch (columnName)
            {
            case ColumnName.Name:
            {
                var oldValue = _dataGridViewService.GetCellValue(columnIndex, rowIndex);
                var editForm = new EditStringDialogForm(oldValue);
                editForm.ShowDialog(this);

                var editResult = editForm.DialogResult;
                var newValue   = editForm.NewValue;
                editForm.Close();

                if (editResult == DialogResult.Cancel)
                {
                    return;
                }

                medicament.Name = newValue;
                break;
            }

            case ColumnName.StockQuantity:
            {
                if (!_dataGridViewService.TryParseDoubleCell(columnName, rowIndex, out var oldValue))
                {
                    return;
                }
                var editForm = new EditDoubleDialogForm(oldValue);
                editForm.ShowDialog(this);

                var editResult = editForm.DialogResult;
                var newValue   = editForm.NewValue;
                editForm.Close();

                if (editResult == DialogResult.Cancel)
                {
                    return;
                }

                medicament.StockQuantity = newValue;
                break;
            }

            default:
                MessageBox.Show(@"Check database and debug code.",
                                @"Unknown field.",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            await _medicamentsService.UpdateAsync(medicament);

            await RefreshDataViewGridAsync();
        }
コード例 #26
0
        private void SelectedTypePropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            var changed = sender as KlantType;

            try
            {
                Ctx.Complete();
            }
            catch (Exception ex)
            {
                MessageBoxService messageService = new MessageBoxService();
                messageService.ShowErrorBox("Er heeft zich een probleem voorgedaan bij het opslaan van een bestaande 'Klant Type' ("+ changed.Type + " " + changed.Naam + ")\n\nError: " + ex.Message);
            }
        }
コード例 #27
0
 public void Scan()
 {
     MessageBoxService.Show("This button simulates scan, in real case it will be qr code scanner.",
                            "Information", MessageBoxButton.OK, MessageBoxImage.Information);
     SearchId = "12345";
 }
コード例 #28
0
        public void Update(CellValueChangedEventArgs e)
        {
            if (null == SelectedBook)
            {
                return;
            }

            if (e.Column.FieldName == "Name" || e.Column.FieldName == "ISBN")
            {
                if (_repo.Query(o => o.Name == SelectedBook.Name && o.ISBN == SelectedBook.ISBN).Count > 1)
                {
                    if (MessageBoxService.Show(
                            string.Format("存在重复的书名[{0}]+ISBN号[{1}],确定仍然要录入吗?", SelectedBook.Name, SelectedBook.ISBN),
                            "提示",
                            MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        if (e.Column.FieldName == "Name")
                        {
                            SelectedBook.Name = e.OldValue.ToString();
                        }
                        else
                        {
                            SelectedBook.ISBN = e.OldValue.ToString();
                        }
                        return;
                    }
                }
            }

            if (ConfigUtil.ConfirmUpdate && MessageBoxService.Show(
                    string.Format("确定要把[{0}]从[{1}]改成[{2}]吗?", e.Column.Header, e.OldValue, e.Value),
                    "提示",
                    MessageBoxButton.YesNo) == MessageBoxResult.No)
            {
                return;
            }

            if (e.Column.FieldName == "TotalCount")
            {
                int old      = (int)e.OldValue;
                int newValue = (int)e.Value;
                int change   = newValue - old;

                if ((SelectedBook.AvailableCount + change) < 0)
                {
                    MessageBoxService.Show("入库数量不应小于已借出的数量!", "提示", MessageBoxButton.OK);
                    return;
                }

                SelectedBook.AvailableCount += change;
            }

            if (e.Column.FieldName == "Name" && !string.IsNullOrWhiteSpace(SelectedBook.Name))
            {
                SelectedBook.Pinyin = PinyinHelper.GetFirstPYLetter(SelectedBook.Name);
            }

            if (e.Column.FieldName == "ISBN" && !string.IsNullOrWhiteSpace(SelectedBook.ISBN))
            {
                Messenger.Default.Send <IsbnMsg>(new IsbnMsg(SelectedBook), IsbnAction.Request);
            }

            Save(SelectedBook);
            Logger.DebugFormat("修改Book,Id={0}, ISBN={1}, Name={2}, {3}={4}->{5}",
                               SelectedBook.Id, SelectedBook.ISBN, SelectedBook.Name, e.Column.FieldName, e.OldValue, e.Value);
        }
コード例 #29
0
 public MessageBoxServiceImpl(MessageBoxService parent)
 {
     _parent = parent;
 }
コード例 #30
0
 public void ShowScheduler(string title)
 {
     MessageBoxService.Show(@"This demo does not include integration with our WPF Scheduler Suite but you can easily introduce Outlook-inspired scheduling and task management capabilities to your apps with DevExpress Tools.",
                            title, MessageButton.OK, MessageIcon.Asterisk, MessageResult.OK);
 }
 public override void Delete(Product entity)
 {
     MessageBoxService.ShowMessage("To ensure data integrity, the Products module doesn't allow records to be deleted. Record deletion is supported by the Employees module.", "Delete Product", MessageButton.OK);
 }
コード例 #32
0
        public void Bereken()
        {
            if (SelectedKlant == null)
            {
                MessageBoxService messageBoxService = new MessageBoxService();
                messageBoxService.ShowMessageBox("Je hebt nog geen klant gekozen!");
                return;
            }

            CurrentView.Bereken();
        }
コード例 #33
0
ファイル: RecipesForm.cs プロジェクト: Igasus/PrihodkoCourse
        private async void EditButton_Click(object sender, EventArgs e)
        {
            if (!_recipesDataGridViewService.TryGetSelectedCellIndices(out var columnIndex, out var rowIndex, true))
            {
                return;
            }

            if (columnIndex == -1)
            {
                MessageBoxService.ShowIncorrectSelectionWarning("Select cell you want to edit.");
                return;
            }

            var columnName = _recipesDataGridViewService.GetColumnName(columnIndex);

            if (columnName == ColumnName.Id ||
                columnName == ColumnName.ClientId ||
                columnName == ColumnName.ClientName ||
                columnName == ColumnName.DiseaseId ||
                columnName == ColumnName.DiseaseName)
            {
                MessageBoxService.ShowIncorrectSelectionWarning("You can't edit id.");
                return;
            }

            if (!_recipesDataGridViewService.TryParseIntCell(ColumnName.Id, rowIndex, out var recipeId))
            {
                return;
            }
            var recipe = await _recipesService.ReadByIdAsync(recipeId);

            switch (columnName)
            {
            case ColumnName.Date:
            {
                var oldValue = recipe.Date;
                var editForm = new EditDateDialogForm(oldValue);
                editForm.ShowDialog(this);

                var editResult = editForm.DialogResult;
                var newValue   = editForm.NewValue;
                editForm.Close();

                if (editResult == DialogResult.Cancel)
                {
                    return;
                }

                recipe.Date = newValue;
                break;
            }

            default:
                MessageBox.Show(@"Check database and debug code.",
                                @"Unknown field.",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            await _recipesService.UpdateAsync(recipe);

            await RefreshRecipesDataGridViewAsync();
        }
コード例 #34
0
        public void Edit()
        {
            if (SelectedKlant == null)
            {
                MessageBoxService messageBoxService = new MessageBoxService();
                messageBoxService.ShowMessageBox("Je hebt nog geen klant gekozen!");
                return;
            }

            if (ButtonToevoegenContent == "Toevoegen")
            {
                //TODO: Denk hier nog eens over na...
                try
                {
                    CurrentView.EditLast(DatumViewModel);
                    ButtonBerekenContent = "Herberekenen";
                    ButtonToevoegenContent = "Aanpassen";
                    ButtonChangeContent = "Annuleren";
                }
                catch (Exception e)
                {
                    MessageBoxService messageService = new MessageBoxService();
                    messageService.ShowMessageBox(e.Message);
                }

            }
            else
            {
                ButtonBerekenContent = "Berekenen";
                ButtonToevoegenContent = "Toevoegen";
                ButtonChangeContent = "Laatste prestatie aanpassen";
                CurrentView.Cancel();
                DatumViewModel.Init();
            }
        }
コード例 #35
0
 private void ShowError(Exception ex)
 {
     MessageBoxService.ShowMessage(messageBoxText: ex.Message, caption: "Error", button: MessageButton.OK, icon: MessageIcon.Error);
     _logger.Error(ex.Message, ex);
 }
コード例 #36
0
 public void Print()
 {
     MessageBoxService messageService = new MessageBoxService();
     if (Ctx.TijdPrestaties.Any())
     {
         //Get all previous TijdPrestaties of the selected klant
         var tempPrestatie = Ctx.TijdPrestaties.GetLatestPrestatie(SelectedKlant);
         if (tempPrestatie == null)
         {
             messageService.ShowMessageBox("Deze klant heeft geen vorige prestaties, u kunt niets printen");
         }
         else
         {
             PrintWindow print = new PrintWindow();
             print.ShowPrintPreview(tempPrestatie);
         }
     }
     else
     {
         messageService.ShowMessageBox("Er bevinden zich nog geen prestaties in de databank, u kunt niets printen");
     }
 }
 public void OpenCommandExecuteFunc()
 {
     MessageBoxService.ShowMessage("Open Command executed");
 }
コード例 #38
0
        public void Save()
        {
            if (!DatumViewModel.HasDates)
            {
                MessageBoxService messageService = new MessageBoxService();
                messageService.ShowMessageBox("Je hebt nog geen datum gekozen!");
                return;
            }

            try
            {
                //Add prestatie + dates to DB
                if (ButtonToevoegenContent == "Toevoegen")
                {
                    //Add date(s) to DB
                    Ctx.Datums.AddRange(DatumViewModel.NewDates);
                    //Add prestatie to DB (parameter needs to be last date)
                    CurrentView.Save(DatumViewModel.NewDates.Last().Date);

                    #region Legacy code

                    ////Add Dates to DB
                    //foreach (var d in DatumViewModel.NewDates)
                    //{
                    //    d.Id = CurrentView.AddPrestatie.Id;
                    //    context.Datum.Add(d);

                    //    //EF is retarded and thinks that I readded the Strijkers to the db, while I didn't.
                    //    //I Just use them as foreign relantionschip, I can't just use the id, because I need the name
                    //    //Manually said this is not true
                    //    //https://msdn.microsoft.com/en-us/magazine/dn166926.aspx
                    //    //This link explains it!

                    //    if (d.Strijker1 != null)
                    //        context.Entry(d.Strijker1).State = EntityState.Unchanged;
                    //    if (d.Strijker2 != null)
                    //        context.Entry(d.Strijker2).State = EntityState.Unchanged;
                    //    if (d.Strijker3 != null)
                    //        context.Entry(d.Strijker3).State = EntityState.Unchanged;
                    //    if (d.Strijker4 != null)
                    //        context.Entry(d.Strijker4).State = EntityState.Unchanged;
                    //    if (d.Strijker5 != null)
                    //        context.Entry(d.Strijker5).State = EntityState.Unchanged;
                    //}

                    #endregion
                }
                //Update (edit) last prestatie + dates
                else
                {
                    CurrentView.UpdateLast();

                    ButtonBerekenContent = "Berekenen";
                    ButtonToevoegenContent = "Toevoegen";
                    ButtonChangeContent = "Laatste prestatie aanpassen";
                }

                //Save changes to DB
                Ctx.Complete();
            }
            catch (Exception ex)
            {
                Ctx.DiscardChanges();
                MessageBoxService messageService = new MessageBoxService();
                messageService.ShowErrorBox("Er heeft zich een probleem voorgedaan bij het opslaan van een prestatie \n\nError: " + ex.Message);
            }

            //Re init CurrentView => Make new Prestatie, ...
            CurrentView.Init();
            DatumViewModel.Init();
        }
コード例 #39
0
        private void DoAdNewModule(BackgroundWorker backgroundWorker, string fileName)
        {
            var step = 0;
            //1.Verify the Zip file.
            //- The zip file is existed.
            //- The zip file contains the files.
            //2. Verify file contents.
            //- At least 1 dll file should be in the zip file.
            //- The Module.json config file should be found.
            //- The Module is valid and Name is not empty.
            ZipArchive   zip = null;
            ModuleConfig newModule;

            try
            {
                backgroundWorker.ReportProgress(++step, "Verify the zip file.");

                #region Verify the zip file

                if (!File.Exists(fileName))
                {
                    backgroundWorker.ReportProgress(++step,
                                                    "Error: Zip file is not existed. Please check the file location.");
                    return;
                }

                try
                {
                    zip = ZipFile.OpenRead(fileName);
                }
                catch (Exception ex)
                {
                    backgroundWorker.ReportProgress(++step, $"Error: {ex.Message}");
                    Logger.Exception(ex);
                    return;
                }

                #endregion Verify the zip file

                backgroundWorker.ReportProgress(++step, "Verify the file contents.");

                #region Verify the file contents

                if (zip.Entries.Count <= 1)
                {
                    backgroundWorker.ReportProgress(++step, "Error: Zip file is empty.");
                    return;
                }

                var jsonFile = zip.Entries.FirstOrDefault(f => f.Name.StartsWith("Module", StringComparison.Ordinal) &&
                                                          f.Name.EndsWith(".json", StringComparison.Ordinal));

                if (jsonFile.IsNull())
                {
                    backgroundWorker.ReportProgress(++step, "Error: The module json config file is not found.");
                    return;
                }

                var dll = zip.Entries.FirstOrDefault(f => f.Name.EndsWith(".dll", StringComparison.Ordinal));

                if (dll.IsNull())
                {
                    backgroundWorker.ReportProgress(++step, "Error: The module doesn't have any binary file.");
                    return;
                }

                #endregion Verify the file contents

                backgroundWorker.ReportProgress(++step, "Verify the config file.");

                #region Verify the config file

                try
                {
                    // ReSharper disable once PossibleNullReferenceException
                    var tmpFileName = Path.Combine(Path.GetTempPath(), jsonFile.Name);
                    jsonFile.ExtractToFile(tmpFileName, true);
                    newModule = JsonConfigHelper.ReadConfig <ModuleConfig>(tmpFileName);
                    File.Delete(tmpFileName);

                    if (newModule.Name.IsNullOrEmpty())
                    {
                        backgroundWorker.ReportProgress(++step, "Error: Module Name is empty.");
                        return;
                    }

                    if (newModule.Version.IsNullOrEmpty())
                    {
                        backgroundWorker.ReportProgress(++step, "Error: Module Version is empty.");
                        return;
                    }
                    //Verify the binaries if have
                    if (newModule.AssemplyFiles.Count > 0)
                    {
                        var notfounds =
                            newModule.AssemplyFiles.Where(a => !zip.Entries.Any(t => t.Name.EndsWith(a))).ToList();
                        if (notfounds.Any())
                        {
                            backgroundWorker.ReportProgress(++step,
                                                            $"Error: Binaries are not found '{string.Join(",", notfounds)}'.");
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    backgroundWorker.ReportProgress(++step, $"Error: {ex.Message}");
                    Logger.Exception(ex);
                    return;
                }

                #endregion Verify the config file

                //Check duplicate module. if existing module then update the existing one.
                backgroundWorker.ReportProgress(++step, "Check Module duplicating.");

                #region Check Module duplicating

                var oldModule = ShellConfigManager.Modules.FirstOrDefault(m => m.Name.EqualsIgnoreCase(newModule.Name));
                if (oldModule != null)
                {
                    backgroundWorker.ReportProgress(++step,
                                                    $"The module '{oldModule.Name}' is an existing module with version '{oldModule.Version}'.");

                    //Compare the version on both Modules.
                    if (
                        MessageBoxService.ConfirmDialog(this,
                                                        $"Do you want to overwrite module:\n- '{oldModule.Name}' version '{oldModule.Version}' with version '{newModule.Version}'?")
                        .Result != MessageBoxResult.Yes)
                    {
                        backgroundWorker.ReportProgress(++step, "The module importing had been canceled by user.");
                        return;
                    }

                    if (oldModule.IsEnabled)
                    {
                        backgroundWorker.ReportProgress(++step,
                                                        $"The old module '{oldModule.Name}' cannot be overwritten because it is enabled. Please disable it and restart the application in order to overwrite the module '{newModule.Name}'.");
                        return;
                    }

                    if (!oldModule.AllowToManage)
                    {
                        backgroundWorker.ReportProgress(++step,
                                                        $"The old module '{oldModule.Name}' is not allow to be overwritten as allow to manage is disabled.");
                        return;
                    }

                    Directory.CreateDirectory(ShellConfigManager.ShellConfig.BackupModulePath);
                    var backupFileName = Path.Combine(ShellConfigManager.ShellConfig.BackupModulePath,
                                                      new DirectoryInfo(oldModule.Directory).Name + "_" + DateTime.Now.ToString("yyyy.mm.dd-hh.mm.ss") +
                                                      ".zip");

                    ZipFile.CreateFromDirectory(oldModule.Directory, backupFileName, CompressionLevel.Optimal, false);
                    backgroundWorker.ReportProgress(++step,
                                                    $"Backup the old module '{oldModule.Name}' to {backupFileName}.");

                    Directory.Delete(oldModule.Directory, true);
                }

                #endregion Check Module duplicating

                backgroundWorker.ReportProgress(++step, "Extract zip file to Module folder.");

                #region Extract zip file to Module folder.

                // ReSharper disable once AssignNullToNotNullAttribute
                var extractFolderName = Path.Combine(ShellConfigManager.ShellConfig.ModulePath,
                                                     Path.GetFileNameWithoutExtension(fileName));
                zip.ExtractToDirectory(extractFolderName);
                //Check if the extracted folder had only 1 sub-folder and the same is exactly the same with parent folder.
                //Then move all files and folders to the parent then delete sub-folder.
                var extractDirectory = new DirectoryInfo(extractFolderName);
                if (extractDirectory.GetDirectories().Length == 1)
                {
                    var sub = extractDirectory.GetDirectories().First();
                    if (sub.Name.EqualsIgnoreCase(extractDirectory.Name))
                    {
                        sub.MoveAllFilesAndFoldersTo(extractDirectory.FullName);
                    }
                }

                #endregion Extract zip file to Module folder.

                backgroundWorker.ReportProgress(++step,
                                                "New module had been imported. Please restart the application to use the new module.");
            }
            catch (Exception ex)
            {
                backgroundWorker.ReportProgress(++step, $"Error: {ex.Message}");
                backgroundWorker.ReportProgress(++step,
                                                "Import module failed. Please re-start the application and try again.");
                Logger.Exception(ex);
            }
            finally
            {
                //Close the zip file
                zip?.Dispose();
                //Write info to log.
                Logger.Info(TextLog);
            }
        }
コード例 #40
0
        private void getDocumentDetail()
        {
            try
            {
                if (Entity == null)
                {
                    return;
                }
                CollectionDetail      = new ObservableCollection <DocumentDetail>();
                ListDetailCurrentTask = null;
                foreach (var document in Entity.Documents)
                {
                    foreach (var detail in document.DocumentDetail)
                    {
                        DocumentDetail currentDetail = new DocumentDetail();

                        currentDetail.Caliber          = detail.Caliber;
                        currentDetail.CreatedDate      = detail.CreatedDate;
                        currentDetail.Discount         = detail.Discount;
                        currentDetail.DiscountType     = detail.DiscountType;
                        currentDetail.Document         = detail.Document;
                        currentDetail.DocumentId       = detail.DocumentId;
                        currentDetail.ExternalDetailId = detail.ExternalDetailId;
                        currentDetail.Id                 = detail.Id;
                        currentDetail.IdLocal            = detail.IdLocal;
                        currentDetail.IdLocalDocument    = detail.IdLocalDocument;
                        currentDetail.LastUpdate         = detail.LastUpdate;
                        currentDetail.LineNum            = detail.LineNum;
                        currentDetail.MaterialId         = detail.MaterialId;
                        currentDetail.MaterialName       = detail.MaterialName;
                        currentDetail.Price              = detail.Price;
                        currentDetail.Qty                = detail.Qty;
                        currentDetail.QtyDelivered       = detail.QtyDelivered;
                        currentDetail.ReasonNoDeliveryId = detail.ReasonNoDeliveryId;
                        currentDetail.Tone               = detail.Tone;
                        currentDetail.UserIdCreated      = detail.UserIdCreated;
                        currentDetail.UserIdUpdated      = detail.UserIdUpdated;

                        if (detail.Qty == detail.QtyDelivered)
                        {
                            currentDetail.Status = "Completo";
                        }
                        else
                        {
                            currentDetail.Status = "Incompleto";
                        }
                        CollectionDetail.Add(currentDetail);
                    }
                }

                if (CollectionDetail.Count > 0)
                {
                    ListDetailCurrentTask = CollectionDetail;
                }
            }
            catch (Exception ex)
            {
                MessageBoxService.ShowMessage(GetStringValue(Next.Enums.Enums.MessageError.DataError), ex.Message,
                                              MessageButton.OK, MessageIcon.Error);
            }
        }
 public virtual void ShowRowDetails(SampleData obj)
 {
     MessageBoxService.Show(obj.ToString(), "Row Details");
 }
コード例 #42
0
 private void DisplayErrorMessage(string message, string header)
 {
     FinishUnboundLoad();
     MessageBoxService.ShowMessage(message, header, MessageButton.OK, MessageIcon.Error);
 }
コード例 #43
0
 public ImportAddressToWatchController(AddressManager addressManger, MessageBoxService msgBox)
 {
     this.ImportCommand  = new DelegateCommand(ImportAddress);
     this.MsgBox         = msgBox;
     this.AddressManager = addressManger;
 }
コード例 #44
0
        public virtual void Add()
        {
            try
            {
                Ctx.KlantTypes.Add(AddType);
                Ctx.Complete();
            }
            catch (Exception ex)
            {
                Ctx.DiscardChanges();
                MessageBoxService messageService = new MessageBoxService();
                messageService.ShowErrorBox("Er heeft zich een probleem voorgedaan bij het toevoegen van een nieuwe 'Klant Type' (" + AddType.Type + " " + AddType.Naam + ")\n\nError: " + ex.Message);
            }

            GetData();
            AddType = new KlantType();
        }