Exemplo n.º 1
0
        private void SetPrivilege(string privilegeCode)
        {
            int  anketaAccess = OperatorOrg.GetAnketaDataAccesseCode(privilegeCode);
            bool readOnly     = (anketaAccess == 1);

            if (readOnly)
            {
                addStripButton.Enabled     = !readOnly;
                editStripButton.Enabled    = !readOnly;
                delStripButton.Enabled     = !readOnly;
                dismissStripButton.Enabled = !readOnly;
                restoreStripButton.Enabled = !readOnly;
                attachToOrgButton.Enabled  = !readOnly;

                addStripButton.ToolTipText     = "У вас недостаточно прав. Обратитесь к администратору";
                editStripButton.ToolTipText    = "У вас недостаточно прав. Обратитесь к администратору";
                delStripButton.ToolTipText     = "У вас недостаточно прав. Обратитесь к администратору";
                dismissStripButton.ToolTipText = "У вас недостаточно прав. Обратитесь к администратору";
                restoreStripButton.ToolTipText = "У вас недостаточно прав. Обратитесь к администратору";

                ToolTip toolTip1 = new ToolTip();
                toolTip1.SetToolTip(attachToOrgButton, "У вас недостаточно прав. Обратитесь к администратору");

                personView.CellDoubleClick -= personView_CellDoubleClick;
            }

            int anketaPrint = OperatorOrg.GetAnketaPrintAccesseCode(privilegeCode);

            printStripDropDownButton.Enabled = (anketaPrint > 0);
            if (anketaPrint == 0)
            {
                printStripDropDownButton.ToolTipText = "У вас недостаточно прав. Обратитесь к администратору";
            }
        }
Exemplo n.º 2
0
        private void mergeView_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    ContextMenuStrip menu = cmsSvod;
                    if (menu == null)
                    {
                        return;
                    }

                    DataGridView    dataView = sender as DataGridView;
                    ToolStripItem[] items; //Массив в который возвращает элементы метод Find
                    List <string>   menuItems = new List <string>
                    {
                        "editSvodMenuItem",
                        "delSvodMenuItem",
                        "printSvodMenuItem"
                    }; //Список элементов которые нужно включать\выключать

                    int  currentMouseOverRow = dataView.HitTest(e.X, e.Y).RowIndex;
                    bool isEnabled           = !(currentMouseOverRow < 0);
                    foreach (string t in menuItems)
                    {
                        items = menu.Items.Find(t, false);
                        if (items.Any())
                        {
                            items[0].Enabled = isEnabled;
                        }
                    }

                    menuItems = new List <string>(); //Список элементов которые нужно принудительно выключать

                    // Проверка прав и отключение пунктов
                    bool readOnly = OperatorOrg.GetStajDohodDataAccesseCode(_privilege) == 1;
                    if (readOnly)
                    {
                        menuItems.Add("addSvodMenuItem");
                        menuItems.Add("editSvodMenuItem");
                        menuItems.Add("delSvodMenuItem");
                    }

                    foreach (string t in menuItems)
                    {
                        items = menu.Items.Find(t, false);
                        if (items.Any())
                        {
                            items[0].Enabled = false;
                        }
                    }

                    menu.Show(dataView, e.Location);
                }
            }
            catch (Exception ex)
            {
                MainForm.ShowErrorFlexMessage(ex.Message, "Непредвиденная ошибка");
            }
        }
Exemplo n.º 3
0
        private void SetPrivilege(string privilegeCode)
        {
            bool readOnly = OperatorOrg.GetStajDohodDataAccesseCode(privilegeCode) == 1;

            if (readOnly)
            {
                addStripButton.Enabled  = false;
                editStripButton.Enabled = false;
                delStripButton.Enabled  = false;

                mergeView.CellDoubleClick -= mergeView_CellDoubleClick;

                addStripButton.ToolTipText  = "У вас недостаточно прав. Обратитесь к администратору";
                editStripButton.ToolTipText = "У вас недостаточно прав. Обратитесь к администратору";
                delStripButton.ToolTipText  = "У вас недостаточно прав. Обратитесь к администратору";
            }
        }
Exemplo n.º 4
0
        private void AnketadataForm_Load(object sender, EventArgs e)
        {
            Text += " - " + _org.regnumVal;

            // получить код привилегии (уровня доступа) Оператора к Организации
            if (_operator.IsAdmin())
            {
                _privilege = OperatorOrg.GetPrivilegeForAdmin();
            }
            else
            {
                _privilege = OperatorOrg.GetPrivilege(_operator.idVal, _org.idVal, _connection);
            }

            // иництализация таблицы персон (записи с анкетными данными)
            _personTable = PersonView.CreatetTable();
            // добавление виртуального столбца для возможности отмечать записи
            _personTable.Columns.Add(Check, typeof(bool));
            _personTable.Columns[Check].DefaultValue = false;

            // инициализация биндинг сорса к таблице персон
            _personBS = new BindingSource();
            _personBS.CurrentChanged += new EventHandler(_personBS_CurrentChanged);
            _personBS.ListChanged    += new ListChangedEventHandler(_personBS_ListChanged);
            _personBS.DataSource      = _personTable;
            // присвоение источника вьюшке
            personView.AutoGenerateColumns = false;
            personView.DataSource          = _personBS;
            // инициализация Адаптера для считывания персон из БД
            string commandStr = PersonView.GetSelectText(_org.idVal);

            _personAdapter = new SQLiteDataAdapter(commandStr, _connection);
            // запосление таблицы данными с БД
            _personAdapter.Fill(_personTable);

            workButton.Enabled = false;
            // отобразить работающих персон
            stateButton_Click(workButton, null);

            // отобразить привилегию на форме для пользователя
            SetPrivilege(_privilege);
        }
Exemplo n.º 5
0
        private void SvodVedomostForm_Load(object sender, EventArgs e)
        {
            Text += " - " + _org.regnumVal;

            // получить код привилегии (уровня доступа) Оператора к Организации
            if (_operator.IsAdmin())
            {
                _privilege = OperatorOrg.GetPrivilegeForAdmin();
            }
            else
            {
                _privilege = OperatorOrg.GetPrivilege(_operator.idVal, _org.idVal, _connection);
            }

            yearBox.Value = MainForm.RepYear;
            RefillData(MainForm.RepYear);
            mergeView.Sorted        += new EventHandler(mergeView_Sorted);
            _mergeBS.CurrentChanged += new EventHandler(_mergeBS_CurrentChanged);
            _mergeBS.MoveLast();

            SetPrivilege(_privilege);
        }
Exemplo n.º 6
0
        private void SetPrivilege()
        {
            DataRowView orgRow  = _orgBS.Current as DataRowView;
            bool        isAdmin = (_operator.candeleteVal == 0);

            adminMenu.Enabled = isAdmin;
            if (orgRow == null)
            {
                anketadataMenuItem.Enabled   = false;
                stajidohodMenuItem.Enabled   = false;
                svodvedomostMenuItem.Enabled = false;
                poiskfizlicaMenuItem.Enabled = false;
                elobmenMenuItem.Enabled      = false;
            }
            else
            {
                string code = OperatorOrg.GetPrivilege(_operator.idVal, (long)orgRow[Org.id], _mainConnection);
                anketadataMenuItem.Enabled   = isAdmin || int.Parse(code[0].ToString()) > 0;
                stajidohodMenuItem.Enabled   = isAdmin || int.Parse(code[2].ToString()) > 0;
                svodvedomostMenuItem.Enabled = isAdmin || int.Parse(code[2].ToString()) > 0;
                poiskfizlicaMenuItem.Enabled = isAdmin || int.Parse(code[0].ToString()) > 0;
                elobmenMenuItem.Enabled      = isAdmin || int.Parse(code[4].ToString()) > 0;
            }
        }
Exemplo n.º 7
0
        private void personView_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Apps || (e.Shift && e.KeyCode == Keys.F10))
                {
                    DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
                    if (currentCell == null)
                    {
                        return;
                    }
                    ContextMenuStrip cms = cmsPerson;
                    if (cms == null)
                    {
                        return;
                    }
                    Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex,
                                                                                   currentCell.RowIndex, false);
                    Point p = new Point(r.Left, r.Top);

                    ToolStripItem[] items;                           //Массив в который возвращает элементы метод Find
                    List <string>   menuItems = new List <string>(); //Список элементов которые нужно включать\выключать
                    menuItems = new List <string>();                 //Список элементов которые нужно принудительно выключать
                    if (restoreStripButton.Enabled)
                    {
                        menuItems.Add("dismissPersonMenuItem");
                    }
                    else
                    {
                        menuItems.Add("restorePersonMenuItem");
                    }

                    // Проверка прав и отключение пунктов
                    int  anketaAccess = OperatorOrg.GetAnketaDataAccesseCode(_privilege);
                    bool readOnly     = (anketaAccess == 1);
                    if (readOnly)
                    {
                        menuItems.Add("addPersonMenuItem");
                        menuItems.Add("editPersonMenuItem");
                        menuItems.Add("delpersonMenuItem");
                        menuItems.Add("dismissPersonMenuItem");
                        menuItems.Add("restorePersonMenuItem");
                    }
                    int anketaPrint = OperatorOrg.GetAnketaPrintAccesseCode(_privilege);
                    if (anketaPrint == 0)
                    {
                        menuItems.Add("printAnketsMenuItem");
                        menuItems.Add("printUnregisteredMenuItem");
                    }

                    foreach (string t in menuItems)
                    {
                        items = cms.Items.Find(t, true);
                        if (items.Any())
                        {
                            items[0].Enabled = false;
                        }
                    }

                    cms.Show((sender as DataGridView), p);
                }

                if (e.KeyCode == Keys.Delete)
                {
                    int  anketaAccess = OperatorOrg.GetAnketaDataAccesseCode(_privilege);
                    bool readOnly     = (anketaAccess == 1);
                    if (readOnly)
                    {
                        MainForm.ShowInfoMessage("У вас недостаточно прав. Обратитесь к администратору.", "Внимание");
                        return;
                    }
                    delStripButton_Click(sender, e);
                }

                if (e.KeyCode == Keys.Enter)
                {
                    int  anketaAccess = OperatorOrg.GetAnketaDataAccesseCode(_privilege);
                    bool readOnly     = (anketaAccess == 1);
                    if (readOnly)
                    {
                        MainForm.ShowInfoMessage("У вас недостаточно прав. Обратитесь к администратору.", "Внимание");
                        return;
                    }
                    editStripButton_Click(sender, e);
                }

                if (e.KeyCode == Keys.Space)
                {
                    if ((sender as DataGridView).CurrentRow == null)
                    {
                        return;
                    }

                    (_personBS.Current as DataRowView)[Check] =
                        !Convert.ToBoolean((_personBS.Current as DataRowView)[Check]);
                    (sender as DataGridView).EndEdit();
                    (sender as DataGridView).Refresh();
                }
            }
            catch (Exception ex)
            {
                MainForm.ShowErrorFlexMessage(ex.Message, "Непредвиденная ошибка");
            }
        }
Exemplo n.º 8
0
        private void saveButton_Click(object sender, EventArgs e)
        {
            OperOrgRowCurrentEndEdit();
            // создание адаптера для записей операторов
            SQLiteDataAdapter adapter = Operator.CreateAdapter(_connectionStr);

            SQLiteCommand    command    = adapter.InsertCommand;
            SQLiteConnection connection = command.Connection;

            // обработать все записи операторов на вставку и пометить как обработанные
            foreach (DataRowView operRow in _operatorBS)
            {
                // если запись новая, то добавить ее в БД
                if (operRow.Row.RowState == DataRowState.Added)
                {
                    // открыть соединение
                    connection.Open();
                    // ввод параметров для команды
                    command.Parameters[Operator.pName].Value     = operRow[Operator.name];
                    command.Parameters[Operator.pPassword].Value = operRow[Operator.password];
                    // выполнение запроса на исполнение и получение ID записи
                    object rowId = adapter.InsertCommand.ExecuteScalar();
                    // закрыть соединение
                    connection.Close();

                    // присвоить полоученный ID всем привелегиям с всталяемым оператором и самому оператору
                    long idVal = (long)rowId;
                    ChangeOperatorId(idVal, operRow, _operOrgBS);
                    operRow.Row.AcceptChanges();
                }
            }
            // отправить оставшиеся записи операторов на обработку в Адаптер
            adapter.Update(_operatorTable);

            // получить ссылку на текущую запись с привелегией
            DataRowView operOrgRow = _operOrgBS.Current as DataRowView;

            // если ссылка не пуста, то записать привелегию, считав ее сформы, и преобразовав в код
            if (operOrgRow != null)
            {
                // считывание и получение кода
                string codeStr = GetPrivilegeCode();
                // запись кода
                operOrgRow[OperatorOrg.code] = codeStr;
                operOrgRow.EndEdit();
            }

            // запомнить значение фильтра
            string filter = _operOrgBS.Filter;
            // запомнить позицию активной записи
            int pos = _operOrgBS.Position;

            // снять фильтр
            _operOrgBS.RemoveFilter();
            // создание соединения
            connection = new SQLiteConnection(_connectionStr);
            // создание команды для вставки записи с привелегией в БД
            command            = OperatorOrg.CreateInsertCommand();
            command.Connection = connection;
            // вставить в БД все новые записи с привелегиями
            foreach (DataRowView itemRow in _operOrgBS)
            {
                // если строка не помечена как удаленная
                if (itemRow.Row.RowState != DataRowState.Deleted)
                {
                    // если строка с привелегией содержит "пустой" код привелегии, то пометить ее как удаленную
                    if ((itemRow[OperatorOrg.code] as string).Replace("0", "").Length <= 0 || !(bool)itemRow[Check])
                    {
                        itemRow.Row.Delete();
                    }
                    else
                    {
                        // если строка новая, то произвести ее вставку в БД
                        if (itemRow.Row.RowState == DataRowState.Added && (bool)itemRow[Check])
                        {
                            // открыть соединение
                            connection.Open();
                            // вставить значения параметров запроса
                            command.Parameters[OperatorOrg.pOperatorID].Value = itemRow[OperatorOrg.operatorID];
                            command.Parameters[OperatorOrg.pOrgID].Value      = itemRow[OperatorOrg.orgID];
                            command.Parameters[OperatorOrg.pCode].Value       = itemRow[OperatorOrg.code];
                            // выполнить запрос и получить значение ID записи
                            object rowID = command.ExecuteScalar();
                            // закрыть соединение
                            connection.Close();
                            // записать полученный ID в запись (синхронизация с БД)
                            long idVal = (long)rowID;
                            itemRow[OperatorOrg.id] = idVal;
                            itemRow.EndEdit();
                            itemRow.Row.AcceptChanges();
                        }
                    }
                }
            }
            // обновить данные (изменение, удаление) в БД для записей привелегий
            _operatororgAdapter.Update(_operOrgTable);
            // восстановить фильтр
            _operOrgBS.Filter = filter;
            // восстановить позицию
            _operOrgBS.Position = pos;

            MainForm.ShowInfoMessage("Данные успешно сохранены", "Сохранение");
            DialogResult = DialogResult.OK;
        }
Exemplo n.º 9
0
        public OperatorsForm(string connection)
        {
            InitializeComponent();
            _connectionStr = connection;

            _adminCode = OperatorOrg.GetPrivilegeForAdmin(); //"212111";
            _emptyCode = new string('0', CodeLength);

            // создание объектов таблиц
            _operatorTable = Operator.CreateTable();

            _orgTable = Org.CreateTable();
            // добавление виртуального столбца, для возможности отмечать
            _orgTable.Columns.Add(Check, typeof(bool));
            _orgTable.Columns[Check].DefaultValue = false;

            _operOrgTable = OperatorOrg.CreateTable();
            // добавление виртуального столбца, для возможности отмечать
            _operOrgTable.Columns.Add(Check, typeof(bool));
            _operOrgTable.Columns[Check].DefaultValue = false;

            // создание виртуальной таблицы для хранения уровня
            _accessTable = new DataTable();
            // добавление необходимых столбцов
            _accessTable.Columns.Add(ANumber, typeof(int));
            _accessTable.Columns.Add(AName, typeof(string));
            // заполнение данными виртуальной таблицы привелегий
            DataRow row;

            //row = _accessTable.NewRow();
            //row[aNumber] = 0;
            //row[aName] = "Без доступа";
            //row.EndEdit();
            //_accessTable.Rows.Add(row);

            row          = _accessTable.NewRow();
            row[ANumber] = 1;
            row[AName]   = "Только чтение";
            row.EndEdit();
            _accessTable.Rows.Add(row);

            row          = _accessTable.NewRow();
            row[ANumber] = 2;
            row[AName]   = "Полный доступ";
            row.EndEdit();
            _accessTable.Rows.Add(row);

            _accessTable.AcceptChanges();

            // создание объектов контроллеров
            _operatorBS      = new BindingSource();
            _orgBS           = new BindingSource();
            _operOrgBS       = new BindingSource();
            _anketaAccessBS  = new BindingSource();
            _paystajAccessBS = new BindingSource();

            // инициализация адаптеров для выполнения запросов нахаполнения таблиц
            _operatorAdapter    = Operator.CreateAdapter(_connectionStr);
            _orgAdapter         = Org.CreateAdapter(_connectionStr);
            _operatororgAdapter = OperatorOrg.CreateAdapter(_connectionStr);

            // привязка таблиц к контроллерам (биндинг сорсам)
            _operatorBS.DataSource      = _operatorTable;
            _orgBS.DataSource           = _orgTable;
            _operOrgBS.DataSource       = _operOrgTable;
            _anketaAccessBS.DataSource  = new DataView(_accessTable);
            _paystajAccessBS.DataSource = new DataView(_accessTable);
        }
Exemplo n.º 10
0
        private void mergeView_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Apps || (e.Shift && e.KeyCode == Keys.F10))
                {
                    DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
                    if (currentCell == null)
                    {
                        return;
                    }
                    ContextMenuStrip cms = cmsSvod;
                    if (cms == null)
                    {
                        return;
                    }
                    Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex,
                                                                                   currentCell.RowIndex, false);
                    Point p = new Point(r.Left, r.Top);

                    DataGridView    dataView = sender as DataGridView;
                    ToolStripItem[] items; //Массив в который возвращает элементы метод Find
                    List <string>   menuItems = new List <string>
                    {
                        "editSvodMenuItem",
                        "delSvodMenuItem",
                        "printSvodMenuItem"
                    }; //Список элементов которые нужно включать\выключать

                    int  currentMouseOverRow = dataView.CurrentCell.RowIndex;
                    bool isEnabled           = !(currentMouseOverRow < 0);
                    foreach (string t in menuItems)
                    {
                        items = cms.Items.Find(t, false);
                        if (items.Any())
                        {
                            items[0].Enabled = isEnabled;
                        }
                    }

                    menuItems = new List <string>(); //Список элементов которые нужно принудительно выключать

                    // Проверка прав и отключение пунктов
                    bool readOnly = OperatorOrg.GetStajDohodDataAccesseCode(_privilege) == 1;
                    if (readOnly)
                    {
                        menuItems.Add("addSvodMenuItem");
                        menuItems.Add("editSvodMenuItem");
                        menuItems.Add("delSvodMenuItem");
                    }

                    foreach (string t in menuItems)
                    {
                        items = cms.Items.Find(t, false);
                        if (items.Any())
                        {
                            items[0].Enabled = false;
                        }
                    }

                    cms.Show((sender as DataGridView), p);
                }

                if (e.KeyCode == Keys.Delete)
                {
                    bool readOnly = OperatorOrg.GetStajDohodDataAccesseCode(_privilege) == 1;
                    if (readOnly)
                    {
                        MainForm.ShowInfoMessage("У вас недостаточно прав. Обратитесь к администратору.", "Внимание");
                        return;
                    }
                    delStripButton_Click(sender, e);
                }

                if (e.KeyCode == Keys.Enter)
                {
                    bool readOnly = OperatorOrg.GetStajDohodDataAccesseCode(_privilege) == 1;
                    if (readOnly)
                    {
                        MainForm.ShowInfoMessage("У вас недостаточно прав. Обратитесь к администратору.", "Внимание");
                        return;
                    }
                    editSvodMenuItem_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                MainForm.ShowErrorFlexMessage(ex.Message, "Непредвиденная ошибка");
            }
        }