Example #1
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is Button button)
            {
                switch (button.Name)
                {
                case "buttonEdit":
                    EditCommand?.Execute(null);
                    break;

                case "buttonDelete":
                    DeleteCommand?.Execute(null);
                    break;

                case "buttonCancel":
                    CancelCommand?.Execute(null);
                    break;

                case "buttonSave":
                    SaveCommand?.Execute(null);
                    break;

                case "buttonAdd":
                    AddCommand?.Execute(null);
                    break;
                }
            }
        }
Example #2
0
        private void _rightMenuButton_Clicked(object sender, System.EventArgs e)
        {
            switch (RightMenu)
            {
            case RightMenuIcon.Add:
                AddCommand?.Execute(null);
                break;

            case RightMenuIcon.CustomText:
            case RightMenuIcon.CustomIcon:
                RightMenuCommand?.Execute(null);
                break;

            case RightMenuIcon.Delete:
                DeleteCommand?.Execute(null);
                break;

            case RightMenuIcon.Edit:
                EditCommand?.Execute(null);
                break;

            case RightMenuIcon.Save:
                SaveCommand?.Execute(null);
                break;

            case RightMenuIcon.Settings:
                SettingsCommand?.Execute(null);
                break;
            }
        }
 private void SaveParsedWords(VocabularyRecord[] items)
 {
     foreach (var item in items)
     {
         if (!QuestionList.Any(q => string.Compare(q.ForeignText, item.ForeignText, true) == 0))
         {
             QuestionList.Add(new VocabularyRecordViewModel(item));
         }
     }
     SaveCommand.Execute(null);
 }
        private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            if (!_validate())
            {
                return;
            }
            SaveCommand?.Execute(null);
            VisualStateManager.GoToState(this, "ThanksState", true);
            await Task.Delay(6000);

            VisualStateManager.GoToState(this, "BackHomeState", true);
        }
        private void OnToolbarAction(ToolbarActionMessage message)
        {
            if (message == ToolbarActionMessage.ClickedSaveButton)
            {
                ValidateSearchQuery(SearchQueryInput);

                if (SearchQueryInputError == null)
                {
                    SaveCommand.Execute(null);
                }
            }
        }
Example #6
0
        public IncomingRequestViewModel(IUnityContainer container) : base(container)
        {
            _messageService     = container.Resolve <IMessageService>();
            _fileManagerService = container.Resolve <IFileManagerService>();

            InstructRequestCommand = new DelegateLogCommand(
                () =>
            {
                Item.IsActual        = true;
                Item.InstructionDate = DateTime.Now;
                //сохраняем запрос
                SaveCommand.Execute(null);
                //закрываем запрос
                GoBackCommand.Execute(null);
            },
                () => Item.IsValid && Item.IsChanged && Item.Performers.Any());

            RequestIsNotActualCommand = new DelegateLogCommand(
                () =>
            {
                var dr = _messageService.ShowYesNoMessageDialog("Подтверждение", "Вы уверены, что запрос не актуален?", defaultYes: true);
                if (dr != MessageDialogResult.Yes)
                {
                    return;
                }

                Item.IsActual = false;
                Item.Performers.Clear();

                //сохраняем запрос
                if (Item.IsChanged)
                {
                    SaveCommand.Execute(null);
                }
                //закрываем запрос
                GoBackCommand.Execute(null);
            },
                () => Item.IsValid);

            OpenFolderCommand = new DelegateLogCommand(
                () =>
            {
                if (string.IsNullOrEmpty(GlobalAppProperties.Actual.IncomingRequestsPath))
                {
                    _messageService.ShowOkMessageDialog("Информация", "Путь к хранилищу приложений не назначен");
                    return;
                }

                var path = _fileManagerService.GetPath(Item.Model.Document);
                Process.Start($"\"{path}\"");
            });
        }
        private void DeleteCommandHandler()
        {
            if (MessageBox.ShowDialog(string.Format("Do you confirm delete {0} records.", SelectedItems.Count()), "Delete", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                foreach (var item in SelectedItems.ToList())
                {
                    QuestionList.Remove(item);
                }
            }

            SaveCommand.Execute(null);
            RaiseCanExecuteChanged();
        }
        private void AddCommandHandler()
        {
            var question = new VocabularyRecord()
            {
                ShowDateStart = DateTime.Now.Date, ShowDateEnd = DateTime.Now.Date.AddDays(3)
            };
            var vm = new VocabularyItemDialogViewModel(
                (item) => { QuestionList.Add(new VocabularyRecordViewModel(item)); SaveCommand.Execute(null); }
                );

            vm.Question = question;
            dialogService.ShowDialog(vm, false, "modalDialog");
            RaiseCanExecuteChanged();
        }
        public void Execute_ClearsChannelList()
        {
            var viewModel = new SettingsViewModel(
                new AddInSettings(string.Empty, string.Empty, string.Empty,
                                  string.Empty, It.IsAny <MattermostVersion>()),
                Mock.Of <ICommand>(),
                Mock.Of <ICommand>());
            var saveService    = new Mock <ISettingsSaveService>();
            var classUnderTest = new SaveCommand(saveService.Object, Mock.Of <IClosableWindow>());

            classUnderTest.Execute(viewModel);

            saveService.Verify(x => x.SaveChannels(string.Empty));
        }
        public void Execute_ClosesWindow()
        {
            var viewModel = new SettingsViewModel(
                new AddInSettings(string.Empty, string.Empty, string.Empty,
                                  string.Empty, It.IsAny <MattermostVersion>()),
                Mock.Of <ICommand>(),
                Mock.Of <ICommand>());
            var window         = new Mock <IClosableWindow>();
            var classUnderTest = new SaveCommand(Mock.Of <ISettingsSaveService>(), window.Object);

            classUnderTest.Execute(viewModel);

            window.Verify(x => x.Close());
        }
Example #11
0
        public async Task <ActionResult> Save(Domain.Models.ContentType contentType, int id)
        {
            var cmd      = new SaveCommand(contentType, id).SetUserContext(User);
            var response = await cmd.Execute();

            return(JsonResult(response));
            //if (response.Success)
            //{
            //    return Json(new { success = true });
            //}
            //else
            //{
            //    return JsonError(response.Message);
            //}
        }
Example #12
0
        public async Task <ActionResult> SaveComment(int commentId)
        {
            var cmd      = new SaveCommand(Domain.Models.ContentType.Comment, commentId);
            var response = await cmd.Execute();

            //Saving.SaveSubmission(messageId, loggedInUser);

            if (response.Success)
            {
                return(Json("Saving ok", JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, response.Message));
            }
        }
Example #13
0
            public void MigratesTheFileSystem(
                [Frozen] Mock <IFileSystem> fileSystem, [Frozen] Mock <IFileSystemMigrator> migrator)
            {
                // Arrange
                var sut = new SaveCommand(
                    new Mock <IPackageAssemblyResolver>().Object,
                    fileSystem.Object,
                    new Mock <ILog>().Object,
                    migrator.Object);

                // Act
                sut.Execute();

                // Assert
                migrator.Verify(m => m.Migrate(), Times.Once);
            }
Example #14
0
        protected override void GoBackCommand_Execute()
        {
            //если придет запрос при несохраненных изменениях
            if (SaveCommand.CanExecute())
            {
                var dr = Container.Resolve <IMessageService>().ShowYesNoMessageDialog("Сохранение", "Сохранить сделанные изменения?", defaultNo: true);
                if (dr == MessageDialogResult.Yes)
                {
                    SaveCommand.Execute();
                }

                if (dr == MessageDialogResult.No)
                {
                    IsConfirmGoBackWithoutSaving = true;
                }
            }

            base.GoBackCommand_Execute();
        }
        /// <summary>
        /// Ends the edit.
        /// </summary>
        /// <param name="commit">if set to <c>true</c> [commit].</param>
        private void EndEdit(bool commit)
        {
            if (this.textBox == null)
            {
                return;
            }

            var textBoxBindingExpression   = this.textBox.GetBindingExpression(TextBox.TextProperty);
            var textBlockBindingExpression = this.GetBindingExpression(TextProperty);

            if (commit)
            {
                var isDirty = textBoxBindingExpression.IsDirty;

                if (textBoxBindingExpression != null)
                {
                    textBoxBindingExpression.UpdateSource();
                }

                if (textBlockBindingExpression != null)
                {
                    textBlockBindingExpression.UpdateTarget();
                }

                if (isDirty && SaveCommand != null && SaveCommand.CanExecute(null))
                {
                    SaveCommand.Execute(null);
                }
            }

            this.internalIsEditingChange = true;
            this.IsEditing = false;
            this.internalIsEditingChange = false;
            var p = (Panel)this.Parent;

            p.Children.Remove(this.textBox);
            this.textBox    = null;
            this.Visibility = Visibility.Visible;
            if (this.oldfocus != null && this.oldfocus.IsVisible)
            {
                this.oldfocus.Focus();
            }
        }
Example #16
0
        protected override void OnTextChanged(string oldTextValue, string newTextValue)
        {
            if (IsFocused)
            {
                // Cancels the current execution
                if (cancellationTokenSource != null)
                {
                    cancellationTokenSource.Cancel();
                }

                // Creates a new instance for the cancellation token
                IsSaving = true;
                cancellationTokenSource = new CancellationTokenSource();

                // Executes a background operation
                Task.Run(async() =>
                {
                    // Takes the token reference reference that will be cancelled after the next character inserted
                    var token = cancellationTokenSource.Token;
                    // Await a certain time before trying another search
                    await Task.Delay(SaveDelay);

                    // If the token wasn't cancelled (when another character is inserted), do the search
                    if (!token.IsCancellationRequested)
                    {
                        Dispatcher.BeginInvokeOnMainThread(() =>
                        {
                            if (SaveCommandParameter == null)
                            {
                                SaveCommand?.Execute(newTextValue);
                            }
                            else
                            {
                                SaveCommand?.Execute(SaveCommandParameter);
                            }

                            IsSaving = false;
                        });
                    }
                }, cancellationTokenSource.Token);
            }
        }
Example #17
0
        /// <summary>
        /// Handles the Click event of the Save control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            int errors = 0;

            foreach (TabItem tab in _Editors.Items)
            {
                errors += (tab.Content as UserControl)
                          .GetVisualOfBaseType <FrameworkElement>()
                          .Where(element => Validation.GetHasError(element))
                          .Count();
            }

            if (errors != 0)
            {
                MessageBox.Show(SocialStream.ConfigTool.Properties.Resources.SaveError);
                return;
            }

            SaveCommand.Execute();
        }
        public void ProcessShortcutKey(ProcessShortcutKeyEventArgs e)
        {
            switch (e.Key)
            {
            case ShortcutKey.Save:
            case ShortcutKey.SaveAndClose:
                SaveCommand.Execute(null);
                e.Handled = true;
                break;

            case ShortcutKey.Close:
                //case ShortcutKey.Exit:
                CancelCommand.Execute(null);
                e.Handled = true;
                break;
                //case ShortcutKey.Delete:
                //    DeleteCommand.Execute(null);
                //    e.Handled = true;
                //    break;
            }
        }
Example #19
0
        protected override void OnTextChanged(string oldTextValue, string newTextValue)
        {
            base.OnTextChanged(oldTextValue, newTextValue);

            if (IsSavingEnabled)
            {
                // Cancels the current execution
                if (cancellationTokenSource != null)
                {
                    cancellationTokenSource.Cancel();
                }

                // Creates a new instance for the cancellation token
                IsSaving = true;
                cancellationTokenSource = new CancellationTokenSource();

                // Executes a background operation
                Task.Run(async() =>
                {
                    // Takes the token reference reference that will be cancelled after the next character inserted
                    var token = cancellationTokenSource.Token;

                    // Getting the bytes from the url that was inserted on the text
                    var bytes = await downloadService.DownloadImageUrl(newTextValue);

                    // If the token wasn't cancelled (when another character is inserted), send it to the ViewModel
                    if (!token.IsCancellationRequested)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            SaveCommand?.Execute(bytes);

                            IsSaving = false;
                        });
                    }
                }, cancellationTokenSource.Token);
            }
        }
        /// <summary>
        /// load ItemInstance based on item selected from list, ie load shadow object
        /// </summary>
        /// <param name="selListItem"></param>
        protected override void loadSelectedItem(ItemResult selListItem)
        {
            if ((selListItem?.pk != null) && (selListItem.pk != Guid.Empty))
            {
                selectedItem = db.db.Load <Item>(selListItem.pk);

#if false
                // if not currently editing anything then we match current item, but
                // we don't update currentItem otherwise as may be a clone, etc.
                if (isDetailViewInActive && EditCommand.CanExecute(null))
                {
                    EditCommand.Execute(null);
                }
#else
                // update detail view immediately when a new item is selected
                // note this will loose changes for a clone
                if (currentItem != null && currentItem.IsChanged)
                {
                    var x = MessageBox.Show("Current item has been modified, do you wish to save changes?", $"Changes to {currentItem.displayName} will be lost!", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);
                    if (x == MessageBoxResult.Yes)
                    {
                        if (SaveCommand.CanExecute(null))
                        {
                            SaveCommand.Execute(null);
                        }
                    }
                }
                if (EditCommand.CanExecute(null))
                {
                    EditCommand.Execute(null);
                }
#endif
            }
            else
            {
                selectedItem = null;
            }
        }
Example #21
0
        /// <summary>
        /// Determine if we should
        /// </summary>
        /// <returns></returns>
        protected bool GetAbandonCurrentProject()
        {
            if (!ModProject.IsDirty)
            {
                return(true);
            }
            bool?booSave = ConfirmSaveCurrentProject();

            if (!booSave.HasValue)
            {
                return(false);
            }
            if (booSave.Value)
            {
                string strPath = GetProjectSavePath();
                if (String.IsNullOrEmpty(strPath))
                {
                    return(false);
                }
                SaveCommand.Execute(strPath);
            }
            return(true);
        }
        public void Execute_CallsSaveService()
        {
            const string            mattermostUrl = "http://localhost";
            const string            teamId        = "teamId";
            const string            username      = "******";
            const MattermostVersion version       = MattermostVersion.ApiVersionOne;
            var viewModel = new SettingsViewModel(
                new AddInSettings(string.Empty, string.Empty, string.Empty,
                                  string.Empty, It.IsAny <MattermostVersion>()),
                Mock.Of <ICommand>(),
                Mock.Of <ICommand>())
            {
                MattermostUrl = mattermostUrl,
                TeamId        = teamId,
                Username      = username,
                Version       = version
            };
            var saveService    = new Mock <ISettingsSaveService>();
            var classUnderTest = new SaveCommand(saveService.Object, Mock.Of <IClosableWindow>());

            classUnderTest.Execute(viewModel);

            saveService.Verify(x => x.SaveCredentials(mattermostUrl, teamId, username, version));
        }
        /// <summary>
        /// KarveToolBarViewModel is a view model to modle the toolbar behaviour.
        /// </summary>
        /// <param name="dataServices">Service for fetching datas</param>
        /// <param name="eventManager">Service for communicate with other view models</param>
        /// <param name="careKeeper">Service for caring command and storing/undoing command</param>
        /// <param name="regionManager">Service for region handling</param>
        /// <param name="dialogService">Service for spotting the dialog</param>
        /// <param name="configurationService">Service for the configuraration parameters</param>
        public KarveToolBarViewModel(IDataServices dataServices,
                                     IEventManager eventManager,
                                     ICareKeeperService careKeeper,
                                     IRegionManager regionManager,
                                     IDialogService dialogService,
                                     IConfigurationService configurationService) : base(dataServices, null, dialogService, configurationService)
        {
            this._dictionary           = SubsystemFactory.GetSubsytem();
            this._dataServices         = dataServices;
            this._dialogService        = dialogService;
            this._configurationService = configurationService;
            this._eventManager         = eventManager;
            this._eventManager.RegisterObserverToolBar(this);
            this._careKeeper           = careKeeper;
            this.SaveCommand           = new DelegateCommand(DoSaveCommand);
            this.NewCommand            = new DelegateCommand(DoNewCommand);
            this.DeleteCommand         = new DelegateCommand <object>(DoDeleteCommand);
            this._dataServices         = dataServices;
            this._configurationService = configurationService;
            this._eventManager         = eventManager;
            this._eventManager.RegisterObserverToolBar(this);
            this.CurrentSaveImagePath = currentSaveImage;
            _regionManager            = regionManager;
            _states              = ToolbarStates.None;
            _noActiveValue       = string.Empty;
            this.IsSaveEnabled   = false;
            this.IsDeleteEnabled = false;
            this.IsNewEnabled    = false;
            ConfirmationRequest  = new InteractionRequest <IConfirmation>();
            Confirmation request = new Confirmation
            {
                Title   = "Confirmacion",
                Content = confirmDelete
            };

            ViewModelUri        = new Uri("karve://toolbar/viewmodel?id=" + UniqueId);
            ConfirmationCommand = new DelegateCommand(() =>
            {
                // string noActiveValue = configurationService.GetPrimaryKeyValue();
                request.Content = confirmDelete;
                ConfirmationRequest.Raise(request);
                if (request.Confirmed)
                {
                    string value   = string.Empty;
                    var singleView = _regionManager.Regions[RegionNames.TabRegion].ActiveViews.FirstOrDefault();
                    if (singleView != null)
                    {
                        var headerProp = singleView.GetType().GetProperty("Header");
                        if (headerProp != null)
                        {
                            if (headerProp.GetValue(singleView) is string header)
                            {
                                value = header.Split('.')[0];
                            }
                        }
                    }

                    DeleteCommand.Execute(value);
                }
            });
            SaveValueCommand = new DelegateCommand(() =>
            {
                request.Content = confirmSave;

                ConfirmationRequest.Raise(request);
                if (request.Confirmed)
                {
                    SaveCommand.Execute();
                }
                else
                {
                    this.CurrentSaveImagePath = KarveToolBarViewModel.currentSaveImage;
                }
            });

            AddValidationChain();
            _uniqueId = ObserverName + Guid.NewGuid();
        }
        public void Execute_Throws_IfArgumentIsNotViewModel()
        {
            var classUnderTest = new SaveCommand(Mock.Of <ISettingsSaveService>(), Mock.Of <IClosableWindow>());

            Assert.Throws <ArgumentException>(() => classUnderTest.Execute(new object()));
        }
 public override void OnWindowClosing(object sender, CancelEventArgs e)
 {
     SaveCommand.Execute(new object[] { this, sender });
 }
 private void SaveClicked(object sender, RoutedEventArgs e)
 {
     DialogHost.CloseDialogCommand.Execute(this, this);
     SaveCommand?.Execute(null);
 }
Example #27
0
 public void ShouldMakeTagCloud_IfSourceFileIsTxt()
 {
     tagCloudCommand.Execute(new[] { GetPathToTestFile("txt_file.txt") });
     saveCommand.Execute(new[] { GetPathForSavingTagCloud("txt_file.png") });
     savingDirectory.GetFiles().Select(x => x.Name).Should().Contain("txt_file.png");
 }
 private async void Button_Clicked(object sender, EventArgs e)
 {
     SaveCommand.Execute(Text);
     await Navigation.PopAsync();
 }
Example #29
0
        public TransferViewModel() : base(PermissionItemName.TransferForm)
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                OpenItemSearch = new RelayCommand(() => {
                    try
                    {
                        if (SelectedMainRow.TblWarehouseFrom != null &&
                            !string.IsNullOrWhiteSpace(SelectedMainRow.TblWarehouseFrom.Code) &&
                            SelectedMainRow.TblWarehouseTo != null &&
                            !string.IsNullOrWhiteSpace(SelectedMainRow.TblWarehouseTo.Code))
                        {
                            var vm             = new ItemDimensionSearchViewModel();
                            vm.WarehouseCode   = SelectedMainRow.TblWarehouseFrom.Code;
                            vm.WarehouseToCode = SelectedMainRow.TblWarehouseTo.Code;
                            vm.SiteIserial     = SelectedMainRow.TblWarehouseFrom.TblSite;
                            vm.AppliedSearchResultList.CollectionChanged += (s, e) => {
                                // هنا هبدا اعبى الى جاى من السيرش
                                foreach (var item in vm.AppliedSearchResultList)
                                {
                                    var temp = SelectedMainRow.TblTransferDetails.FirstOrDefault(td => td.ItemDimFrom == item.ItemDimFromIserial &&
                                                                                                 td.ItemTransfer.ColorToId == item.ColorToId &&
                                                                                                 (td.ItemTransfer.SizeTo == item.SizeTo || (string.IsNullOrEmpty(td.ItemTransfer.SizeTo) && string.IsNullOrEmpty(item.SizeTo))) &&
                                                                                                 (td.ItemTransfer.BatchNoTo == item.BatchNoTo || (string.IsNullOrEmpty(td.ItemTransfer.BatchNoTo) && string.IsNullOrEmpty(item.BatchNoTo))));
                                    decimal allTransferedQuantity = SelectedMainRow.TblTransferDetails.Where(td =>
                                                                                                             td.ItemTransfer.ItemDimFromIserial == item.ItemDimFromIserial).Sum(td => td.ItemTransfer.TransferredQuantity);

                                    if (temp == null)// مش موجود
                                    {
                                        if ((item.AvailableQuantity < (allTransferedQuantity + item.TransferredQuantity) && item.PendingQuantity >= 0) ||
                                            ((item.AvailableQuantity + item.PendingQuantity) < (allTransferedQuantity + item.TransferredQuantity) && item.PendingQuantity >= 0))
                                        {
                                            MessageBox.Show(strings.CheckQuantities);
                                            return;
                                        }
                                        var transferDetail = new TransferDetail()
                                        {
                                            TransferHeader = SelectedMainRow.Iserial,
                                            ItemDimFrom    = item.ItemDimFromIserial,
                                            ItemDimTo      = item.ItemDimToIserial,
                                            Quantity       = item.TransferredQuantity,
                                            ItemTransfer   = item,
                                        };
                                        ValidateDetailRow(transferDetail);
                                    }
                                    else// لو موجود هحدث الكمية
                                    {
                                        if ((item.AvailableQuantity < (allTransferedQuantity - temp.ItemTransfer.AvailableQuantity + item.TransferredQuantity) && item.PendingQuantity >= 0) ||
                                            ((item.AvailableQuantity + item.PendingQuantity) < (allTransferedQuantity - temp.ItemTransfer.AvailableQuantity + item.TransferredQuantity) && item.PendingQuantity >= 0))
                                        {
                                            MessageBox.Show(strings.CheckQuantities);
                                            return;
                                        }
                                        temp.ItemTransfer.AvailableQuantity   = item.AvailableQuantity;
                                        temp.ItemTransfer.PendingQuantity     = item.PendingQuantity;
                                        temp.ItemTransfer.TransferredQuantity = item.TransferredQuantity;
                                        temp.Quantity = item.TransferredQuantity;
                                    }
                                }
                                RaisePropertyChanged(nameof(Total));
                            };
                            var childWindowSeach = new ItemDimensionSearchChildWindow(vm);
                            childWindowSeach.Show();
                            childWindowSeach.IsTransfer    = true;
                            childWindowSeach.QuantityTitle = strings.Transferred;
                            vm.FromTitle = string.Format("From {0}", SelectedMainRow.TblWarehouseFrom.Ename);
                            vm.ToTitle   = string.Format("To {0}", SelectedMainRow.TblWarehouseTo.Ename);
                            vm.Title     = strings.TransferItem;
                            _FormMode    = FormMode.Search;
                        }
                        else
                        {
                            MessageBox.Show(strings.PleaseSelectWarehouse);
                        }
                    }
                    catch (Exception ex) { throw ex; }
                });
                OpenFPItemSearch = new RelayCommand(() =>
                {
                    try
                    {
                        if (SelectedMainRow.TblWarehouseFrom != null &&
                            !string.IsNullOrWhiteSpace(SelectedMainRow.TblWarehouseFrom.Code) &&
                            SelectedMainRow.TblWarehouseTo != null &&
                            !string.IsNullOrWhiteSpace(SelectedMainRow.TblWarehouseTo.Code))
                        {
                            var vm = new ItemFPSearchViewModel();
                            vm.FPAppliedSearchResultList.CollectionChanged += (s, e) =>
                            {
                                if (vm.FPAppliedSearchResultList.Count > 0)
                                {
                                    var SearchItem = vm.FPAppliedSearchResultList.FirstOrDefault();
                                    if (SelectedMainRow.TblTransferDetails != null && SelectedMainRow.TblTransferDetails.Count > 0)
                                    {
                                        SelectedDetailRow.ItemFPName    = SearchItem.ItemPerRow.Name;
                                        SelectedDetailRow.ItemFPCode    = SearchItem.ItemPerRow.Code;
                                        SelectedDetailRow.ItemFPIserial = SearchItem.ItemPerRow.Iserial;

                                        foreach (var item in SelectedMainRow.TblTransferDetails)
                                        {
                                            if (item.ItemTransfer.ItemCode == SelectedDetailRow.ItemTransfer.ItemCode)
                                            {
                                                item.ItemFPName    = SearchItem.ItemPerRow.Name;
                                                item.ItemFPCode    = SearchItem.ItemPerRow.Code;
                                                item.ItemFPIserial = SearchItem.ItemPerRow.Iserial;
                                            }
                                        }
                                    }
                                }
                            };
                            var childWindowSeach = new ItemFPSearchChildWindow(vm);
                            childWindowSeach.Show();
                            _FormMode = FormMode.Search;
                        }
                        else
                        {
                            MessageBox.Show(strings.PleaseSelectWarehouse);
                        }
                    } catch (Exception ex) { throw ex; }
                });

                ApproveTransfer = new RelayCommand(() => {
                    if (SaveCommand.CanExecute(null))
                    {
                        SaveCommand.Execute(null);
                    }
                    SelectedMainRow.Approved    = true;
                    SelectedMainRow.ApproveDate = DateTime.Now;
                    SelectedMainRow.ApprovedBy  = LoggedUserInfo.Iserial;
                    if (SaveCommand.CanExecute(null))
                    {
                        SaveCommand.Execute(null);
                    }
                    if (SelectedMainRow.Approved)//كده نفذ فهعمل جديد
                    {
                        if (NewCommand.CanExecute(null))
                        {
                            NewCommand.Execute(null);
                        }
                    }
                }, () => CheckCanApprove());
                DeleteTransferDetail = new RelayCommand <object>((o) =>
                {
                    if (((KeyEventArgs)(o)).Key == Key.Delete)
                    {
                        if (SelectedMainRow.Iserial <= 0 || SelectedDetailRow.Iserial <= 0)
                        {
                            SelectedMainRow.TblTransferDetails.Remove(SelectedDetailRow);
                            if (SelectedMainRow.TblTransferDetails.Count == 0)
                            {
                                AddNewDetailRow(false);
                            }
                        }
                        else
                        {
                            DeleteDetailRow();
                        }
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                }, (o) => {
                    return(SelectedMainRow != null && !SelectedMainRow.Approved);
                });
                LoadingDetailRows = new RelayCommand <object>((o) =>
                {
                    var e = o as DataGridRowEventArgs;
                    //if (SelectedMainRow.TblTransferDetails.Count < PageSize)
                    //{
                    //    return;
                    //}
                    //if (SelectedMainRow.TblTransferDetails.Count - 2 < e.Row.GetIndex() && !Loading)
                    //{
                    //    GetDetailData();
                    //}
                });
                WarehouseClient.GetItemDimensionQuantitiesCompleted += (s, e) =>
                {
                    var temp = SelectedMainRow.TblTransferDetails.FirstOrDefault(ad =>
                                                                                 ad.ItemDimFrom == e.Result.ItemDimFromIserial);
                    var qtemp = e.Result.AvailableQuantity;
                    if (temp != null)
                    {
                        SelectedDetailRow = temp;
                    }
                    else//هعمل واحد جديد
                    {
                        temp = new TransferDetail()
                        {
                            TransferHeader = SelectedMainRow.Iserial,
                            ItemDimFrom    = e.Result.ItemDimFromIserial,
                            ItemDimTo      = e.Result.ItemDimToIserial,
                        };
                        temp.ItemTransfer.InjectFrom(e.Result);
                        temp.ItemTransfer.ColorPerRow.InjectFrom(e.Result.ColorPerRow);
                        temp.ItemTransfer.AvailableQuantity   = qtemp;
                        temp.ItemTransfer.TransferredQuantity = 0;
                        temp.Quantity = 0;
                        ValidateDetailRow(temp);
                    }
                };
                GetDetailItem = new RelayCommand <object>((o) =>
                {
                    if (((KeyEventArgs)(o)).Key == Key.Enter)
                    {
                        if (SelectedMainRow.TblWarehouseFrom == null || SelectedMainRow.TblWarehouseTo == null)
                        {
                            MessageBox.Show(strings.PleaseSelectWarehouse);
                            return;
                        }
                        WarehouseClient.GetItemDimensionQuantitiesAsync(
                            SelectedMainRow.TblWarehouseFrom.Code,
                            SelectedMainRow.TblWarehouseTo.Code,
                            ItemDimFromIserial,
                            SelectedMainRow.DocDate);
                    }
                });
                //SearchComboFrom = new RelayCommand<object>((o) =>
                //{
                //    if (((KeyEventArgs)(o)).Key == Key.F2)
                //    {if (SelectedMainRow.TblWarehouseFrom == null) SelectedMainRow.TblWarehouseFrom = new WarehouseService.TblWarehouse();
                //    new GenericSearchViewModel<TblWarehouse>().SearchLookup(WarehouseListFrom, SelectedMainRow.TblWarehouseFrom
                //            , new SilverlightCommands.RelayCommand((p) => { int x = 0;x++; }), "search warehouse", new Models.LookupItemModel(),
                //            new SilverlightCommands.RelayCommand((p) => { int y = 0;y++; }));
                //    }
                //});
                ReturnToBarcode = new RelayCommand <object>((o) =>
                {
                    //if (((KeyEventArgs)(o)).Key == Key.Enter)
                    //{
                    //    foreach (var item in SelectedMainRow.TblTransferDetails)
                    //    {
                    //        item.IsQuantityFocused = false;
                    //    }
                    //    IsRefFocused = true;
                    //}
                    RaisePropertyChanged(nameof(Total));
                });
                DetailSelectionChanged = new RelayCommand <object>((o) =>
                {
                    var e = o as SelectionChangedEventArgs;
                    // هنا هنقل الفوكس للكمية شوف بقى ازاى
                    IsRefFocused = false;
                    foreach (var item in SelectedMainRow.TblTransferDetails)
                    {
                        item.IsQuantityFocused = false;
                    }
                    SelectedDetailRow.IsQuantityFocused = true;
                });
                this.PremCompleted += (s, sv) =>
                {
                    if (this.CustomePermissions.SingleOrDefault(x => x.Code == "TransferApprove") != null)
                    {
                        CanApprove = true;
                    }
                };
                this.GetCustomePermissions(PermissionItemName.TransferForm.ToString());

                MainRowList = new ObservableCollection <TransferHeader>();
                AddNewMainRow(false);

                WarehouseClient.GetUserAsignedWarehousesForTransferCompleted += (s, e) =>
                {
                    UserWarehouseList.Clear();
                    foreach (var item in e.Result)
                    {
                        UserWarehouseList.Add(item);
                    }
                };
                WarehouseClient.GetUserAsignedWarehousesForTransferAsync(LoggedUserInfo.Iserial);

                WarehouseClient.GetTransferCompleted += (s, sv) =>
                {
                    foreach (var row in sv.Result)
                    {
                        var newrow = new TransferHeader();
                        newrow.InjectFrom(row);
                        MainRowList.Add(newrow);
                    }
                    Loading   = false;
                    FullCount = sv.fullCount;
                    if (SearchWindow != null)
                    {
                        SearchWindow.FullCount = sv.fullCount;
                        SearchWindow.Loading   = false;
                    }
                    if (FullCount == 0 && MainRowList.Count == 0)
                    {
                        AddNewMainRow(false);
                    }
                };
                WarehouseClient.GetTransferDetailCompleted += (s, sv) =>
                {
                    SelectedMainRow.TblTransferDetails.Clear();
                    foreach (var row in sv.Result)
                    {
                        var newrow = new TransferDetail();
                        newrow.InjectFrom(row);
                        newrow.ItemTransfer.InjectFrom(row.ItemTransfer);
                        newrow.ItemTransfer.ColorPerRow.InjectFrom(row.ItemTransfer.ColorPerRow);
                        SelectedMainRow.TblTransferDetails.Add(newrow);
                    }
                    if (!SelectedMainRow.TblTransferDetails.Any())
                    {
                        AddNewDetailRow(false);
                    }
                    Loading = false;
                    RaisePropertyChanged(nameof(Total));
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };
                WarehouseClient.UpdateOrInsertTransferHeaderCompleted += (s, x) =>
                {
                    TransferHeader savedRow = null;
                    if (x.outindex >= 0)
                    {
                        savedRow = MainRowList.ElementAt(x.outindex);
                    }

                    if (savedRow != null)
                    {
                        savedRow.InjectFrom(x.Result);
                        savedRow.TblWarehouseFrom = WarehouseListFrom.FirstOrDefault(w => w.Iserial == savedRow.WarehouseFrom);
                        savedRow.TblWarehouseTo   = WarehouseListTo.FirstOrDefault(w => w.Iserial == savedRow.WarehouseTo);
                        savedRow.TblTransferDetails.Clear();
                        foreach (var item in x.Result.TblTransferDetails)
                        {
                            var detailTemp = new TransferDetail();
                            detailTemp.InjectFrom(item);
                            detailTemp.ItemTransfer.InjectFrom(item.ItemTransfer);
                            detailTemp.ItemTransfer.ColorPerRow.InjectFrom(item.ItemTransfer.ColorPerRow);
                            savedRow.TblTransferDetails.Add(detailTemp);
                        }
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                    DeleteCommand.RaiseCanExecuteChanged();
                    ApproveTransfer.RaiseCanExecuteChanged();
                    DeleteTransferDetail.RaiseCanExecuteChanged();
                    // IsNewChanged();
                };
                WarehouseClient.UpdateOrInsertTransferDetailCompleted += (s, x) =>
                {
                    var savedRow = SelectedMainRow.TblTransferDetails.ElementAt(x.outindex);
                    if (savedRow != null)
                    {
                        savedRow.InjectFrom(x.Result);
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };
                WarehouseClient.DeleteTransferCompleted += (s, ev) =>
                {
                    if (ev.Error != null)
                    {
                        throw ev.Error;
                    }

                    var oldrow = MainRowList.FirstOrDefault(x => x.Iserial == ev.Result);
                    if (oldrow != null)
                    {
                        MainRowList.Remove(oldrow);
                    }
                };
                WarehouseClient.DeleteTransferDetailCompleted += (s, ev) =>
                {
                    if (ev.Error != null)
                    {
                        throw ev.Error;
                    }
                    var oldrow = SelectedMainRow.TblTransferDetails.FirstOrDefault(x => x.Iserial == ev.Result.Iserial);
                    if (oldrow != null)
                    {
                        SelectedMainRow.TblTransferDetails.Remove(oldrow);
                    }
                    RaisePropertyChanged(nameof(Total));
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };

                WarehouseClient.GetLookUpWarehouseForTransferFromCompleted += (s, e) => {
                    foreach (var row in e.Result)
                    {
                        var newrow = new TblWarehouse();
                        newrow.InjectFrom(row);
                        WarehouseListFrom.Add(newrow);
                    }
                    Loading = false;
                };
                WarehouseClient.GetLookUpWarehouseForTransferToCompleted += (s, e) => {
                    foreach (var row in e.Result)
                    {
                        var newrow = new TblWarehouse();
                        newrow.InjectFrom(row);
                        WarehouseListTo.Add(newrow);
                    }
                    Loading = false;
                };

                GetComboData();
                GetMaindata();
            }
        }
Example #30
0
 private void OnAddNew()
 {
     SaveCommand.Execute();
     //CommitCommand.Execute(null);
 }