Example #1
0
    public string UpdatePosition(string titleId, string title)
    {
        if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(titleId))
        {
            //logger.Info(string.Format(base.LogEmptyInfo, "Title, TitleId"));
            return(string.Format(LogEmptyInfo, "Title, TitleId"));
        }

        CardData    refStaffData    = Session.CardManager.GetDictionaryData(RefStaff.ID);
        SectionData positionSection = refStaffData.Sections[RefStaff.Positions.ID];

        //im RowData position = GetExistObject(RefStaff.Positions.ID, RefStaff.Positions.Name, title);
        RowDataCollection positionColl = GetExistObject(RefStaff.Positions.ID, RefStaff.Positions.Name, title);
        RowData           position     = positionColl[0];

        if (position == null)
        {
            return(AddPosition(titleId, title));
        }

        refStaffData.BeginUpdate();
        //position[RefStaff.Positions.Name] = title;
        position[RefStaff.Positions.SyncTag] = titleId;
        refStaffData.EndUpdate();

        return("Должность обновлена");
    }
Example #2
0
        /// <summary>
        /// получает запись доп. изделия в универсальном справочнике.
        /// </summary>
        /// <param name="GotNumber">Заводской номер.</param>
        /// <param name="Device">Наименование изделия.</param>
        public RowData GetDeviceRow(String GotNumber, String Device)
        {
            String Number = null, Year = null;

            if (GotNumber.Contains("/"))
            {
                Year   = GotNumber.Split('/')[1];
                Number = GotNumber.Split('/')[0];
            }
            else
            {
                Number = GotNumber;
            }

            SectionData Items = ApplicationCard.UniversalCard.Sections[RefUniversal.Item.ID];

            SectionQuery Query = Card.CardScript.Session.CreateSectionQuery();

            Query.ConditionGroup.Operation = ConditionGroupOperation.And;
            Query.ConditionGroup.Conditions.AddNew("Name", FieldType.Unistring, ConditionOperation.Contains, String.Format("{0} № {1}/{2}", Device, Number, Year));

            RowDataCollection Found = Items.FindRows(Query.GetXml());

            return(Found.Count == 1 ? Found[0] : null);
        }
Example #3
0
    private void UpdateEmployeeManager(RowData employeeDocsvision, CardData refStaffData, string employeeChief)
    {
        if (employeeChief == null)
        {
            // logger.Info("Руководитель сотрудника не найден.");
            return;
        }

        SectionQuery sectionQueryEmployee = Session.CreateSectionQuery();

        sectionQueryEmployee.ConditionGroup.Conditions.AddNew(RefStaff.Employees.IDCode, FieldType.Unistring,
                                                              ConditionOperation.Equals, employeeChief);

        RowDataCollection employeeCollection = refStaffData.Sections[RefStaff.Employees.ID].FindRows(sectionQueryEmployee.GetXml());

        if (employeeCollection != null && employeeCollection.Count > 0)
        {
            employeeDocsvision[RefStaff.Units.Manager] = employeeCollection[0].Id;
            //logger.Info("Руководитель сотрудника обновлен.");
        }

        /*else
        *  {
        *   logger.Info("Руководитель сотрудника не найден.");
        *
        *  }   */
    }
        private static RowData SearchItemInReference(UserSession Session, CardData reference, Guid sectionId,
                                                     string fieldName, string fieldValue, FieldType fieldType = FieldType.Unistring,
                                                     ConditionOperation operation = ConditionOperation.Equals)
        {
            RowDataCollection rdc = reference.Sections[sectionId]
                                    .FindRows(GetSectionSearchQuery(Session, fieldName, fieldValue, fieldType, operation));

            return(rdc.Count != 0 ? rdc[0] : null);
        }
Example #5
0
    private bool SearchEmployeeTest(CardData refStaffData, string code)
    {
        SectionQuery sectionQueryTest = Session.CreateSectionQuery();

        sectionQueryTest.ConditionGroup.Conditions.AddNew(RefStaff.Employees.IDCode, FieldType.Unistring,
                                                          ConditionOperation.Equals, code);

        RowDataCollection employeeCollection = refStaffData.Sections[RefStaff.Employees.ID].FindRows(sectionQueryTest.GetXml());

        return(employeeCollection.Count > 0);
    }
Example #6
0
    public RowData CreateEmployee(RowData department)
    {
        if (department == null)
        {
            return(null);
        }

        RowDataCollection employeeRows = department.ChildSections[RefStaff.Employees.ID].Rows;

        return(employeeRows.AddNew());
    }
Example #7
0
        /// <summary>
        /// Получение перечня ремонтных работ.
        /// </summary>
        public ArrayList GetRepairWorks()
        {
            ArrayList RepairWorksList = new ArrayList();

            // Если прибор гарантийный и гарантия не аннулирована, не включаем ремонтные работы в калькуляцию
            if ((this.WarrantyRepair) && (!this.VoidWarranty))
            {
                return(RepairWorksList);
            }

            // Если клиент отказался от ремонта, то не включаем ремонтные работы в калькуляцию
            //if (this.RefusalToRepair)
            //{ return RepairWorksList; }

            CardData    SCard       = Card.CardScript.Session.CardManager.GetCardData(new Guid(this.ServiceCardID));
            SectionData RepairWorks = SCard.Sections[RefServiceCard.RepairWorks.ID.ToGuid()];

            if ((RepairWorks != null) && (RepairWorks.Rows.Count > 0))
            {
                RowDataCollection RowDescriptions = SCard.Sections[RefServiceCard.DescriptionOfFault.ID.ToGuid()].Rows;
                foreach (RowData Row in RepairWorks.Rows)
                {
                    if (Row.GetString(RefServiceCard.RepairWorks.NegotiationResult) != "Не выполнять")
                    {
                        RowData Description = null;
                        foreach (RowData RowDescription in RowDescriptions)
                        {
                            if (RowDescription.GetGuid(RefServiceCard.DescriptionOfFault.Id) == Row.GetGuid(RefServiceCard.RepairWorks.ParentTableRowId))
                            {
                                Description = RowDescription;
                            }
                        }

                        string BlockName           = Description.GetString(RefServiceCard.DescriptionOfFault.BlockOfDevice);
                        string BlockNameID         = Description.GetString(RefServiceCard.DescriptionOfFault.BlockOfDeviceID);
                        string WorksType           = Row.GetString(RefServiceCard.RepairWorks.WorksType);
                        string WorksTypeID         = Row.GetString(RefServiceCard.RepairWorks.WorksTypeID);
                        int    Amount              = this.DoubleCost == true ? (int)Row.GetDecimal(RefServiceCard.RepairWorks.Amount) * 2 : (int)Row.GetDecimal(RefServiceCard.RepairWorks.Amount);
                        bool   Improvement         = (bool)Row.GetBoolean(RefServiceCard.RepairWorks.Revision);
                        bool   VoidWarranty        = this.VoidWarranty;
                        bool   DoubleCost          = this.DoubleCost;
                        string DescriptionOfReason = this.DescriptionOfReason;
                        bool   RefusalToRepair     = this.RefusalToRepair;


                        CalculationItem NewItem = new CalculationItem(Card, DeviceName, DeviceItemID, BlockName, BlockNameID, WorksType, WorksTypeID, Improvement, Amount, true, VoidWarranty, DoubleCost,
                                                                      DescriptionOfReason, RefusalToRepair);
                        RepairWorksList.Add(NewItem);
                    }
                }
            }
            return(RepairWorksList);
        }
Example #8
0
 public void UpdateDepartmentCurator(RowData departmentDocsvision, CardData refStaffData, string curator)
 {
     if (curator != null)
     {
         //im RowData employee = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.IDCode, curator);
         RowDataCollection employeeColl = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.IDCode, curator);
         RowData           employee     = employeeColl[0];
         if (employee != null)
         {
             departmentDocsvision[RefStaff.Units.ContactPerson] = employee.Id;
         }
     }
 }
Example #9
0
        /// <summary>
        ///  Добавление ремонтной работы/доработки.
        /// </summary>
        /// <param name="sender"> sender.</param>
        /// <param name="e"> e.</param>
        private void AddButton_Click(object sender, EventArgs e)
        {
            bool          Improvement;
            object        activateParam = new object[] { "{DD20BF9B-90F8-4D9A-9553-5B5F17AD724E}", "", "{43A6DA44-899C-47D8-9567-2185E05D8524}", null, null, true };
            VbaCollection result        = (VbaCollection)Card.CardScript.CardFrame.CardHost.SelectFromCard(new Guid("{B2A438B7-8BB3-4B13-AF6E-F2F8996E148B}"), "Выберите вид ремонтных работ или доработку", activateParam);

            if (result != null)
            {
                foreach (object r in result)
                {
                    // Проверка выбранной записи
                    bool              Verify       = true;
                    RowData           WorkRow      = UniversalCard.GetItemRow(r.ToGuid());
                    int               WorksType    = (int)WorkRow.ChildSections[RefUniversal.Properties.ID].FindRow("@Name = 'Тип работ'").GetInt32(RefUniversal.Properties.Value);
                    RowDataCollection WorksDevices = WorkRow.ChildSections[RefUniversal.Properties.ID].FindRow("@Name = 'Приборы'").ChildSections[RefUniversal.SelectedValues.ID].Rows;
                    if (WorksType == 3)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("Позиция '" + WorkRow.GetString(RefUniversal.Item.Name) + "' не является ремонтной работой или доработкой. Она не будет добавлена в перечень ремонтных работ.");
                        Verify = false;
                    }

                    if (!WorksDevices.Any(row => row.GetString(RefUniversal.SelectedValues.SelectedValue).ToGuid().Equals(DeviceType.ToGuid())))
                    {
                        string DeviceTypeName = UniversalCard.GetItemName(new Guid(DeviceType));
                        DevExpress.XtraEditors.XtraMessageBox.Show("Позиция '" + WorkRow.GetString(RefUniversal.Item.Name) + "' не относится к прибору " + DeviceTypeName + ". Она не будет добавлена в перечень ремонтных работ.");
                        Verify = false;
                    }

                    if (Verify)
                    {
                        // Добавление выбранной записи
                        Improvement = WorksType == 2 ? true : false;
                        object[] Parametr = new object[9];
                        Parametr[0] = UniversalCard.GetItemName(r.ToGuid());
                        Parametr[1] = r.ToString();
                        Parametr[2] = 1;
                        Parametr[3] = Improvement;
                        Parametr[4] = Card.Context.GetCurrentEmployee().DisplayName;
                        Parametr[5] = Card.Context.GetObjectRef(Card.Context.GetCurrentEmployee()).Id.ToString();
                        Parametr[6] = 0;
                        Parametr[7] = null;
                        Parametr[8] = Work.NegotiationResult.NotAgreed.GetDescription();
                        DataRow NewRow = Table.Rows.Add(Parametr);
                    }
                }
            }
        }
Example #10
0
    //im private RowData GetExistObject(Guid mode, string alias, string value)
    private RowDataCollection GetExistObject(Guid mode, string alias, string value)
    {
        if (string.IsNullOrEmpty(alias) || string.IsNullOrEmpty(value) || mode == null || mode == Guid.Empty)
        {
            return(null);
        }
        try
        {
            CardData    refStaffData = Session.CardManager.GetDictionaryData(RefStaff.ID);
            SectionData unitsSection = null;

            if (mode == RefStaff.Employees.ID)
            {
                unitsSection = refStaffData.Sections[RefStaff.Employees.ID];
            }
            else if (mode == RefStaff.Units.ID)
            {
                unitsSection = refStaffData.Sections[RefStaff.Units.ID];
            }
            else if (mode == RefStaff.Positions.ID)
            {
                unitsSection = refStaffData.Sections[RefStaff.Positions.ID];
            }

            if (unitsSection == null)
            {
                return(null);
            }

            SectionQuery sectionQuery = Session.CreateSectionQuery();
            sectionQuery.ConditionGroup.Conditions.AddNew(alias, FieldType.Unistring, ConditionOperation.Equals, value);

            RowDataCollection employeeCollection = unitsSection.FindRows(sectionQuery.GetXml());
            if (employeeCollection != null && employeeCollection.Count > 0)
            {
                //im return employeeCollection[0];
                return(employeeCollection);
            }
        }
        catch (Exception ex)
        {
            return(null);
        }

        return(null);
    }
Example #11
0
        /// <summary>
        ///  Выбор вида ремонтных работ и доработок.
        /// </summary>
        /// <param name="sender"> sender.</param>
        /// <param name="e"> e.</param>
        private void repositoryItemButtonEdit1_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int[]  index = gridView1.GetSelectedRows();
            bool   Improvement;
            string WorksTypeID   = gridView1.GetRowCellDisplayText(index[0], "TWID").ToString();
            object activateParam = new string[] { "{DD20BF9B-90F8-4D9A-9553-5B5F17AD724E}", WorksTypeID, "{43A6DA44-899C-47D8-9567-2185E05D8524}" };
            object result        = Card.CardScript.CardFrame.CardHost.SelectFromCard(new Guid("{B2A438B7-8BB3-4B13-AF6E-F2F8996E148B}"), "Выберите вид ремонтных работ или доработку", activateParam);

            if (result != null)
            {
                // Проверка выбранной записи
                RowData           WorkRow      = UniversalCard.GetItemRow(result.ToGuid());
                int               WorksType    = (int)WorkRow.ChildSections[RefUniversal.Properties.ID].FindRow("@Name = 'Тип работ'").GetInt32("Value");
                RowDataCollection WorksDevices = WorkRow.ChildSections[RefUniversal.Properties.ID].FindRow("@Name = 'Приборы'").ChildSections[RefUniversal.SelectedValues.ID].Rows;

                if (WorksType == 3)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("Выбранная вами позиция не является ремонтной работой или доработкой. Изменения внесены не будут.");
                    return;
                }
                if (!WorksDevices.Any(r => r.GetString(RefUniversal.SelectedValues.SelectedValue) == DeviceType))
                {
                    string DeviceTypeName = UniversalCard.GetItemName(new Guid(DeviceType));
                    DevExpress.XtraEditors.XtraMessageBox.Show("Выбранная вами позиция не относится к прибору " + DeviceTypeName + ". Изменения внесены не будут.");
                    return;
                }

                // Дбавление выбранной записи
                Improvement = WorksType == 2 ? true : false;
                foreach (int i in index)
                {
                    gridView1.SetRowCellValue(i, "TW", UniversalCard.GetItemName(result.ToGuid()));
                    gridView1.SetRowCellValue(i, "TWID", result.ToString());
                    gridView1.SetRowCellValue(i, "TI", Improvement);
                    gridView1.SetRowCellValue(i, "TR", Work.NegotiationResult.NotAgreed.GetDescription());
                }
                Table.AcceptChanges();
                WorksList = GetWorksList(Table);
            }
        }
Example #12
0
    private void UpdateEmployeePosition(RowData employeeDocsvision, CardData refStaffData, string titleId, string title)
    {
        SectionData  positionSection      = refStaffData.Sections[RefStaff.Positions.ID];
        SectionQuery sectionQueryPosition = Session.CreateSectionQuery();

        // Добавление условия поиска по дате создания документа
        sectionQueryPosition.ConditionGroup.Conditions.AddNew(RefStaff.Positions.Name, FieldType.Unistring,
                                                              ConditionOperation.Equals, title);

        RowDataCollection positionCollection = positionSection.FindRows(sectionQueryPosition.GetXml());

        if (positionCollection.Count > 0)
        {
            //logger.Info("Должность сотрудника обновлена");
            employeeDocsvision[RefStaff.Employees.Position] = positionCollection[0].Id;
        }
        else
        {
            //logger.Info("Создана новая должность. Должность сотрудника обновлена");
            employeeDocsvision[RefStaff.Employees.Position] = AddPositionManual(title, titleId);
        }
    }
Example #13
0
 private void UpdateDepartmentChief(RowData departmentDocsvision, CardData refStaffData, string chief)
 {
     if (chief != null)
     {
         //im RowData employee = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.IDCode, chief);
         RowDataCollection employeeCollection = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.IDCode, chief);
         RowData           employee           = employeeCollection[0];
         if (employee != null)
         {
             departmentDocsvision[RefStaff.Units.Manager] = employee.Id;
         }
     }
     else
     {
         //Поиск по руководителя по родителю
         var existedParentDepartment = departmentDocsvision.ParentRow;
         if (existedParentDepartment != null && existedParentDepartment[RefStaff.Units.Manager] != null)
         {
             departmentDocsvision[RefStaff.Units.Manager] = existedParentDepartment[RefStaff.Units.Manager];
         }
     }
 }
Example #14
0
    public string DeletePosition(string titleId)
    {
        if (string.IsNullOrEmpty(titleId))
        {
            //logger.Info(string.Format(base.LogEmptyInfo, "TitleId"));
            return(string.Format(LogEmptyInfo, "TitleId"));
        }

        CardData    refStaffData = Session.CardManager.GetDictionaryData(RefStaff.ID);
        SectionData unitsSection = refStaffData.Sections[RefStaff.Positions.ID];
        //im RowData position = GetExistObject(RefStaff.Positions.ID, RefStaff.Positions.SyncTag, titleId);
        RowDataCollection positionColl = GetExistObject(RefStaff.Positions.ID, RefStaff.Positions.SyncTag, titleId);
        RowData           position     = positionColl[0];

        if (position != null)
        {
            refStaffData.BeginUpdate();
            unitsSection.DeleteRow(position.Id);
            refStaffData.EndUpdate();
        }

        return("Должность удалена");
    }
Example #15
0
        public static Boolean CheckDuplication(UserSession Session, String CheckName)
        {
            logger.Info("checkName='{0}'", CheckName);

            String[] CheckNameParts = CheckName.Split('\t');
            if (CheckNameParts.Length == 2)
            {
                return(Directory.Exists(Path.Combine(ArchivePath, MyHelper.RemoveInvalidFileNameChars(CheckNameParts[0]), MyHelper.RemoveInvalidFileNameChars(CheckNameParts[1]))));
            }
            else if (CheckNameParts.Length == 3)
            {
                return(Directory.Exists(Path.Combine(ArchivePath, MyHelper.RemoveInvalidFileNameChars(CheckNameParts[0]), MyHelper.RemoveInvalidFileNameChars(CheckNameParts[1]), MyHelper.RemoveInvalidFileNameChars(CheckNameParts[2]))));
            }
            else if (CheckName.Contains("Админ"))
            {
                logger.Info("Big files permission");
                return(false);
            }
            else
            {
                CardData     UniversalCard = Session.CardManager.GetDictionaryData(RefUniversal.ID);
                SectionQuery Query_Section = UniversalCard.Session.CreateSectionQuery();
                Query_Section.ConditionGroup.Conditions.AddNew(RefUniversal.Item.Name, FieldType.Unistring, ConditionOperation.StartsWith, CheckName);
                RowDataCollection FoundItems = UniversalCard.Sections[RefUniversal.Item.ID].FindRows(Query_Section.GetXml(null, true));

                if (FoundItems.Count > 0)
                {
                    logger.Info("Запись найдена");
                    logger.Info("Идентификатор: " + FoundItems[0].Id);

                    return(true);
                }

                logger.Info("Запись не найдена");
                return(false);
            }
        }
Example #16
0
        public static Boolean Synchronize(UserSession Session, String CardID)
        {
            logger.Info("cardId='{0}'", CardID);
            using (new Impersonator(ServerExtension.Domain, ServerExtension.User, ServerExtension.SecurePassword))
            {
                Guid CardId = new Guid(CardID);
                switch (Session.CardManager.GetCardState(CardId))
                {
                case ObjectState.Existing:
                    CardData Card = Session.CardManager.GetCardData(CardId);

                    Card.UnlockCard();

                    ExtraCard Extra = Card.GetExtraCard();
                    if (Extra.IsNull())
                    {
                        logger.Info("Синхронизация не производилась, неверный тип карточки.");
                        return(false);
                    }

                    if (String.IsNullOrEmpty(Extra.Name) || String.IsNullOrEmpty(Extra.ShortCategory) || (String.IsNullOrEmpty(Extra.Code) && !(Extra is ExtraCardMarketingFiles)))
                    {
                        logger.Info("Синхронизация не производилась, не заполнены обязательные поля.");
                        return(false);
                    }


                    String  Digest    = Extra.ToString();
                    Boolean FileSynch = false;

                    /*Синхронизация с реестром только для КД и ТД*/
                    if (Extra is ExtraCardCD || Extra is ExtraCardTD)
                    {
                        Guid RegItemId = Extra.RegID ?? Guid.Empty;
                        if (RegItemId != Guid.Empty)
                        {
                            try
                            {
                                RowData RegItem = Session.CardManager.GetDictionaryData(RefUniversal.ID).Sections[RefUniversal.Item.ID].GetRow(RegItemId);
                                if (RegItem.GetString(RefUniversal.Item.Name) != Digest)
                                {
                                    logger.Info("Требуется синхронизация...");
                                    RegItem.SetString(RefUniversal.Item.Name, Digest);
                                    foreach (RowData rowData in RegItem.ChildSections[0].Rows)
                                    {
                                        String PropertyName = rowData.GetString(RefUniversal.TypeProperties.Name);
                                        if ((PropertyName == "Код СКБ" && Extra is ExtraCardCD) || (PropertyName == "Обозначение документа" && Extra is ExtraCardTD))
                                        {
                                            rowData.SetString(RefUniversal.TypeProperties.Value, Extra.CodeId);
                                            rowData.SetString(RefUniversal.TypeProperties.DisplayValue, Extra.Code);
                                        }
                                        else if (PropertyName == "Тип документа")
                                        {
                                            rowData.SetString(RefUniversal.TypeProperties.Value, Extra.Category);
                                            rowData.SetString(RefUniversal.TypeProperties.DisplayValue, Extra.Category);
                                        }
                                        else if (PropertyName == "Версия")
                                        {
                                            rowData.SetString(RefUniversal.TypeProperties.Value, Extra.Version);
                                            rowData.SetString(RefUniversal.TypeProperties.DisplayValue, Extra.Version);
                                        }
                                    }
                                    logger.Info("Синхронизация с реестром выполнена.");
                                    FileSynch = true;
                                }
                                else
                                {
                                    logger.Info("Синхронизация не требуется.");
                                }
                            }
                            catch (Exception Ex) { logger.WarnException("Не удалось синхронизировать с записью реестра: " + RegItemId, Ex); }
                        }
                        else
                        {
                            logger.Info("Регистрация в реестре");
                            RowData RegisterRow = Session.CardManager.GetDictionaryData(RefUniversal.ID).GetItemTypeRow(MyHelper.RefItem_TechDocRegister);

                            SubSectionData RegisterTypeProperties = RegisterRow.ChildSections[RefUniversal.TypeProperties.ID];

                            RowData RegistrarUnit = Card.Sections[CardOrd.Properties.ID].GetProperty("Подразделение регистратора");
                            RowData Device        = Card.Sections[CardOrd.Properties.ID].GetProperty("Прибор");

                            RowData RegItem = RegisterRow.ChildSections[RefUniversal.Item.ID].Rows.AddNew();
                            RegItem.SetString(RefUniversal.Item.Name, Card.Description);
                            RegItem.SetString(RefUniversal.Item.Comments, Extra.Number);

                            RowDataCollection PropertiesSubSectionRows = RegItem.ChildSections[RefUniversal.Properties.ID].Rows;
                            RowData           ItemPropertyRow          = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='" + (Extra is ExtraCardCD ? "Код СКБ" : "Обозначение документа") + "'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Code);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.CodeId, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Тип документа'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Category);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.Category, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Версия'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Version);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.Version, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Статус'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, ((DocumentState)Extra.Status).GetDescription());
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, (Int32)(DocumentState)Extra.Status, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Подразделение регистратора'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, RegistrarUnit.GetString(CardOrd.Properties.DisplayValue));
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, RegistrarUnit.GetString(CardOrd.Properties.Value), FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Прибор'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Device.GetString(CardOrd.Properties.DisplayValue));
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Device.ChildSections[CardOrd.SelectedValues.ID].FirstRow.GetString(CardOrd.SelectedValues.SelectedValue), FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Ссылка на карточку документа'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Card.Description);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.Card.Id, FieldType.Variant);
                            ItemPropertyRow = PropertiesSubSectionRows.AddNew();
                            ItemPropertyRow.SetGuid(RefUniversal.Properties.Property, RegisterTypeProperties.FindRow("@Name='Файлы документа'").Id);
                            ItemPropertyRow.SetString(RefUniversal.Properties.DisplayValue, Extra.Path);
                            ItemPropertyRow.SetValue(RefUniversal.Properties.Value, Extra.Card.Id, FieldType.Variant);

                            Extra.RegID = RegItem.Id;
                            logger.Info("В реестр добавлена запись: " + Card.Description);
                        }
                    }
                    else
                    {
                        FileSynch = true;
                    }

                    if (FileSynch)
                    {
                        logger.Info("Синхронизация пути...");
                        String OldPath = Extra.Path;
                        logger.Info("Старый путь: " + OldPath);
                        String NewPath = String.Empty;
                        logger.Info("Новый путь: " + NewPath);
                        if (Directory.Exists(OldPath))
                        {
                            DirectoryInfo OldFolder    = new DirectoryInfo(OldPath);
                            DirectoryInfo ParentFolder = OldFolder.Parent;
                            if (ParentFolder != null)
                            {
                                logger.Info("Старый путь:" + OldPath);
                                NewPath = MyHelper.RemoveInvalidFileNameChars(Digest);
                                if (NewPath != Digest)
                                {
                                    logger.Info("Удалены недопустимые символы: " + Digest);
                                }
                                NewPath = Path.Combine(ParentFolder.FullName, NewPath);
                                String TempPath = Path.Combine(ParentFolder.FullName, Path.GetRandomFileName());
                                logger.Info("Временный путь:" + TempPath);
                                logger.Info("Новый путь:" + NewPath + @"\");
                                try
                                {
                                    logger.Info("Перемещение во временную папку");
                                    Directory.Move(OldPath, TempPath);
                                    try
                                    {
                                        logger.Info("Перемещение в новую папку");
                                        Directory.Move(TempPath, NewPath);
                                    }
                                    catch (Exception Ex)
                                    {
                                        logger.WarnException("Перемещение не удалось!", Ex);
                                        try
                                        {
                                            logger.Info("Перемещение в старую папку");
                                            Directory.Move(TempPath, OldPath);
                                        }
                                        catch (Exception SubEx)
                                        {
                                            logger.Warn("Перемещение не удалось!");
                                            logger.ErrorException("Перемещение не удалось!", SubEx);
                                            NewPath = String.Empty;
                                        }
                                    }
                                }
                                catch (Exception Ex)
                                {
                                    logger.WarnException("Перемещение не удалось!", Ex);
                                    NewPath = String.Empty;
                                }

                                if (!String.IsNullOrWhiteSpace(NewPath))
                                {
                                    if (!(Extra is ExtraCardMarketingFiles))
                                    {
                                        Extra.Path = NewPath + @"\";
                                    }
                                    logger.Info("Синхронизация пути выполнена");
                                }
                                else
                                {
                                    logger.Warn("Синхронизация пути не выполнена");
                                }
                            }
                            else
                            {
                                logger.Warn("Отсутствует родительская папка!");
                            }
                        }
                        else
                        {
                            logger.Info("Отсутствует путь для синхронизации!");
                        }
                    }
                    return(true);

                default:
                    return(false);
                }
            }
        }
Example #17
0
        private void AddImprov_Click(object sender, EventArgs e)
        {
            RowData           PartyRow            = null;
            CardData          UniversalDictionary = Session.CardManager.GetCardData(new Guid("{B2A438B7-8BB3-4B13-AF6E-F2F8996E148B}"));
            List <RowData>    PartyItemRows       = new List <RowData>();
            RowDataCollection PartyRowsCollection;

            if (!Document.Sections.Any(r => r.Id == new Guid("{A8F93D97-496B-4675-B520-058B919146B7}")))
            {
                PartyRowsCollection = Document.Sections[new Guid("{5B6B407E-3D72-49E7-97D9-8E1E028C7274}")].Rows.First(r => r.GetString("Name") == "Партия").ChildSections[new Guid("{E6F5105F-8BD8-4500-9780-60D7C1402DDB}")].Rows;
                foreach (RowData CurrentRow in PartyRowsCollection)
                {
                    PartyItemRows.Add(UniversalDictionary.GetItemRow((Guid)CurrentRow.GetGuid("SelectedValue")));
                }
            }
            else
            {
                PartyRowsCollection = Document.Sections[new Guid("{A8F93D97-496B-4675-B520-058B919146B7}")].Rows;
                foreach (RowData CurrentRow in PartyRowsCollection)
                {
                    PartyItemRows.Add(UniversalDictionary.GetItemRow((Guid)CurrentRow.GetGuid("PartyId")));
                }
            }


            //List<RowData> PartyItemRows = PartyRowsCollection.Select(r => UniversalDictionary.GetItemRow((Guid)r.GetGuid("Id"))).ToList();

            if (PartyItemRows.Any(r => UniversalDictionary.GetItemPropertyValue(r.Id, "Наименование прибора").ToGuid() == DeviceType.Id))
            {
                PartyRow = PartyItemRows.FirstOrDefault(r => UniversalDictionary.GetItemPropertyValue(r.Id, "Наименование прибора").ToGuid() == DeviceType.Id);
            }
            else
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! В Разрешении не указана партия для текущего прибора.";
                StatusStrip.Update();
                switch (MessageBox.Show("Внести доработку во все приборы в эксплуатации?", "Ошибка", MessageBoxButtons.YesNo))
                {
                case DialogResult.Yes:
                    StatusStrip.Items["StatusText"].Text = "Продолжение работы...";
                    StatusStrip.Update();
                    break;

                case DialogResult.No:
                    return;

                    break;
                }
            }
            List <Guid> ImprovPartiesGuid = new List <Guid>();

            if (!PartyRow.IsNull())
            {
                RowData PartyDicType                = UniversalDictionary.Sections[new Guid("{5E3ED23A-2B5E-47F2-887C-E154ACEAFB97}")].Rows.First(r => r.GetString("Name") == "Справочник партий");
                IEnumerable <RowData> AllParties    = PartyDicType.ChildSections[new Guid("{DD20BF9B-90F8-4D9A-9553-5B5F17AD724E}")].Rows.Where(r => (UniversalDictionary.GetItemPropertyValue(r.Id, "Наименование прибора").ToGuid() == DeviceType.Id) && (!UniversalDictionary.GetItemPropertyValue(r.Id, "Год начала выпуска").IsNull()));
                PartyComparer         PC            = new PartyComparer();
                List <RowData>        ImprovParties = AllParties.Where(r => PC.Compare(r.GetString("Name"), PartyRow.GetString("Name")) == 1).ToList();
                foreach (RowData CurrentParty in ImprovParties)
                {
                    ImprovPartiesGuid.Add(CurrentParty.Id);
                }
            }



            CardData baseUniversal = Session.CardManager.GetCardData(new Guid("{4538149D-1FC7-4D41-A104-890342C6B4F8}"));

            if (!baseUniversal.Sections[new Guid("{A1DCE6C1-DB96-4666-B418-5A075CDB02C9}")].GetAllRows().Any(r => r.Id == new Guid("{43A6DA44-899C-47D8-9567-2185E05D8524}")))
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Не найден справочник ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }

            // Поиск записей справочника
            SearchQuery searchQuery = Session.CreateSearchQuery();

            searchQuery.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery = searchQuery.AttributiveSearch.CardTypeQueries.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.ID);

            SectionQuery sectionQuery = typeQuery.SectionQueries.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.System.ID);

            sectionQuery.Operation = SectionQueryOperation.And;

            sectionQuery.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup = sectionQuery.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup.Conditions.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.System.Kind, FieldType.RefId, ConditionOperation.Equals, new Guid("{F4650B71-B131-41D2-AAFA-8DA1101ACA52}"));

            SectionQuery sectionQuery2 = typeQuery.SectionQueries.AddNew(new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}"));

            sectionQuery2.Operation = SectionQueryOperation.And;

            sectionQuery2.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup2 = sectionQuery2.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup2.Operation = ConditionGroupOperation.And;
            ConditionGroup2.Conditions.AddNew("BaseDocument", FieldType.RefId, ConditionOperation.Equals, Document.Id);
            ConditionGroup2.Conditions.AddNew("Status", FieldType.Int, ConditionOperation.Equals, 0);

            SectionQuery sectionQuery3 = typeQuery.SectionQueries.AddNew(new Guid("{E6DB53B7-7677-4978-8562-6B17917516A6}"));

            sectionQuery3.Operation = SectionQueryOperation.And;

            sectionQuery3.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup3 = sectionQuery3.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup3.Operation = ConditionGroupOperation.And;
            ConditionGroup3.Conditions.AddNew("DeviceID", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            searchQuery.Limit = 0;
            string             query = searchQuery.GetXml();
            CardDataCollection CardBaseUniversalItems = Session.CardManager.FindCards(query);
            CardData           ItemCard = null;
            RowData            ItemRow  = null;

            if (CardBaseUniversalItems.Count() == 0)
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Не найдена соответствующая карточка ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }
            if (CardBaseUniversalItems.Count() > 1)
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Найдено несколько подходящих карточек ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }
            if (CardBaseUniversalItems.Count() == 1)
            {
                ItemCard = CardBaseUniversalItems.First();
                RowData ItemType = baseUniversal.Sections[new Guid("{A1DCE6C1-DB96-4666-B418-5A075CDB02C9}")].GetAllRows().First(r => r.Id == new Guid("{43A6DA44-899C-47D8-9567-2185E05D8524}"));
                ItemRow = ItemType.ChildSections[new Guid("{1B1A44FB-1FB1-4876-83AA-95AD38907E24}")].Rows.First(r => (Guid)r.GetGuid("ItemCard") == ItemCard.Id);
                if (ItemRow.IsNull())
                {
                    StatusStrip.Items["StatusText"].Text = "Ошибка! Не найдена соответствующая запись справочника ремонтных работ и доработок...";
                    StatusStrip.Update();
                    return;
                }
                else
                {
                    StatusStrip.Items["StatusText"].Text = "Запись найдена: " + ItemRow.GetString("Name") + "...";
                    StatusStrip.Update();
                }
            }

            Guid              DevicePassportTypeID     = new Guid("{42826E25-AD0E-4D9C-8B18-CD88E6796972}");
            CardData          CardTypeDictionary       = Session.CardManager.GetDictionaryData(RefTypes.ID);
            SectionData       DocumentTypes            = CardTypeDictionary.Sections[RefTypes.DocumentTypes.ID];
            RowData           DevicePassportType       = DocumentTypes.GetRow(DevicePassportTypeID);
            RowDataCollection DevicePassportProperties = DevicePassportType.ChildSections[RefTypes.Properties.ID].Rows;

            SearchQuery searchQuery2 = Session.CreateSearchQuery();

            searchQuery2.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery2    = searchQuery2.AttributiveSearch.CardTypeQueries.AddNew(CardOrd.ID);
            SectionQuery  sectionQuery4 = typeQuery2.SectionQueries.AddNew(CardOrd.MainInfo.ID);

            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("Type", FieldType.RefId, ConditionOperation.Equals, DevicePassportTypeID);

            sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.Properties.ID);
            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "Прибор");
            sectionQuery4.ConditionGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            if (ImprovPartiesGuid.Count != 0)
            {
                sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.Properties.ID);
                sectionQuery4.Operation = SectionQueryOperation.And;
                sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
                sectionQuery4.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "№ партии");
                ConditionGroup PartyGroup = sectionQuery4.ConditionGroup.ConditionGroups.AddNew();
                PartyGroup.Operation = ConditionGroupOperation.Or;
                for (int j = 0; j < ImprovPartiesGuid.Count; j++)
                {
                    PartyGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.OneOf, ImprovPartiesGuid.ToArray()[j]);
                }
            }
            else
            {
                sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.Properties.ID);
                sectionQuery4.Operation = SectionQueryOperation.And;
                sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
                sectionQuery4.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "Состояние прибора");
                sectionQuery4.ConditionGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.OneOf, new int[] { 5, 6 });
            }
            // Получение текста запроса
            searchQuery2.Limit = 0;
            string query2 = searchQuery2.GetXml();

            Console.WriteLine(query2);
            Console.ReadLine();
            CardDataCollection coll = Session.CardManager.FindCards(query2);

            Clear();

            StatusStrip.Items["StatusText"].Text = "Найдено паспортов: " + coll.Count.ToString() + "...";
            StatusStrip.Update();

            int i = 0;

            for (i = 0; i < coll.Count; i++)
            {
                CardData Card = coll[i];
                Card.ForceUnlock();
                StatusStrip.Items["StatusText"].Text = i.ToString() + " из " + coll.Count + ". " + Card.Description;
                StatusStrip.Update();

                SectionData       Properties  = Card.Sections[CardOrd.Properties.ID];
                RowDataCollection DocumentCol = Properties.FindRow("@Name = 'Документ'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection Assembly    = Properties.FindRow("@Name = 'Сборочный узел'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection RepareItem  = Properties.FindRow("@Name = 'Запись справочника ремонтных работ и доработок'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection Indication  = Properties.FindRow("@Name = 'Указание'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection Check       = Properties.FindRow("@Name = 'Выполнено'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection CheckDate   = Properties.FindRow("@Name = 'Дата выполнения'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowDataCollection Comments    = Properties.FindRow("@Name = 'Комментарии'").ChildSections[CardOrd.SelectedValues.ID].Rows;

                if (DocumentCol.Count != Assembly.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (Assembly.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = Assembly.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != RepareItem.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (RepareItem.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = RepareItem.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != Indication.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (Indication.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = Indication.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != Check.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (Check.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = Check.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != CheckDate.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (CheckDate.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = CheckDate.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (DocumentCol.Count != Comments.Count)
                {
                    foreach (RowData Doc in DocumentCol)
                    {
                        int Order = (int)Doc.GetInt32("Order");
                        if (Comments.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                        {
                            RowData NewRow = Comments.AddNew();
                            NewRow.SetInt32("Order", Order);
                        }
                    }
                }

                if (!DocumentCol.Any(r => r.GetGuid("SelectedValue") == Document.Id))
                {
                    int     CurrentOrder = DocumentCol.Count + 1;
                    RowData NewRow2      = DocumentCol.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                    NewRow2.SetGuid("SelectedValue", Document.Id);

                    NewRow2 = RepareItem.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                    NewRow2.SetGuid("SelectedValue", ItemRow.Id);

                    NewRow2 = Assembly.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                    if (!ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("AssemblyUnit").IsNull())
                    {
                        NewRow2.SetGuid("SelectedValue", (Guid)ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("AssemblyUnit"));
                    }

                    NewRow2 = Indication.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                    if (!ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("Instructions").IsNull())
                    {
                        NewRow2.SetGuid("SelectedValue", (Guid)ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("Instructions"));
                    }

                    NewRow2 = Check.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);

                    NewRow2 = CheckDate.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);

                    NewRow2 = Comments.AddNew();
                    NewRow2.SetInt32("Order", CurrentOrder);
                }
                Clear();
            }

            StatusStrip.Items["StatusText"].Text = i.ToString() + " карточек успешно обработано.";
            StatusStrip.Update();
        }
Example #18
0
        /// <summary>
        /// Осуществляет обновление доработки в Паспорте прибора на основании данных Конструктора справочников
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BindImprov_Click(object sender, EventArgs e)
        {
            if (this.TypeName.Text == "")
            {
                MessageBox.Show("Укажите тип прибора!");
                return;
            }

            if (this.DocName.Text == "")
            {
                MessageBox.Show("Укажите документ-основание!");
                return;
            }

            StatusStrip.Items["StatusText"].Text = "Процесс начат...";
            StatusStrip.Update();

            // Получение записи справочника ремонтных работ и доработок
            //ObjectContext Context = Session.CreateContext();
            // Получение справочника "Ремонтные работы и доработки"
            //IBaseUniversalService baseUniversalService = Context.GetService<IBaseUniversalService>();
            //BaseUniversal baseUniversal = Context.GetObject<BaseUniversal>(RefBaseUniversal.ID);

            CardData baseUniversal = Session.CardManager.GetCardData(new Guid("{4538149D-1FC7-4D41-A104-890342C6B4F8}"));

            if (!baseUniversal.Sections[new Guid("{A1DCE6C1-DB96-4666-B418-5A075CDB02C9}")].GetAllRows().Any(r => r.Id == new Guid("{43A6DA44-899C-47D8-9567-2185E05D8524}")))
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Не найден справочник ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }

            // Поиск записей справочника
            SearchQuery searchQuery = Session.CreateSearchQuery();

            searchQuery.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery = searchQuery.AttributiveSearch.CardTypeQueries.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.ID);

            SectionQuery sectionQuery = typeQuery.SectionQueries.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.System.ID);

            sectionQuery.Operation = SectionQueryOperation.And;

            sectionQuery.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup = sectionQuery.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup.Conditions.AddNew(DocsVision.BackOffice.CardLib.CardDefs.CardBaseUniversalItem.System.Kind, FieldType.RefId, ConditionOperation.Equals, new Guid("{F4650B71-B131-41D2-AAFA-8DA1101ACA52}"));

            SectionQuery sectionQuery2 = typeQuery.SectionQueries.AddNew(new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}"));

            sectionQuery2.Operation = SectionQueryOperation.And;

            sectionQuery2.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup2 = sectionQuery2.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup2.Operation = ConditionGroupOperation.And;
            ConditionGroup2.Conditions.AddNew("BaseDocument", FieldType.RefId, ConditionOperation.Equals, Document.Id);
            ConditionGroup2.Conditions.AddNew("Status", FieldType.Int, ConditionOperation.Equals, 0);

            SectionQuery sectionQuery3 = typeQuery.SectionQueries.AddNew(new Guid("{E6DB53B7-7677-4978-8562-6B17917516A6}"));

            sectionQuery3.Operation = SectionQueryOperation.And;

            sectionQuery3.ConditionGroup.Operation = ConditionGroupOperation.And;
            ConditionGroup ConditionGroup3 = sectionQuery3.ConditionGroup.ConditionGroups.AddNew();

            ConditionGroup3.Operation = ConditionGroupOperation.And;
            ConditionGroup3.Conditions.AddNew("DeviceID", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            searchQuery.Limit = 0;
            string             query = searchQuery.GetXml();
            CardDataCollection CardBaseUniversalItems = Session.CardManager.FindCards(query);
            CardData           ItemCard = null;
            RowData            ItemRow  = null;

            if (CardBaseUniversalItems.Count() == 0)
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Не найдена соответствующая карточка ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }
            if (CardBaseUniversalItems.Count() > 1)
            {
                StatusStrip.Items["StatusText"].Text = "Ошибка! Найдено несколько подходящих карточек ремонтных работ и доработок...";
                StatusStrip.Update();
                return;
            }
            if (CardBaseUniversalItems.Count() == 1)
            {
                ItemCard = CardBaseUniversalItems.First();
                RowData ItemType = baseUniversal.Sections[new Guid("{A1DCE6C1-DB96-4666-B418-5A075CDB02C9}")].GetAllRows().First(r => r.Id == new Guid("{43A6DA44-899C-47D8-9567-2185E05D8524}"));
                ItemRow = ItemType.ChildSections[new Guid("{1B1A44FB-1FB1-4876-83AA-95AD38907E24}")].Rows.First(r => (Guid)r.GetGuid("ItemCard") == ItemCard.Id);
                if (ItemRow.IsNull())
                {
                    StatusStrip.Items["StatusText"].Text = "Ошибка! Не найдена соответствующая запись справочника ремонтных работ и доработок...";
                    StatusStrip.Update();
                    return;
                }
                else
                {
                    StatusStrip.Items["StatusText"].Text = "Запись найдена: " + ItemRow.GetString("Name") + "...";
                    StatusStrip.Update();
                }
            }


            Guid              DevicePassportTypeID     = new Guid("{42826E25-AD0E-4D9C-8B18-CD88E6796972}");
            CardData          CardTypeDictionary       = Session.CardManager.GetDictionaryData(RefTypes.ID);
            SectionData       DocumentTypes            = CardTypeDictionary.Sections[RefTypes.DocumentTypes.ID];
            RowData           DevicePassportType       = DocumentTypes.GetRow(DevicePassportTypeID);
            RowDataCollection DevicePassportProperties = DevicePassportType.ChildSections[RefTypes.Properties.ID].Rows;

            SearchQuery searchQuery2 = Session.CreateSearchQuery();

            searchQuery2.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery2    = searchQuery2.AttributiveSearch.CardTypeQueries.AddNew(CardOrd.ID);
            SectionQuery  sectionQuery4 = typeQuery2.SectionQueries.AddNew(CardOrd.MainInfo.ID);

            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("Type", FieldType.RefId, ConditionOperation.Equals, DevicePassportTypeID);

            sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.Properties.ID);
            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "Прибор");
            sectionQuery4.ConditionGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            sectionQuery4           = typeQuery2.SectionQueries.AddNew(CardOrd.SelectedValues.ID);
            sectionQuery4.Operation = SectionQueryOperation.And;
            sectionQuery4.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery4.ConditionGroup.Conditions.AddNew("SelectedValue", FieldType.RefCardId, ConditionOperation.Equals, Document.Id);

            // Получение текста запроса
            searchQuery2.Limit = 0;
            string query2 = searchQuery2.GetXml();

            Console.WriteLine(query2);
            Console.ReadLine();
            CardDataCollection coll = Session.CardManager.FindCards(query2);

            Clear();

            StatusStrip.Items["StatusText"].Text = "Найдено паспортов: " + coll.Count.ToString() + "...";
            StatusStrip.Update();

            int i = 0;

            for (i = 0; i < coll.Count; i++)
            {
                CardData Card = coll[i];
                Card.ForceUnlock();
                StatusStrip.Items["StatusText"].Text = i.ToString() + " из " + coll.Count + ". " + Card.Description;
                StatusStrip.Update();


                SectionData       Properties  = Card.Sections[CardOrd.Properties.ID];
                RowDataCollection DocumentCol = Properties.FindRow("@Name = 'Документ'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowData           DocumentRow = DocumentCol.First(r => new Guid(r.GetString("SelectedValue")).Equals(Document.Id));
                if (DocumentRow != null)
                {
                    RowDataCollection Assembly   = Properties.FindRow("@Name = 'Сборочный узел'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection RepareItem = Properties.FindRow("@Name = 'Запись справочника ремонтных работ и доработок'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Indication = Properties.FindRow("@Name = 'Указание'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Check      = Properties.FindRow("@Name = 'Выполнено'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection CheckDate  = Properties.FindRow("@Name = 'Дата выполнения'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Comments   = Properties.FindRow("@Name = 'Комментарии'").ChildSections[CardOrd.SelectedValues.ID].Rows;

                    if (DocumentCol.Count != Assembly.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (Assembly.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = Assembly.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != RepareItem.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (RepareItem.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = RepareItem.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != Indication.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (Indication.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = Indication.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != Check.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (Check.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = Check.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != CheckDate.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (CheckDate.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = CheckDate.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    if (DocumentCol.Count != Comments.Count)
                    {
                        foreach (RowData Doc in DocumentCol)
                        {
                            int Order = (int)Doc.GetInt32("Order");
                            if (Comments.FirstOrDefault(r => r.GetInt32("Order") == Order).IsNull())
                            {
                                RowData NewRow = Comments.AddNew();
                                NewRow.SetInt32("Order", Order);
                            }
                        }
                    }

                    int CurrentOrder = (int)DocumentRow.GetInt32("Order");

                    RepareItem.First(r => r.GetInt32("Order") == CurrentOrder).SetGuid("SelectedValue", ItemRow.Id);

                    if (!ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("AssemblyUnit").IsNull())
                    {
                        Assembly.First(r => r.GetInt32("Order") == CurrentOrder).SetGuid("SelectedValue", (Guid)ItemCard.Sections[new Guid("{3F9F3C1D-1CF1-4E71-BBE4-31D6AAD94EF7}")].FirstRow.GetGuid("AssemblyUnit"));
                    }
                    if (!ItemRow.GetString("Description").IsNull())
                    {
                        Indication.First(r => r.GetInt32("Order") == CurrentOrder).SetString("SelectedValue", ItemRow.GetString("Description"));
                    }
                }
                Clear();
            }

            StatusStrip.Items["StatusText"].Text = i.ToString() + " карточек успешно обработано.";
            StatusStrip.Update();
        }
Example #19
0
        private void DeleteImprov_Click(object sender, EventArgs e)
        {
            if (this.TypeName.Text == "")
            {
                MessageBox.Show("Укажите тип прибора!");
                return;
            }

            if (this.DocName.Text == "")
            {
                MessageBox.Show("Укажите документ-основание!");
                return;
            }

            StatusStrip.Items["StatusText"].Text = "Процесс начат...";
            StatusStrip.Update();

            Guid              DevicePassportTypeID     = new Guid("{42826E25-AD0E-4D9C-8B18-CD88E6796972}");
            CardData          CardTypeDictionary       = Session.CardManager.GetDictionaryData(RefTypes.ID);
            SectionData       DocumentTypes            = CardTypeDictionary.Sections[RefTypes.DocumentTypes.ID];
            RowData           DevicePassportType       = DocumentTypes.GetRow(DevicePassportTypeID);
            RowDataCollection DevicePassportProperties = DevicePassportType.ChildSections[RefTypes.Properties.ID].Rows;

            SearchQuery searchQuery = Session.CreateSearchQuery();

            searchQuery.CombineResults = ConditionGroupOperation.And;

            CardTypeQuery typeQuery    = searchQuery.AttributiveSearch.CardTypeQueries.AddNew(CardOrd.ID);
            SectionQuery  sectionQuery = typeQuery.SectionQueries.AddNew(CardOrd.MainInfo.ID);

            sectionQuery.Operation = SectionQueryOperation.And;
            sectionQuery.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery.ConditionGroup.Conditions.AddNew("Type", FieldType.RefId, ConditionOperation.Equals, DevicePassportTypeID);

            sectionQuery           = typeQuery.SectionQueries.AddNew(CardOrd.Properties.ID);
            sectionQuery.Operation = SectionQueryOperation.And;
            sectionQuery.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery.ConditionGroup.Conditions.AddNew("Name", FieldType.String, ConditionOperation.Equals, "Прибор");
            sectionQuery.ConditionGroup.Conditions.AddNew("Value", FieldType.RefId, ConditionOperation.Equals, DeviceType.Id);

            sectionQuery           = typeQuery.SectionQueries.AddNew(CardOrd.SelectedValues.ID);
            sectionQuery.Operation = SectionQueryOperation.And;
            sectionQuery.ConditionGroup.Operation = ConditionGroupOperation.And;
            sectionQuery.ConditionGroup.Conditions.AddNew("SelectedValue", FieldType.RefCardId, ConditionOperation.Equals, Document.Id);

            // Получение текста запроса
            searchQuery.Limit = 0;
            string query = searchQuery.GetXml();

            Console.WriteLine(query);
            Console.ReadLine();
            CardDataCollection coll = Session.CardManager.FindCards(query);

            Clear();

            StatusStrip.Items["StatusText"].Text = "Найдено паспортов: " + coll.Count.ToString() + "...";
            StatusStrip.Update();

            int i = 0;

            for (i = 0; i < coll.Count; i++)
            {
                CardData Card = coll[i];
                Card.ForceUnlock();
                StatusStrip.Items["StatusText"].Text = i.ToString() + " из " + coll.Count + ". " + Card.Description;
                StatusStrip.Update();

                SectionData       Properties  = Card.Sections[CardOrd.Properties.ID];
                RowDataCollection DocumentCol = Properties.FindRow("@Name = 'Документ'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                RowData           DocumentRow = DocumentCol.First(r => new Guid(r.GetString("SelectedValue")).Equals(Document.Id));
                if (DocumentRow != null)
                {
                    int Order = (int)DocumentRow.GetInt32("Order");

                    RowDataCollection Assembly   = Properties.FindRow("@Name = 'Сборочный узел'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection RepareItem = Properties.FindRow("@Name = 'Запись справочника ремонтных работ и доработок'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Indication = Properties.FindRow("@Name = 'Указание'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Check      = Properties.FindRow("@Name = 'Выполнено'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection CheckDate  = Properties.FindRow("@Name = 'Дата выполнения'").ChildSections[CardOrd.SelectedValues.ID].Rows;
                    RowDataCollection Comments   = Properties.FindRow("@Name = 'Комментарии'").ChildSections[CardOrd.SelectedValues.ID].Rows;

                    if (Assembly.FirstOrDefault(r => r.GetInt32("Order") == Order) != null)
                    {
                        Assembly.Remove(Assembly.First(r => r.GetInt32("Order") == Order).Id);
                    }
                    if (RepareItem.FirstOrDefault(r => r.GetInt32("Order") == Order) != null)
                    {
                        RepareItem.Remove(RepareItem.First(r => r.GetInt32("Order") == Order).Id);
                    }
                    if (Indication.FirstOrDefault(r => r.GetInt32("Order") == Order) != null)
                    {
                        Indication.Remove(Indication.First(r => r.GetInt32("Order") == Order).Id);
                    }
                    if (Check.FirstOrDefault(r => r.GetInt32("Order") == Order) != null)
                    {
                        Check.Remove(Check.First(r => r.GetInt32("Order") == Order).Id);
                    }
                    if (CheckDate.FirstOrDefault(r => r.GetInt32("Order") == Order) != null)
                    {
                        CheckDate.Remove(CheckDate.First(r => r.GetInt32("Order") == Order).Id);
                    }
                    if (Comments.FirstOrDefault(r => r.GetInt32("Order") == Order) != null)
                    {
                        Comments.Remove(Comments.First(r => r.GetInt32("Order") == Order).Id);
                    }

                    DocumentCol.Remove(DocumentRow.Id);
                }
                Clear();
            }

            StatusStrip.Items["StatusText"].Text = i.ToString() + " карточек успешно обработано.";
            StatusStrip.Update();
        }
Example #20
0
    //im public string UpdateEmployee(string code, string familyName, string firstName, string middleName, bool? actual, string titleId,
    public object UpdateEmployee(string code, string familyName, string firstName, string middleName, bool?actual, string titleId,
                                 string title, int routingType, string departmentCode, string email, string employeeChief)
    {
        string requestEmptyField = GetRequestEmployee(code, familyName, departmentCode, actual);

        if (!string.IsNullOrEmpty(requestEmptyField))
        {
            //logger.Info(requestEmptyField);
            //im return requestEmptyField;
            return(true);
        }

        CardData refStaffData = Session.CardManager.GetDictionaryData(RefStaff.ID);

        // Поиск пользователя
        //var rowColl = new RowDataCollection<RowData>(); //im

        //im RowData employeeDocsvision = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.IDCode, code);
        RowDataCollection employeeDocsvisionColl = null;

        try{
            employeeDocsvisionColl = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.IDCode, code);
        }
        catch {}

        //im if (employeeDocsvision == null)

        /*
         * if (employeeDocsvisionColl == null || employeeDocsvisionColl.Count == 0 || employeeDocsvisionColl.Count > 1)
         * {
         *  //im var accountNameFromAd = GetAccountFromAD(familyName, firstName, middleName, email);
         *  //im employeeDocsvision = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.AccountName, accountNameFromAd);
         * return true;
         * }
         */
        RowData employeeDocsvision = null;

        try{
            employeeDocsvision = employeeDocsvisionColl[0];
        }
        catch {}

        //im if (employeeDocsvision == null)
        if (employeeDocsvision == null)
        {
            //logger.Info("Сотрудник не найден, началось создание нового сотрудника.");
            return(AddEmployee(code, familyName, firstName, middleName, actual, titleId, title, routingType,
                               departmentCode, email, employeeChief));
        }

        //Поиск подразделения
        //im RowData department = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, departmentCode);
        RowDataCollection departmentColl = null;

        try{
            departmentColl = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, departmentCode);
        }
        catch {}
        //im if (department == null)
        if (departmentColl == null || departmentColl.Count == 0 || departmentColl.Count > 1)
        {
            //logger.Info("Не найдено подразделение сотрудника.");
            //im return "Не найдено подразделение сотрудника.";
            return("Не найдено подразделение для сотрудника.");
        }
        RowData department = departmentColl[0];

        refStaffData.BeginUpdate();

        // Перемещение сотрудника в требуемое подразделение, если необходимо
        MoveExistEmployee(employeeDocsvision, department);


        // Обновление следующих полей: 1. Фамилия  2. Имя  3. Отчество 6. E-mail, 8. Маршрутизация, так же IDCode, displayName
        UpdateEmployeeSimple(employeeDocsvision, refStaffData, code, familyName, firstName, middleName, email, routingType);

        // Обновление статуса сотрудника
        SetEmployeeStatus(actual, employeeDocsvision);

        //logger.Info("Обновление базовых полей сотрудника завершено.");

        //4. Должность
        UpdateEmployeePosition(employeeDocsvision, refStaffData, titleId, title);

        //5. Руководитель
        UpdateEmployeeManager(employeeDocsvision, refStaffData, employeeChief);

        /*
         * // 7. Пользователь
         * if (email != null || email != string.Empty)
         *      SetAccountName(employeeDocsvision, familyName, firstName, middleName, email);
         */

        refStaffData.EndUpdate();
        return(true);

        // 9. Папки
        //im DocsVisionFilesHelper filesHelper = new DocsVisionFilesHelper(Session, ObjectContext/*, logger*/);
        //im filesHelper.UpdateEmployeeFolder(employeeDocsvision);


        //im refStaffData.EndUpdate();
        //logger.Info("Обновление сотрудника завершено.");
        //im return "Обновление сотрудника завершено.";
        //im return true;
    }
Example #21
0
    //Сотрудники

    //im public string AddEmployee(string code, string familyName, string firstName, string middleName, bool? actual, string titleId,
    public object AddEmployee(string code, string familyName, string firstName, string middleName, bool?actual, string titleId,
                              string title, int routingType, string departmentCode, string email, string employeeChief)
    {
        try
        {
            string requestEmptyField = GetRequestEmployee(code, familyName, departmentCode, actual);
            if (!string.IsNullOrEmpty(requestEmptyField))
            {
                //logger.Info(requestEmptyField);
                //im return requestEmptyField;
                return(true);
            }

            if (!actual.HasValue || !actual.Value)
            {
                //im return "Сотрудник неактуален, добавление не произведено.";
                return(true);
            }

            //Поиск сотрудника ***
            //im RowData employeeDocsvision = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.IDCode, code);
            RowDataCollection employeeDocsvision = GetExistObject(RefStaff.Employees.ID, RefStaff.Employees.IDCode, code);
            //im if (employeeDocsvision == null)
            if (employeeDocsvision == null || employeeDocsvision.Count == 0)
            {
                //Поиск подразделения
                //im RowData department = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, departmentCode);
                RowDataCollection departmentColl = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, departmentCode);
                //im if (department == null)
                if (departmentColl == null || departmentColl.Count == 0 || departmentColl.Count > 1)
                {
                    return("Не найдено подразделение.");
                    //return false;
                }
                RowData department = departmentColl[0];

                CardData refStaffData = Session.CardManager.GetDictionaryData(RefStaff.ID);

                refStaffData.BeginUpdate();

                // Создание нового пользователя
                RowData newEmployeeDocsvision = CreateEmployee(department);


                // Обновление следующих полей: 1. Фамилия  2. Имя  3. Отчество 6. E-mail, 8. Маршрутизация, так же IDCode, displayName
                UpdateEmployeeSimple(newEmployeeDocsvision, refStaffData, code, familyName, firstName, middleName, email, routingType);

                // 7. Пользователь
                if (!string.IsNullOrEmpty(email))
                {
                    SetAccountName(newEmployeeDocsvision, familyName, firstName, middleName, email);
                }

                //4. Должность
                UpdateEmployeePosition(newEmployeeDocsvision, refStaffData, titleId, title);

                //5. Руководитель
                UpdateEmployeeManager(newEmployeeDocsvision, refStaffData, employeeChief);

                refStaffData.EndUpdate();

                // 9. Папки
                DocsVisionFilesHelper filesHelper = new DocsVisionFilesHelper(Session, ObjectContext /*, logger*/);
                filesHelper.UpdateEmployeeFolder(newEmployeeDocsvision);

                //logger.Info("Создание сотрудника завершено.");

                //Проверка наличия созданного сотрудника

                /*logger.Info(base.SearchEmployeeTest(refStaffData, employee1C) == true
                 *                              ? "Наличие созданного сотрудника подтверждено!"
                 *                              : "Созданный сотрудник не подтвержден!");*/
                /*im
                 * return (SearchEmployeeTest(refStaffData, code)
                 *                              ? "Наличие созданного сотрудника подтверждено!"
                 *                              : "Созданный сотрудник не подтвержден!");*/

                return(SearchEmployeeTest(refStaffData, code)
                                                                ? true
                                                                : true); // создал, но не подтвердил
            }
            else
            {
                //im return "Сотрудник уже есть в справочнике";
                return(true);
            }
        }
        catch (Exception ex)
        {
            //im return string.Format("Ошибка создания сотрудника {0}", ex.Message);
            return("Не удалось добавить сотрудника в справочник.");
        }
    }
Example #22
0
        public static Boolean RegisterProtocol(UserSession Session, String CardID, String TempFolder, Guid EmployeeId)
        {
            logger.Info("cardId='{0}'", CardID);
            logger.Info("tempName='{0}'", TempFolder);
            logger.Info("EmployeeId='{0}'", EmployeeId);
            using (new Impersonator(ServerExtension.Domain, ServerExtension.User, ServerExtension.SecurePassword))
            {
                Guid CardId = new Guid(CardID);
                switch (Session.CardManager.GetCardState(CardId))
                {
                case ObjectState.Existing:
                    DirectoryInfo TempDirectory = new DirectoryInfo(Path.Combine(ArchiveTempPath, TempFolder));
                    FileInfo[]    TempFiles     = TempDirectory.GetFiles();
                    logger.Info("В папке файлов: " + TempFiles.Length);
                    if (TempFiles.Length > 0)
                    {
                        logger.Info("Файлы: " + TempFiles.Select(file => file.Name).Aggregate((a, b) => a + "; " + b));
                        CardData Card = Session.CardManager.GetCardData(CardId);
                        Card.UnlockCard();
                        if (Card.InUpdate)
                        {
                            Card.CancelUpdate();
                        }
                        Card.PlaceLock();
                        Card.BeginUpdate();
                        foreach (Protocol Protocol in TempFiles.Select(fi => new Protocol(fi)))
                        {
                            if (Protocol.IsParsed)
                            {
                                RowData MainInfoRow   = Card.Sections[CardOrd.MainInfo.ID].FirstRow;
                                Guid    FilesID       = MainInfoRow.GetGuid(CardOrd.MainInfo.FilesID) ?? Guid.Empty;
                                Boolean FileListExist = !(FilesID.IsEmpty() && Card.Session.CardManager.GetCardState(FilesID) == ObjectState.Existing);
                                logger.Info("FileListExist = " + FileListExist);
                                CardData FileListCard;
                                if (FileListExist)
                                {
                                    FileListCard = Card.Session.CardManager.GetCardData(FilesID);
                                }
                                else
                                {
                                    FileListCard = Card.Session.CardManager.CreateCardData(FileList.ID);
                                    MainInfoRow.SetGuid(CardOrd.MainInfo.FilesID, FileListCard.Id);
                                }

                                SectionData FileReferencesSection = FileListCard.Sections[FileList.FileReferences.ID];
                                /* Проверка существования файла протокола в карточке */
                                if (!FileReferencesSection.Rows.Any(file => Protocol.PhysicalFile.Name.Contains(file.GetString(CardFile.MainInfo.FileName))))
                                {
                                    FileListCard.UnlockCard();

                                    VersionedFileCard FileCard        = (VersionedFileCard)Card.Session.CardManager.CreateCard(DocsVision.Platform.Cards.Constants.VersionedFileCard.ID);
                                    FileVersion       FileCardVersion = FileCard.Initialize(Protocol.PhysicalFile.FullName, Guid.Empty, false, true);
                                    CardData          FileData        = Card.Session.CardManager.CreateCardData(CardFile.ID);

                                    FileData.BeginUpdate();
                                    FileData.Description = "Файл: " + FileCard.Name;

                                    RowData FileMainInfoRow = FileData.Sections[CardFile.MainInfo.ID].Rows.AddNew();
                                    FileMainInfoRow.SetGuid(CardFile.MainInfo.FileID, FileCard.Id);
                                    FileMainInfoRow.SetString(CardFile.MainInfo.FileName, FileCardVersion.Name);
                                    FileMainInfoRow.SetGuid(CardFile.MainInfo.Author, FileCardVersion.AuthorId);
                                    FileMainInfoRow.SetInt32(CardFile.MainInfo.FileSize, FileCardVersion.Size);
                                    FileMainInfoRow.SetInt32(CardFile.MainInfo.VersioningType, 0);

                                    RowData FilePropertiesRow = FileData.Sections[CardFile.Properties.ID].Rows.AddNew();
                                    FilePropertiesRow.SetString(CardFile.Properties.Name, "Дата начала испытаний");
                                    FilePropertiesRow.SetInt32(CardFile.Properties.ParamType, (Int32)PropertieParamType.Date);
                                    FilePropertiesRow.SetString(CardFile.Properties.Value, Protocol.StringDate);
                                    FilePropertiesRow.SetString(CardFile.Properties.DisplayValue, Protocol.StringDate);

                                    FileData.Sections[CardFile.Categories.ID].Rows.AddNew().SetGuid(CardFile.Categories.CategoryID, MyHelper.RefCategory_CalibrationProtocol);

                                    FileData.EndUpdate();

                                    Int32 FilesCount = FileReferencesSection.Rows.Count;
                                    FileReferencesSection.Rows.AddNew().SetGuid(FileList.FileReferences.CardFileID, FileData.Id);
                                    FileListCard.Sections[FileList.MainInfo.ID].FirstRow.SetInt32(FileList.MainInfo.Count, FilesCount + 1);

                                    SectionData PropertiesSection = Card.Sections[CardOrd.Properties.ID];
                                    RowData     PropertyRow       = PropertiesSection.GetProperty("Дата");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetDateTime(CardOrd.SelectedValues.SelectedValue, DateTime.Now);
                                    }
                                    PropertyRow = PropertiesSection.GetProperty("Действие");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetString(CardOrd.SelectedValues.SelectedValue, "Прикреплен протокол калибровки");
                                    }
                                    PropertyRow = PropertiesSection.GetProperty("Участник");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetGuid(CardOrd.SelectedValues.SelectedValue, EmployeeId);
                                    }
                                    PropertyRow = PropertiesSection.GetProperty("Комментарий");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetString(CardOrd.SelectedValues.SelectedValue, "Автоматическое прикрепление протокола калибровки " + Protocol.PhysicalFile.Name);
                                    }
                                    PropertyRow = PropertiesSection.GetProperty("Ссылки");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetString(CardOrd.SelectedValues.SelectedValue, null);
                                    }

                                    if (!FileListExist)
                                    {
                                        Card.Sections[CardOrd.MainInfo.ID].FirstRow.SetGuid(CardOrd.MainInfo.FilesID, FileListCard.Id);
                                    }
                                }
                            }
                            else
                            {
                                logger.Warn("Нераспознаный файл: " + Protocol.PhysicalFile.Name);
                            }
                        }

                        Card.EndUpdate();
                        Card.RemoveLock();

                        TempDirectory.Delete(true);
                        logger.Info("RegisterProtocol - выполнено.");
                    }
                    else
                    {
                        logger.Info("RegisterProtocol - не выполнено.");
                    }
                    return(true);

                default:
                    logger.Info("RegisterProtocol - не выполнено. Паспорт прибора не существует.");
                    return(false);
                }
            }
        }
Example #23
0
    //public string UpdateDepartment(string unitId, string unit, string unitFull, string ownerId, string chief, string curator)
    public object UpdateDepartment(string unitId, string unit, string unitFull, string ownerId, string chief, string curator)
    {
        if (string.IsNullOrEmpty(unit))
        {
            //logger.Info(string.Format(LogEmptyInfo, "Unit"));
            //return string.Format(LogEmptyInfo, "Unit");
            return(true);
        }

        CardData    refStaffData = Session.CardManager.GetDictionaryData(RefStaff.ID);
        SectionData unitsSection = refStaffData.Sections[RefStaff.Units.ID];

        //im RowData department = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, unitId);
        RowDataCollection departmentColl = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, unitId);
        RowData           department     = null;

        try{
            department = departmentColl[0];
        }
        catch {}

        if (department == null)
        {
            return(AddDepartment(unitId, unit, unitFull, ownerId, chief, curator));
        }

        refStaffData.BeginUpdate();

        //Родитель
        if (ownerId == unitId)
        {
            return(true);
        }
        var existedParentDepartmentCode = department.ParentRow[RefStaff.Units.Code];

        if (!(existedParentDepartmentCode == null && ownerId == null) && !ownerId.Equals(existedParentDepartmentCode))
        {
            SectionQuery sectionQueryParentDepartment = Session.CreateSectionQuery();
            sectionQueryParentDepartment.ConditionGroup.Conditions.AddNew(RefStaff.Units.Code, FieldType.Unistring,
                                                                          ConditionOperation.Equals, ownerId);

            RowDataCollection departmentParentCollection = unitsSection.FindRows(sectionQueryParentDepartment.GetXml());
            if (departmentParentCollection != null && departmentParentCollection.Count > 0)
            {
                department.Move(departmentParentCollection[0].Id, Guid.Empty);
            }
        }

        refStaffData.EndUpdate();

        refStaffData.BeginUpdate();
        try{
            var isFirstLoad = ConfigurationManager.AppSettings["FirstLoad"];
            if (isFirstLoad == "1")
            {
                department[RefStaff.Units.Name]     = unit;
                department[RefStaff.Units.FullName] = unitFull;
            }
            else
            {
                department[RefStaff.Units.Name]     = unit;
                department[RefStaff.Units.FullName] = unitFull;
            }
            department[RefStaff.Units.Code] = unitId;

            //Руководитель подразделения
            if (chief != string.Empty)
            {
                try{
                    UpdateDepartmentChief(department, refStaffData, chief);
                }
                catch {
                    refStaffData.EndUpdate();
                    return("Руководитель не найден.");
                }
            }

            //Куратор подразделения
            if (curator != string.Empty)
            {
                try{
                    UpdateDepartmentCurator(department, refStaffData, curator);
                }
                catch {
                    refStaffData.EndUpdate();
                    return("Куратор не найден.");
                }
            }

            refStaffData.EndUpdate();

            //return "Департамент обновлен";
            return(true);
        }
        catch {
            return("Ошибка при попытке обновить подразделение. Необходимо перезапустить сервис!");
        }
    }
Example #24
0
    //Подразделения
    //im public string AddDepartment(string unitId, string unit, string unitFull, string ownerId, string chief, string curator)
    public object AddDepartment(string unitId, string unit, string unitFull, string ownerId, string chief, string curator)
    {
        try{
            if (string.IsNullOrEmpty(unit))
            {
                //logger.Info(string.Format(base.LogEmptyInfo, "Unit"));
                //return string.Format(LogEmptyInfo, "Unit");
                return(true);
            }

            CardData refStaffData = Session.CardManager.GetDictionaryData(RefStaff.ID);

            SectionData unitsSection = refStaffData.Sections[RefStaff.Units.ID];

            //im RowData department = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, unitId);
            RowDataCollection departmentColl = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, unitId);
            if (departmentColl == null || departmentColl.Count == 0)
            {
                RowData unitRow = null;

                //Поиск по родителю

                if (!String.IsNullOrEmpty(ownerId))
                {
                    //im unitRow = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, ownerId);
                    RowDataCollection unitRowColl = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, ownerId);
                    if (unitRowColl != null)
                    {
                        unitRow = unitRowColl[0];
                    }
                }

                if (unitRow == null)
                {
                    unitRow = unitsSection.GetRow(new Guid(ConfigurationManager.AppSettings["RootDepartmentGuid"]));                     //Нужно брать по известному ID подразделения
                }
                RowDataCollection departmentRows = unitRow.ChildRows;

                refStaffData.BeginUpdate();

                var newRowDepartment = departmentRows.AddNew();
                var isFirstLoad      = ConfigurationManager.AppSettings["FirstLoad"];
                if (isFirstLoad == "1")
                {
                    newRowDepartment[RefStaff.Units.Name]     = unit;
                    newRowDepartment[RefStaff.Units.FullName] = unitFull;
                }
                else
                {
                    newRowDepartment[RefStaff.Units.Name]     = unit;
                    newRowDepartment[RefStaff.Units.FullName] = unitFull;
                }
                newRowDepartment[RefStaff.Units.Code] = unitId;
                newRowDepartment[RefStaff.Units.Type] = StaffUnitType.Department;

                //Руководитель подразделения

                /*im
                 * UpdateDepartmentChief(newRowDepartment, refStaffData, chief);
                 */
                if (!String.IsNullOrEmpty(chief))
                {
                    //im unitRow = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, ownerId);
                    RowDataCollection unitRowColl = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, chief);
                    if (unitRowColl != null)
                    {
                        unitRow = unitRowColl[0];
                    }
                }
                //Куратор подразделения

                /*
                 * UpdateDepartmentCurator(newRowDepartment, refStaffData, curator);
                 */
                if (!String.IsNullOrEmpty(curator))
                {
                    //im unitRow = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, ownerId);
                    RowDataCollection unitRowColl = GetExistObject(RefStaff.Units.ID, RefStaff.Units.Code, curator);
                    if (unitRowColl != null)
                    {
                        unitRow = unitRowColl[0];
                    }
                }

                refStaffData.EndUpdate();
                //return "Департамент добавлен";
                return(true);
            }
            else
            {
                //return "Подразделение уже добавлено";
                return(true);
            }
        }
        catch {
            CardData refStaffData = Session.CardManager.GetDictionaryData(RefStaff.ID);
            refStaffData.BeginUpdate();
            refStaffData.EndUpdate();
            return("Ошибка при попытке добавить новое подразделение. Необходимо перезапустить сервис!");
            //return false;
        }
    }
Example #25
0
        private void CardControl_Saving(Object sender, CancelEventArgs e)
        {
            try
            {
                /* Переформирование файлов */
                for (Int32 i = 0; i < Table_Service.RowCount; i++)
                {
                    BaseCardProperty   Row    = Table_Service[i];
                    ServiceTableChange Change = Dic_Changes.Find(Row[RefApplicationCard.Service.Id].ToGuid());
                    if (Change.FileIsChanged || Row[RefApplicationCard.Service.PackedListID].ToGuid().IsEmpty())
                    {
                        Guid FileId = Row[RefApplicationCard.Service.PackedListID].ToGuid();
                        AccountCard.FillPackFile(Context, UniversalCard.GetItemName(Row[RefApplicationCard.Service.DeviceID].ToGuid()), Row[RefApplicationCard.Service.PackedListData] as String, ref FileId);
                        Row[RefApplicationCard.Service.PackedListID] = FileId;
                        Table_Service.RefreshRow(i);
                    }
                    if (Change.DeviceNumberId.IsChanged)
                    {
                        if (!Change.DeviceNumberId.OldValue.IsEmpty())
                        {
                            UniversalCard.GetItemRow(Change.DeviceNumberId.OldValue).SetDeviceState(DeviceState.Operating);
                        }
                        if (!Change.DeviceNumberId.NewValue.IsEmpty())
                        {
                            UniversalCard.GetItemRow(Change.DeviceNumberId.NewValue).SetDeviceState(DeviceState.OnTheWay);
                        }
                    }
                    if (Change.Sensors.IsChanged)
                    {
                        if (!String.IsNullOrEmpty(Change.Sensors.OldValue))
                        {
                            foreach (String Sensor in Change.Sensors.OldValue.Split(';'))
                            {
                                UniversalCard.GetSensorRow(Sensor).SetDeviceState(DeviceState.Operating);
                            }
                        }
                        if (!String.IsNullOrEmpty(Change.Sensors.NewValue))
                        {
                            foreach (String Sensor in Change.Sensors.NewValue.Split(';'))
                            {
                                UniversalCard.GetSensorRow(Sensor).SetDeviceState(DeviceState.OnTheWay);
                            }
                        }
                    }
                }

                /* Синхронизация */
                if (Dic_Changes.IsChanged())
                {
                    ReferenceList   RefList      = Context.GetObject <ReferenceList>(GetControlValue(RefApplicationCard.MainInfo.Links).ToGuid());
                    List <CardData> AccountCards = new List <CardData>();
                    /* Получение карточек */
                    foreach (ReferenceListReference Link in RefList.References)
                    {
                        if (Link.CardType.Equals(RefAccountCard.ID))
                        {
                            CardData AccountCard = CardScript.Session.CardManager.GetCardData(Link.Card);
                            CardLock CardLock    = CardScript.GetCardLock(AccountCard);
                            if (!CardLock.IsFree)
                            {
                                throw new MyException("Договор/счет «" + CardLock.CardDescription + "» заблокирован " + (CardLock.IsMine ? "вами!" : "пользователем «" + CardLock.AccountName + "»!"));
                            }
                            AccountCards.Add(AccountCard);
                        }
                    }
                    for (Int32 i = 0; i < AccountCards.Count; i++)
                    {
                        RefList = Context.GetObject <ReferenceList>(AccountCards[i].Sections[RefAccountCard.MainInfo.ID].FirstRow.GetGuid(RefAccountCard.MainInfo.LinkListId));

                        List <CardData> ShipmentTasks = new List <CardData>(),
                                        CompleteTasks = new List <CardData>();

                        /* Получение карточек */
                        foreach (ReferenceListReference Link in RefList.References)
                        {
                            if (Link.CardType.Equals(RefShipmentCard.ID))
                            {
                                CardData ShipmentTask = CardScript.Session.CardManager.GetCardData(Link.Card);
                                CardLock CardLock     = CardScript.GetCardLock(ShipmentTask);
                                if (!CardLock.IsFree)
                                {
                                    throw new MyException("Задание на отгрузку «" + CardLock.CardDescription + "» заблокировано " + (CardLock.IsMine ? "вами!" : "пользователем «" + CardLock.AccountName + "»!"));
                                }
                                ShipmentTasks.Add(ShipmentTask);
                                CardData CompleteTask = CardScript.Session.CardManager.GetCardData(ShipmentTask.Sections[RefShipmentCard.MainInfo.ID].FirstRow.GetGuid(RefShipmentCard.MainInfo.CompleteTaskId).ToGuid());
                                CardLock = CardScript.GetCardLock(CompleteTask);
                                if (!CardLock.IsFree)
                                {
                                    throw new MyException("Задание на комплектацию «" + CardLock.CardDescription + "» заблокировано " + (CardLock.IsMine ? "вами!" : "пользователем «" + CardLock.AccountName + "»!"));
                                }
                                CompleteTasks.Add(CompleteTask);
                            }
                        }

                        if (AccountCards[i].InUpdate)
                        {
                            AccountCards[i].CancelUpdate();
                        }

                        RowDataCollection AccountServiceRows     = AccountCards[i].Sections[RefAccountCard.Service.ID].Rows;
                        RowDataCollection AccountAddCompleteRows = AccountCards[i].Sections[RefAccountCard.AddComplete.ID].Rows;

                        for (Int32 j = 0; j < Table_Service.RowCount; j++)
                        {
                            BaseCardProperty   Row        = Table_Service[i];
                            ServiceTableChange Change     = Dic_Changes.Find(Row[RefApplicationCard.Service.Id].ToGuid());
                            RowData            ServiceRow = AccountServiceRows.Find(RefAccountCard.Service.Id, Change.RowId);
                            if (Change.IsChanged && !ServiceRow.IsNull())
                            {
                                if (Change.Warranty.IsChanged)
                                {
                                    ServiceRow.SetBoolean(RefAccountCard.Service.Warranty, Change.Warranty.NewValue);
                                }
                                if (Change.DeviceId.IsChanged)
                                {
                                    ServiceRow.SetGuid(RefAccountCard.Service.DeviceId, Change.DeviceId.NewValue);
                                }
                                if (Change.AC.IsChanged)
                                {
                                    ServiceRow.SetBoolean(RefAccountCard.Service.AC, Change.AC.NewValue);
                                }
                                if (Change.FileIsChanged)
                                {
                                    ServiceRow.SetString(RefAccountCard.Service.ACList, Row[RefApplicationCard.Service.ACList] as String);
                                    ServiceRow.SetString(RefAccountCard.Service.PackedListData, Row[RefApplicationCard.Service.PackedListData] as String);
                                    ServiceRow.SetGuid(RefAccountCard.Service.PackedListId, Row[RefApplicationCard.Service.PackedListData].ToGuid());

                                    RowDataCollection AddCompleteRows    = AccountAddCompleteRows.Filter("@" + RefAccountCard.AddComplete.ParentTableRowId + " = '" + Change.RowId.ToString().ToUpper() + "'");
                                    List <String>     AccountComlete     = AddCompleteRows.Select(r => r.GetString(RefAccountCard.AddComplete.Name)).ToList();
                                    List <String>     ApplicationComlete = new List <String>();
                                    for (Int32 k = 0; k < Table_AddComplete.RowCount; k++)
                                    {
                                        if (Table_AddComplete[k][RefApplicationCard.AddComplete.ParentTableRowId].ToGuid().Equals(Change.RowId))
                                        {
                                            ApplicationComlete.Add(Table_AddComplete[k][RefApplicationCard.AddComplete.Name] as String);
                                        }
                                    }

                                    for (Int32 k = 0; k < AddCompleteRows.Count; k++)
                                    {
                                        if (!ApplicationComlete.Contains(AddCompleteRows[k].GetString(RefAccountCard.AddComplete.Name)))
                                        {
                                            AccountCards[i].Sections[RefAccountCard.AddComplete.ID].DeleteRow(AddCompleteRows[k].Id);
                                        }
                                    }

                                    for (Int32 k = 0; k < Table_AddComplete.RowCount; k++)
                                    {
                                        if (Table_AddComplete[k][RefApplicationCard.AddComplete.ParentTableRowId].ToGuid().Equals(Change.RowId))
                                        {
                                            RowData AddCompleteRow = AddCompleteRows.Find(RefAccountCard.AddComplete.Name, Table_AddComplete[k][RefApplicationCard.AddComplete.Name] as String);
                                            if (AddCompleteRow.IsNull())
                                            {
                                                AddCompleteRow = AccountCards[i].Sections[RefAccountCard.AddComplete.ID].Rows.AddNew();
                                                AddCompleteRow.SetInt32(RefAccountCard.AddComplete.Ordered, 0);
                                            }
                                            AddCompleteRow.SetInt32(RefAccountCard.AddComplete.Count, (Int32?)Table_AddComplete[k][RefApplicationCard.AddComplete.Count]);
                                            AddCompleteRow.SetGuid(RefAccountCard.AddComplete.Id, Table_AddComplete[k][RefApplicationCard.AddComplete.Id].ToGuid());
                                            AddCompleteRow.SetString(RefAccountCard.AddComplete.Name, Table_AddComplete[k][RefApplicationCard.AddComplete.Name] as String);
                                            AddCompleteRow.SetString(RefAccountCard.AddComplete.Code, Table_AddComplete[k][RefApplicationCard.AddComplete.Code] as String);
                                        }
                                    }
                                }
                            }
                        }

                        for (Int32 j = 0; j < ShipmentTasks.Count; j++)
                        {
                            if (ShipmentTasks[j].LockStatus == LockStatus.Free && CompleteTasks[j].LockStatus == LockStatus.Free)
                            {
                                if (ShipmentTasks[j].InUpdate)
                                {
                                    ShipmentTasks[j].CancelUpdate();
                                }
                                if (CompleteTasks[j].InUpdate)
                                {
                                    CompleteTasks[j].CancelUpdate();
                                }

                                RowDataCollection ShipmentDevicesRows = ShipmentTasks[j].Sections[RefShipmentCard.Devices.ID].Rows;
                                RowDataCollection CompleteDevicesRows = CompleteTasks[j].Sections[RefCompleteCard.Devices.ID].Rows;

                                foreach (RowData DevicesRow in ShipmentDevicesRows)
                                {
                                    ServiceTableChange Change = Dic_Changes.Find(DevicesRow.GetGuid(RefShipmentCard.Devices.AccountCardRowId).ToGuid());
                                    if (!Change.IsNull() && Change.IsChanged)
                                    {
                                        RowDataCollection CompleteRows = CompleteDevicesRows.Filter("@" + RefCompleteCard.Devices.ShipmentTaskRowId + " = '" + DevicesRow.GetGuid(RefShipmentCard.Devices.Id).ToString().ToUpper() + "'");
                                        /* Изменение связных полей */
                                        if (Change.Warranty.IsChanged)
                                        {
                                            DevicesRow.SetBoolean(RefShipmentCard.Devices.Warranty, Change.Warranty.NewValue);
                                            foreach (RowData CompleteRow in CompleteRows)
                                            {
                                                CompleteRow.SetBoolean(RefCompleteCard.Devices.Warranty, Change.Warranty.NewValue);
                                            }
                                        }
                                        if (Change.AC.IsChanged)
                                        {
                                            DevicesRow.SetBoolean(RefShipmentCard.Devices.AC, Change.AC.NewValue);
                                            foreach (RowData CompleteRow in CompleteRows)
                                            {
                                                CompleteRow.SetBoolean(RefCompleteCard.Devices.AC, Change.AC.NewValue);
                                            }
                                        }
                                        if (Change.DeviceId.IsChanged)
                                        {
                                            DevicesRow.SetGuid(RefShipmentCard.Devices.DeviceId, Change.DeviceId.NewValue);
                                            foreach (RowData CompleteRow in CompleteRows)
                                            {
                                                CompleteRow.SetGuid(RefCompleteCard.Devices.DeviceId, Change.DeviceId.NewValue);
                                            }
                                        }
                                        if (Change.FileIsChanged)
                                        {
                                            DevicesRow.SetBoolean(RefShipmentCard.Devices.IsChanged, Change.FileIsChanged);
                                            for (Int32 k = 0; k < Table_Service.RowCount; k++)
                                            {
                                                if (Table_Service[k][RefApplicationCard.Service.Id].ToGuid().Equals(Change.RowId))
                                                {
                                                    DevicesRow.SetGuid(RefShipmentCard.Devices.TemplatePackListId, Table_Service[k][RefApplicationCard.Service.PackedListID].ToGuid());
                                                }
                                            }
                                        }

                                        /* Очистка связных полей */
                                        if (Change.DeviceId.IsChanged || Change.AC.IsChanged)
                                        {
                                            DevicesRow.SetString(RefShipmentCard.Devices.DeviceNumbers, null);
                                            DevicesRow.SetString(RefShipmentCard.Devices.PartyNumbers, null);
                                            DevicesRow.SetString(RefShipmentCard.Devices.Coupons, null);

                                            foreach (RowData CompleteRow in CompleteRows)
                                            {
                                                try
                                                {
                                                    Guid DeviceNumberId = CompleteRow.GetObject(RefCompleteCard.Devices.DeviceNumberId).ToGuid();
                                                    /* Очистка приборов */
                                                    if (!DeviceNumberId.IsEmpty())
                                                    {
                                                        try { UniversalCard.GetItemRow(DeviceNumberId).UpdateDeviceInformation(UniversalCard, CompleteRow.GetBoolean(RefCompleteCard.Devices.AS)); }
                                                        catch (MyException Ex)
                                                        {
                                                            switch (Ex.ErrorCode)
                                                            {
                                                            case -1:
                                                                WriteLog("Ошибка: предвиденное исключение" + "\r\n" + Ex.Message + "\r\n" + Ex.StackTrace);
                                                                WriteLog("Ошибка: предвиденное исключение" + "\r\n" + Ex.InnerException.Message + "\r\n" + Ex.InnerException.StackTrace);
                                                                break;

                                                            case 0:
                                                                WriteLog("Ошибка: предвиденное исключение" + "\r\n" + Ex.Message + "\r\n" + Ex.StackTrace);
                                                                break;

                                                            case 1:
                                                                String[] ss = Ex.Message.Split('\t');
                                                                WriteLog("Ошибка: предвиденное исключение" + "\r\n" + (ss.Length >= 2 ? "В карточке " + ss[1] + " отсутствует поле: " + ss[0] : Ex.Message) + "\r\n" + Ex.StackTrace);
                                                                WriteLog("Ошибка: предвиденное исключение" + "\r\n" + Ex.InnerException.Message + "\r\n" + Ex.InnerException.StackTrace);
                                                                break;
                                                            }
                                                        }
                                                    }

                                                    CompleteRow.SetGuid(RefCompleteCard.Devices.DeviceNumberId, Guid.Empty);
                                                    CompleteRow.SetString(RefCompleteCard.Devices.DeviceNumber, null);
                                                    CompleteRow.SetGuid(RefCompleteCard.Devices.CouponId, Guid.Empty);
                                                }
                                                catch (Exception Ex) { WriteLog("Ошибка: непредвиденное исключение" + "\r\n" + Ex.Message + "\r\n" + Ex.StackTrace); }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (ArgumentNullException Ex)
            {
                MyMessageBox.Show("Поле \"" + Ex.ParamName + "\" обязательно к заполнению!", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Cancel = true;
            }
            catch (MyException Ex)
            {
                MyMessageBox.Show(Ex.Message + Environment.NewLine + "Синхронизация связных карточек не произойдет.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Cancel = true;
            }
            catch (Exception Ex) { CallError(Ex); }
        }