Example #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="action"></param>
        /// <param name="externalParams"> </param>
        internal virtual void RunAction(ActionMetaItem action, List <object> externalParams)
        {
            WaitDialogType waitType;

            switch (action.ActionType)
            {
            //case ActionTypes.Create:
            //case ActionTypes.Edit:
            //case ActionTypes.View:
            //    waitType = WaitDialogType.FormLoading;
            //    break;
            default:
                waitType = WaitDialogType.None;
                break;
            }
            if (!m_ActionLocker.Lock(waitType))
            {
                return;
            }

            try
            {
                var needCancel = false;
                if (OnBeforeActionExecuting != null)
                {
                    /*
                     * IObject bo;
                     * if (BaseGridPanel != null && BaseGridPanel.FocusedItem != null)
                     *  bo = BaseGridPanel.FocusedItem;
                     * else
                     *  bo = BusinessObject;
                     */
                    OnBeforeActionExecuting(ParentLayout != null ? ParentLayout.ParentBasePanel : null
                                            , action
                                            , BusinessObject
                                            , ref needCancel);
                }
                if (needCancel)
                {
                    return;
                }

                //определим набор параметров, которые могут быть переданы от родительской панели
                //сначала получаем указатель на панель, которую обслуживает эта панель
                var parentBasePanel = ParentLayout != null ? ParentLayout.ParentBasePanel.ParentBasePanel : null;
                var parameters      = externalParams;
                if (parentBasePanel != null && externalParams == null)
                {
                    parameters = parentBasePanel.GetParamsAction(BusinessObject);
                }

                #region Выполнение действий

                var currentBo = BusinessObject;

                switch (action.ActionType)
                {
                case ActionTypes.Action:
                    // For Grid panels only we should pass Key of Selected Item  as parameter
                    using (var manager = CreateDbManagerProxy())
                    {
                        bool bSuccess;
                        if (externalParams != null)
                        {
                            bSuccess = action.RunAction(manager, BusinessObject, externalParams).result;
                        }
                        else if ((BaseGridPanel != null))
                        {
                            BaseGridPanel.RefreshFocusedItem();
                            currentBo = BaseGridPanel.FocusedItem;

                            var prs = CreatePanelGridParameters(BaseGridPanel);
                            prs.AddRange(action.Parameters);
                            bSuccess = action.RunAction(manager, currentBo, prs).result;
                        }
                        else
                        {
                            bSuccess = action.RunAction(manager, BusinessObject).result;
                        }
                        if (bSuccess)
                        {
                            if (action.IsNeedClose)
                            {
                                ActionCloseForm(action.Name == "OK" ? DialogResult.OK : DialogResult.Cancel);
                            }
                            if (!String.IsNullOrEmpty(action.RelatedLists))
                            {
                                var names = action.RelatedLists.Split(',');
                                foreach (var name in names)
                                {
                                    BaseFormManager.RefreshList(name);
                                }
                            }
                        }
                    }
                    break;

                case ActionTypes.Create:
                    if (BaseGridPanel != null)
                    {
                        BaseGridPanel.Edit(null, parameters, action.ActionType, false);
                        currentBo = BaseGridPanel.FocusedItem;
                    }
                    else if ((ParentLayout != null) && (ParentLayout.ParentBasePanel != null))
                    {
                        //TODO необходимо проверить этот код
                        var saveAction =
                            m_AllActions.SingleOrDefault(c => c.ActionType == ActionTypes.Save) ??
                            m_AllActions.SingleOrDefault(c => c.ActionType == ActionTypes.Ok);
                        if (saveAction != null)
                        {
                            if (ActionSave(saveAction, true))
                            {
                                using (var manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
                                {
                                    var bo = action.RunAction(manager, null as IObject, parameters).obj;
                                    if (bo != null)
                                    {
                                        currentBo = bo;
                                        ParentLayout.ParentBasePanel.BusinessObject = bo;
                                        ParentLayout.BusinessObject = bo;
                                        BusinessObject = bo;
                                    }
                                }
                            }
                        }
                    }
                    break;

                case ActionTypes.Ok:
                    //проверить наличие изменений + сохранить + закрыть форму
                    var success = true;
                    if (!BusinessObject.ReadOnly)
                    {
                        success = ActionSave(action, false);
                    }
                    if (success)
                    {
                        ActionCloseForm(DialogResult.OK);
                    }
                    break;

                case ActionTypes.Cancel:
                    //проверить наличие изменений + не сохранять + закрыть форму
                    if (ActionCanCancel())
                    {
                        ActionCloseForm();
                    }
                    break;

                case ActionTypes.Close:
                    //закрыть форму
                    var successClose = true;
                    if (BusinessObject != null)
                    {
                        using (var manager = CreateDbManagerProxy())
                        {
                            successClose = action.RunAction(manager, BusinessObject).result;
                        }
                    }
                    if (successClose)
                    {
                        ActionCloseForm();
                    }
                    break;

                case ActionTypes.Delete:
                    //применяется только для списочных форм
                    //проверить наличие активного элемента + сохранить + обновление
                    if ((BaseGridPanel != null) &&
                        (BaseGridPanel.FocusedItem != null) &&
                        (ParentLayout != null))
                    {
                        #region Для списочных форм

                        /*if (BaseGridPanel.FocusedItem.HasChanges && !BaseGridPanel.FocusedItem.IsNew)
                         * {
                         *  ErrorForm.ShowWarning("msgCantDelete", "Can't delete object");
                         * }
                         * else*/
                        if (WinUtils.ConfirmDelete())
                        {
                            BaseGridPanel.RefreshFocusedItem();
                            var itemsToDelete = BaseGridPanel.SelectedItems.Count > 0
                                                        ? BaseGridPanel.SelectedItems
                                                        : new List <IObject> {
                                BaseGridPanel.FocusedItem
                            };
                            currentBo = BaseGridPanel.FocusedItem;
                            try
                            {
                                var appForm = (parentBasePanel ?? ParentLayout.ParentBasePanel) as IApplicationForm;
                                if (
                                    BaseFormManager.FindFormByID(appForm, currentBo.Key) != null)
                                {
                                    ErrorForm.ShowWarning("msgCantDelete", "Can't delete object");
                                    break;
                                }

                                using (var manager = CreateDbManagerProxy())
                                {
                                    foreach (var item in itemsToDelete)
                                    {
                                        item.Validation += GridPanelItem_DeleteValidation;
                                        if (action.RunAction(manager, item).result)
                                        {
                                            if (!(BaseGridPanel is IChildListPanel))
                                            {
                                                BaseFormManager.RefreshList(BusinessObject.GetType().Name);
                                                //BaseGridPanel.Delete(item.Key);
                                            }
                                            else
                                            {
                                                BaseGridPanel.Grid.GridView.BeginDataUpdate();
                                                var filter =
                                                    BaseGridPanel.Grid.GridView.ActiveFilter.NonColumnFilter;
                                                BaseGridPanel.Grid.GridView.ActiveFilter.NonColumnFilter =
                                                    String.Empty;
                                                BaseGridPanel.Grid.GridView.ActiveFilter.NonColumnFilter = filter;
                                                BaseGridPanel.Grid.GridView.EndDataUpdate();
                                            }
                                            if (!string.IsNullOrEmpty(action.RelatedLists))
                                            {
                                                var names = action.RelatedLists.Split(',');
                                                foreach (var name in names)
                                                {
                                                    if (name != BusinessObject.GetType().Name)
                                                    {
                                                        BaseFormManager.RefreshList(name);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                foreach (var item in itemsToDelete)
                                {
                                    item.Validation -= GridPanelItem_DeleteValidation;
                                }
                            }
                        }

                        #endregion
                    }
                    else if
                    (
                        (ParentLayout is LayoutSimple) &&
                        (BusinessObject != null)
                    )
                    {
                        if (!BusinessObject.IsNew && BusinessObject.HasChanges)
                        {
                            ErrorForm.ShowWarning("msgCantDelete", "Can't delete object");
                        }
                        else if (WinUtils.ConfirmDelete())
                        {
                            currentBo = BusinessObject;
                            //if (
                            //    BaseFormManager.FindFormByID(ParentLayout.ParentBasePanel as IApplicationForm,
                            //                                 currentBo.Key) != null)
                            //{
                            //    ErrorForm.ShowWarning("msgCantDelete", "Can't delete object");
                            //    break;
                            //}

                            using (var manager = CreateDbManagerProxy())
                            {
                                if (action.RunAction(manager, BusinessObject).result)
                                {
                                    ActionCloseForm();
                                }
                            }
                        }
                    }

                    break;

                case ActionTypes.Refresh:

                    //применяется только для списочных форм
                    //получить данные из БД
                    if (BaseGridPanel != null)
                    {
                        BaseGridPanel.Refresh();
                    }
                    break;

                case ActionTypes.View:
                case ActionTypes.Edit:

                    //применяется только для списочных форм
                    //проверить наличие активного элемента + открыть форму редактирования (сохранения внутри неё) + обновить
                    if (BaseGridPanel != null)
                    {
                        var readOnly    = action.ActionType == ActionTypes.View || action.IsReadOnly(BusinessObject, Permissions);
                        var focusedItem = BaseGridPanel.FocusedItem;
                        if (BaseGridPanel.EnableMultiEdit && BaseGridPanel.SelectedItems.Count > 1)
                        {
                            var keys = BaseGridPanel.SelectedItems.Select(bo => bo.Key).ToList();
                            BaseGridPanel.Edit(keys, CreatePanelGridParameters(BaseGridPanel), action.ActionType, readOnly);
                        }
                        else if ((focusedItem != null) && (focusedItem.Key != null))
                        {
                            currentBo = focusedItem;
                            BaseGridPanel.Edit(focusedItem.Key, CreatePanelGridParameters(BaseGridPanel), action.ActionType, readOnly);
                        }
                    }
                    break;

                case ActionTypes.Save:
                    //проверить наличие изменений + сохранить
                    ActionSave(action, true);
                    break;

                case ActionTypes.Report:

                    if ((ParentLayout != null) && (ParentLayout.ParentBasePanel != null))
                    {
                        ParentLayout.ParentBasePanel.ShowReport();
                    }
                    break;

                case ActionTypes.Select:
                    if ((BaseGridPanel != null) && (BaseGridPanel.FocusedItem != null))
                    {
                        ActionCloseForm(DialogResult.OK);
                    }
                    break;

                case ActionTypes.SelectAll:
                    if (BaseGridPanel != null)
                    {
                        BaseGridPanel.SelectAll();
                        if (BaseGridPanel.SelectedItems != null && BaseGridPanel.SelectedItems.Count > 0)
                        {
                            ActionCloseForm(DialogResult.OK);
                        }
                    }
                    break;
                }

                #endregion

                if (OnLastExecutedActionChanged != null)
                {
                    OnLastExecutedActionChanged(action);
                }

                RaiseAfterActionExecuted(action, currentBo);
            }
            catch (PermissionException exc)
            {
                ErrorForm.ShowWarning("msgNoExecutePermission");
                Dbg.Debug("Permission exception for {0}.{1}, exeption:{2}", exc.ObjectName, exc.ActionName, exc);
            }
            catch (ParamsCountException exc)
            {
                ErrorForm.ShowError(StandardError.ParamsCountError, exc);
            }
            catch (DbModelTimeoutException)
            {
                ErrorForm.ShowWarning("msgTimeoutList", "Cannot retrieve records from database because of the timeout. Please change search criteria and try again");
            }
            catch (DbModelRaiserrorException ex2)
            {
                if (string.IsNullOrEmpty(ex2.MessageId))
                {
                    ErrorForm.ShowError(ex2.Message, ex2);
                }
                else
                {
                    var args = ex2.MessageId.Split(new[] { ' ' });
                    if (args.Count() > 1)
                    {
                        var pars = new object[args.Count() - 1];
                        for (int i = 1; i < args.Count(); i++)
                        {
                            pars[i - 1] = args[i];
                        }
                        ErrorForm.ShowError(args[0], args[0], pars);
                    }
                    else
                    {
                        ErrorForm.ShowError(ex2.MessageId, ex2.Message, ex2);
                    }
                }
            }
            catch (DbModelException ex1)
            {
                if (string.IsNullOrEmpty(ex1.MessageId))
                {
                    ErrorForm.ShowError(ex1.Message, ex1);
                }
                else
                {
                    ErrorForm.ShowError(ex1.MessageId, ex1.Message, ex1);
                }
            }
            catch (BvModelException exc)
            {
                ErrorForm.ShowError(StandardError.UnprocessedError, exc.InnerException ?? exc);
            }
            catch (Exception exc)
            {
                ErrorForm.ShowError(StandardError.UnprocessedError, exc);
            }
            finally
            {
                m_ActionLocker.Unlock();
            }
        }