示例#1
0
        /// <summary>
        /// Типовое действие "Сохранить"
        /// </summary>
        /// <param name="action"> </param>
        /// <param name="saveOnly">true-выполняется действие Save, false-выполняется действие OK</param>
        private bool ActionSave(ActionMetaItem action, bool saveOnly)
        {
            if (!BusinessObject.HasChanges)
            {
                return(true);
            }
            var form = FindForm();

            if (form != null)
            {
                form.BringToFront();
            }
            var canProceed = saveOnly ? WinUtils.ConfirmSave() : WinUtils.ConfirmOk();

            if (!canProceed)
            {
                return(false);
            }
            using (new WaitDialog(WaitDialogType.FormSaving))
            {
                using (var manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
                {
                    return(action.RunAction(manager, BusinessObject).result);
                }
            }
        }
示例#2
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();
            }
        }
示例#3
0
        /// <summary>
        /// </summary>
        /// <param name="key"></param>
        /// <param name="parameters"></param>
        /// <param name="actionType"></param>
        /// <param name="readOnly"></param>
        public override IApplicationForm Edit(object key, List <object> parameters, ActionTypes actionType, bool readOnly)
        {
            //TODO переписать метод более понятным
            IObject processedBusinessObject = null;
            var     meta = ObjectAccessor.MetaInterface(BusinessObject.GetType());

            if (key == null)
            {
                ActionMetaItem createAction = meta.Actions.Find(item => item.ActionType == ActionTypes.Create && item.PanelType == ActionsPanelType.Group);
                if (createAction == null)
                {
                    return(this);
                }

                using (var manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
                {
                    var ret = createAction.RunAction(manager, m_DataSourceParent, parameters);
                    if (ret.result)
                    {
                        processedBusinessObject = ret.obj;
                    }
                }
                if (processedBusinessObject != null)
                {
                    SetEnvironment(processedBusinessObject);
                    if (InlineMode == InlineMode.UseCreateButton)
                    {
                        DataSource.Add(processedBusinessObject);
                        for (var i = Grid.GridView.RowCount - 1; i >= 0; i--)
                        {
                            var row = Grid.GridView.GetRow(i);
                            if (row.Equals(processedBusinessObject))
                            {
                                Grid.GridView.FocusedRowHandle = i;
                            }
                        }
                    }
                }
            }
            else
            {
                if (InlineMode == InlineMode.None)
                {
                    ActionMetaItem editAction = meta.Actions.Find(
                        item => item.ActionType == actionType && item.PanelType == ActionsPanelType.Group);
                    if (editAction == null)
                    {
                        return(this);
                    }

                    using (var manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
                    {
                        processedBusinessObject = editAction.IsCreate
                            ? editAction.RunAction(manager, null as IObject, new List <object> {
                            key
                        }).obj
                                : FocusedItem;
                    }
                }
            }

            if ((InlineMode == InlineMode.None) && (processedBusinessObject != null))
            {
                using (var manager = CreateDbManagerProxy())
                {
                    var clone = processedBusinessObject.CloneWithSetup(manager);

                    #region В отдельном окне

                    //для нового элемента FocusedItem == null
                    var detailPanelName = GetDetailFormName(FocusedItem ?? BusinessObject);
                    if (Utils.IsEmpty(detailPanelName))
                    {
                        ErrorForm.ShowMessage("msgNoDetails", "msgNoDetails");
                        return(this);
                    }
                    var detailPanel = ClassLoader.LoadClass(detailPanelName);
                    Dbg.Assert(detailPanel != null, "class {0} can't be loaded", detailPanelName);
                    Dbg.Assert(detailPanel is IApplicationForm,
                               "detail form  {0} doesn't implement IApplicationFrom interface",
                               detailPanelName);
                    if (detailPanel is IBasePanel)
                    {
                        var appForm = detailPanel as IApplicationForm;
                        if (readOnly)
                        {
                            clone.ReadOnly = true;
                            (detailPanel as IBasePanel).ReadOnly = true;
                        }

                        /*
                         * var layout = GetLayout() as LayoutEmpty;
                         * if (layout != null)
                         * {
                         *  var cancel = false;
                         *  layout.OnBeforeActionExecutingRaised(this, createAction ?? editAction, clone, ref cancel);
                         *  if (cancel) return this;
                         * }
                         */
                        BaseFormManager.ShowModal(appForm, clone);
                        SetEnvironment(clone);
                        //определяем действие, по которому закрылась форма
                        if (appForm != null)
                        {
                            //если Ok, то заменяем клоном исходный объект
                            LastExecutedActionInternal = appForm.GetLastExecutedAction();
                            if (LastExecutedActionInternal != null)
                            {
                                if (LastExecutedActionInternal.ActionType.Equals(ActionTypes.Ok) ||
                                    LastExecutedActionInternal.ActionType.Equals(ActionTypes.Close) ||
                                    (LastExecutedActionInternal.ActionType.Equals(ActionTypes.Action) && LastExecutedActionInternal.IsNeedClose)
                                    )
                                {
                                    var index = DataSource.IndexOf(processedBusinessObject);
                                    if (index < 0)
                                    {
                                        clone.DeepSetChange();
                                        DataSource.Add(clone);
                                    }
                                    else
                                    {
                                        DataSource.ReplaceAndSetChange(processedBusinessObject as T, clone as T);
                                    }
                                    SetObjects(clone);

                                    Refresh();
                                }
                                else
                                {
                                    //видимо, происходит отмена. Надо дать возможность удалить временные объекты.
                                    DeleteTempObjects(processedBusinessObject);
                                }
                            }
                            else
                            {
                                //видимо, происходит отмена. Надо дать возможность удалить временные объекты.
                                DeleteTempObjects(processedBusinessObject);
                            }
                        }
                    }

                    #endregion
                }
            }
            return(this);
        }