/// <summary>
        /// Получить данные строк таблицы.
        /// </summary>
        /// <param name="ParentDocument"> Родительский документ (из которого выгружаются данные). </param>
        /// <param name="SensorsNumber"> Заводской номер датчика. </param>
        /// <returns></returns>
        public List <TablesRow> GetRows(WordprocessingDocument ParentDocument, string SensorsNumber)
        {
            Table CurrentTable = ParentDocument == null ? null : ParentDocument.GetTable(ParentTableName);

            string RodInfo    = "";
            string RodLength  = CurrentTable.GetCellValue(5, 1).ToString() == "Выберите длину" ? "" : CurrentTable.GetCellValue(5, 1).ToString(); // Длина стержня
            string RodNumber  = CurrentTable.GetCellValue(6, 1).ToString() == "Введите номер" ? "" : CurrentTable.GetCellValue(6, 1).ToString();  // Номер стержня
            string ErrorValue = CurrentTable.GetCellValue(3, 1).ToString();                                                                       // Максимальная погрешность

            if ((RodLength != "") && (RodNumber != ""))
            {
                RodInfo = "в комплекте со стержнем длиной " + RodLength + ", № " + RodNumber;
            }

            List <TablesRow> Collection = new List <TablesRow>();

            Variables = new string[] { SensorsNumber, RodInfo, ErrorValue };

            foreach (TablesRow Row in Rows)
            {
                string[] Values = new string[Row.Values.Count()];
                for (int i = 0; i < Row.Values.Count(); i++)
                {
                    Values[i] = ConvertData(Row.Values[i], CurrentTable);
                }
                Collection.Add(new TablesRow(Values, Row.GridSpan, Row.VerticalMerge, Row.Type, Row.JoinToRow));
            }
            return(Collection);
        }
Пример #2
0
        static void FillBookmarks(WordprocessingDocument Certificate, string DeviceType, string DeviceNumber, string DeviceNumber2, string ReceiptDate, string ClientName,
                                  string CalibrationDate, string CalibrationMethods, string Temperature, string Humidity, string AtmospherePressure, string CalibrationMeans)
        {
            CalibrationLib.ChangeCellsWidth(Certificate.GetTable("СЕРТИФИКАТ О КАЛИБРОВКЕ №"), 3, 0, DeviceType.Length);

            Dictionary <String, BookmarkStart> BookmarkDic = new Dictionary <String, BookmarkStart>();

            foreach (BookmarkStart Bookmark in Certificate.MainDocumentPart.RootElement.Descendants <BookmarkStart>())
            {
                BookmarkDic[Bookmark.Name] = Bookmark;
            }

            /* Запись закладочных полей */
            BookmarkDic["DeviceType"].WriteText(DeviceType);
            BookmarkDic["DeviceNumber"].WriteText(DeviceNumber);
            BookmarkDic["DeviceNumber2"].WriteText(DeviceNumber2);
            BookmarkDic["ReceiptDate"].WriteText(ReceiptDate);

            /*if (ClientName.Length > 55)
             * {
             *  int Length1 = ClientName.Substring(0, 50).LastIndexOf(" ");
             *  string Text1 = ClientName.Substring(0, Length1);
             *  BookmarkDic["ClientName"].WriteText(Text1);
             *
             *  ClientName = ClientName.Substring(Length1 + 1);
             *  Paragraph paragraph = (Paragraph)BookmarkDic["ClientName"].Parent;
             *  TableCell tableCell = (TableCell)paragraph.Parent;
             *  TableRow tableRow = (TableRow)tableCell.Parent;
             *  Table table = (Table)tableRow.Parent;
             *  int RowIndex = table.Elements().ToList().IndexOf(tableRow);
             *
             *  while (ClientName.Length > 90)
             *  {
             *      int LineLength = ClientName.Substring(0, 90).LastIndexOf(" ");
             *      string Text = ClientName.Substring(0, LineLength);
             *      ClientName = ClientName.Substring(LineLength + 1);
             *
             *      table.InsertLineForClient(RowIndex + 1, Text);
             *      RowIndex++;
             *  }
             *  table.InsertLineForClient(RowIndex + 1, ClientName);
             * }
             * else
             * {
             *  BookmarkDic["ClientName"].WriteText(ClientName);
             * }*/

            BookmarkDic["CalibrationDate"].WriteText(CalibrationDate);
            BookmarkDic["CalibrationMethods"].WriteText(CalibrationMethods);
            BookmarkDic["Temperature"].WriteText(Temperature);
            BookmarkDic["Humidity"].WriteText(Humidity);
            BookmarkDic["AtmospherePressure"].WriteText(AtmospherePressure);
            BookmarkDic["CalibrationMeans"].WriteText(CalibrationMeans);
        }
        static void AddSensorTables(WordprocessingDocument Protocol, UserSession Session, TablesCreator Creator, string SensorType, CardData SensorCard,
                                    DateTime StartDateOfService, string DeviceTypeName)
        {
            string SensorNumber = SensorCard.GetDeviceNumber();
            IEnumerable <VerificationProtocolTableLook> TablesCollection = Creator.VerificationProtokolSensorTablesCollection.Where(r => r.DeviceTypes.Any(s => s == SensorType));

            if (TablesCollection.Count() == 0)
            {
                XtraMessageBox.Show("Для датчика '" + SensorType + "' не найден шаблон таблицы. Обратитесь к системному администратору.");
            }
            else
            {
                foreach (VerificationProtocolTableLook CurrentTable in TablesCollection)
                {
                    WordprocessingDocument ParentDocument;
                    string TempPath = "";
                    switch (CurrentTable.ParentDocumentCategory)
                    {
                    case VerificationProtocolTableLook.DocumentCategory.AcceptanceTestingProtocol:
                        ParentDocument = CalibrationLib.GetDocument(Session, SensorCard, CalibrationLib.AcceptanceTestingProtocolCategoryID, out TempPath);
                        break;

                    case VerificationProtocolTableLook.DocumentCategory.CalibrationProtocol:
                        ParentDocument = CalibrationLib.GetDocument(Session, SensorCard, CalibrationLib.CalibrationProtocolCategoryID, out TempPath);
                        break;

                    case VerificationProtocolTableLook.DocumentCategory.MeasuringData:
                        ParentDocument = CalibrationLib.GetDocument(Session, SensorCard, CalibrationLib.MeasuringDataCategoryID, out TempPath);
                        break;

                    default:
                        ParentDocument = null;
                        break;
                    }

                    Table NewSensorTable = CurrentTable.GetSensorsTable(ParentDocument, SensorNumber, DeviceTypeName);

                    AddNewTable(Protocol, NewSensorTable, Protocol.GetTable("Заключение:").ElementsBefore().Last());
                    if (ParentDocument != null)
                    {
                        ParentDocument.Close();
                        File.Delete(TempPath);
                    }
                }
            }
            return;
        }
        /// <summary>
        /// Получить данные строк таблицы
        /// </summary>
        /// <param name="ParentDocument"> Родительский документ (из которого выгружаются данные).</param>
        /// <returns></returns>
        public List <TablesRow> GetRows(WordprocessingDocument ParentDocument)
        {
            Table CurrentTable = ParentDocument == null ? null : ParentDocument.GetTable(ParentTableName);

            List <TablesRow> Collection = new List <TablesRow>();

            string TermNumber = CurrentTable != null?CurrentTable.GetCellValue(1, 1).ToString() : "";

            Variables = new string[] { TermNumber };

            foreach (TablesRow Row in Rows)
            {
                string[] Values = new string[Row.Values.Count()];
                for (int i = 0; i < Row.Values.Count(); i++)
                {
                    Values[i] = this.ConvertData(Row.Values[i], CurrentTable);
                }
                Collection.Add(new TablesRow(Values, Row.GridSpan, Row.VerticalMerge, Row.Type, Row.JoinToRow));
            }
            return(Collection);
        }
        /// <summary>
        /// Получить данные строки таблицы.
        /// </summary>
        /// <param name="ParentDocument"> Родительский документ (Из которого выгружаются данные). </param>
        /// <param name="SensorsNumber"> Заводской номер датчика. </param>
        /// <returns></returns>
        public List <TablesRow> GetRows(WordprocessingDocument ParentDocument, string SensorsNumber)
        {
            Table CurrentTable = ParentDocument == null ? null : ParentDocument.GetTable(ParentTableName);

            List <TablesRow> Collection = new List <TablesRow>();

            #region // Определяем максимальную погрешность из файла с даными измерений.
            double ErrorValue = Math.Round(Convert.ToDouble(CurrentTable.GetCellValue(3, 1)), 2);

            #endregion

            #region // Определяем вариацию из файла с даными измерений.
            double Variation = Math.Round(Convert.ToDouble(CurrentTable.GetCellValue(2, 1)), 2);
            // Преобразуем вариацию к требуемому виду: вариация должна принимать значения от 0 до 0.3 с шагом 0.05.
            for (double j = 0; j < 0.45; j = j + 0.05d)
            {
                double y = j + 0.05d;
                if ((Variation > j) && (Variation <= y))
                {
                    if (Math.Abs(Variation - j) < Math.Abs(Variation - y))
                    {
                        Variation = j;
                        break;
                    }
                    else
                    {
                        Variation = y >= 0.3 ? 0.3 : y;
                        break;
                    }
                }
            }
            #endregion

            #region                                                                                                                              // Получение информации об измерительном стержне.
            string RodInfo   = "";
            string RodLength = CurrentTable.GetCellValue(5, 1).ToString() == "Выберите длину" ? "" : CurrentTable.GetCellValue(5, 1).ToString(); // Длина стержня (текст)
            string RodNumber = CurrentTable.GetCellValue(6, 1).ToString() == "Введите номер" ? "" : CurrentTable.GetCellValue(6, 1).ToString();  // Номер стержня
            if ((RodLength != "") && (RodNumber != ""))
            {
                RodInfo = "в комплекте с измерительным стержнем длиной " + RodLength + ", № " + RodNumber;
            }
            #endregion

            #region // Определяем измеренные значения
            switch (RodLength)
            {
            case "500 мм":
                RandomMeasuredValue[0] = Math.Round(Math.Round(500d * (1d / 3d), 1) + (RandomMeasuredValue[0] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[1] = Math.Round(Math.Round(500d * (2d / 3d), 1) + (RandomMeasuredValue[1] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[2] = Math.Round(Math.Round(500d * (4d / 5d), 1) + (RandomMeasuredValue[2] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                break;

            case "500":
                RandomMeasuredValue[0] = Math.Round(Math.Round(500d * (1d / 3d), 1) + (RandomMeasuredValue[0] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[1] = Math.Round(Math.Round(500d * (2d / 3d), 1) + (RandomMeasuredValue[1] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[2] = Math.Round(Math.Round(500d * (4d / 5d), 1) + (RandomMeasuredValue[2] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                break;

            case "700 мм":
                RandomMeasuredValue[0] = Math.Round(Math.Round(700d * (1d / 3d), 1) + (RandomMeasuredValue[0] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[1] = Math.Round(Math.Round(700d * (2d / 3d), 1) + (RandomMeasuredValue[1] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[2] = Math.Round(Math.Round(700d * (4d / 5d), 1) + (RandomMeasuredValue[2] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                break;

            case "700":
                RandomMeasuredValue[0] = Math.Round(Math.Round(700d * (1d / 3d), 1) + (RandomMeasuredValue[0] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[1] = Math.Round(Math.Round(700d * (2d / 3d), 1) + (RandomMeasuredValue[1] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[2] = Math.Round(Math.Round(700d * (4d / 5d), 1) + (RandomMeasuredValue[2] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                break;

            case "1000 мм":
                RandomMeasuredValue[0] = Math.Round(Math.Round(1000d * (1d / 3d), 1) + (RandomMeasuredValue[0] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[1] = Math.Round(Math.Round(1000d * (2d / 3d), 1) + (RandomMeasuredValue[1] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[2] = Math.Round(Math.Round(1000d * (4d / 5d), 1) + (RandomMeasuredValue[2] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                break;

            case "1000":
                RandomMeasuredValue[0] = Math.Round(Math.Round(1000d * (1d / 3d), 1) + (RandomMeasuredValue[0] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[1] = Math.Round(Math.Round(1000d * (2d / 3d), 1) + (RandomMeasuredValue[1] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                RandomMeasuredValue[2] = Math.Round(Math.Round(1000d * (4d / 5d), 1) + (RandomMeasuredValue[2] * (RandomValue.Next(0, 2) == 1 ? 1 : -1)), 0) + (RandomValue.Next(0, 2) == 1 ? 0 : 0.5d);
                break;
            }
            #endregion

            #region // Определяем значения погрешности.
            if (RodInfo != "")
            {
                // Преобразуем суммарную погрешность к требуемому виду: погрешность должна принимать значения от -1 до 1 с шагом 0.05.
                for (double i = -1; i < 1; i = Math.Round(i + 0.05d, 2))
                {
                    double x = Math.Round(i + 0.05d, 2);
                    if ((ErrorValue > i) && (ErrorValue <= x))
                    {
                        if (Math.Abs(ErrorValue - i) < Math.Abs(ErrorValue - x))
                        {
                            ErrorValue = i == -1 ? x : i;
                            break;
                        }
                        else
                        {
                            ErrorValue = x == 1 ? i : x;
                            break;
                        }
                    }
                }
            }

            double   MaxError       = RodInfo != "" ? Math.Round(Math.Abs(ErrorValue) - 0.5 - Variation, 2) : Math.Round(Math.Abs(ErrorValue) - 0.09, 2);
            double[] NewRandomError = new double[RandomMeasuredValue.Length];
            int      RandomIndex    = RandomValue.Next(0, RandomMeasuredValue.Length - 1);

            for (int i = 0; i < NewRandomError.Count(); i++)
            {
                if (i == RandomIndex)
                {
                    NewRandomError[i] = ErrorValue > 0 ? MaxError : MaxError * -1;
                }
                else
                {
                    double RandValue = MaxError;

                    if (RodInfo != "")
                    {
                        int steps = Convert.ToInt32(Math.Round(MaxError / 0.05d, 0));
                        RandValue         = Math.Round(0.05 * RandomValue.Next(0, steps), 2);
                        NewRandomError[i] = RandomValue.Next(0, 2) == 1 ? RandValue : Math.Round(RandValue * -1, 2);
                    }
                    else
                    {
                        while (RandValue >= MaxError)
                        {
                            RandValue = Math.Round(RandomValue.NextDouble(), 2);
                        }
                        NewRandomError[i] = RandomValue.Next(0, 2) == 1 ? MaxError - RandValue : (MaxError - RandValue) * -1;
                    }
                }
            }
            RandomError = NewRandomError;
            #endregion

            // Определение рассчитанных переменных.
            Variables = new string[] { SensorsNumber, Variation.ToString(), ErrorValue.ToString(), RodInfo };
            // Получение данных таблицы на основе шаблона.
            foreach (TablesRow Row in Rows)
            {
                string[] Values = new string[Row.Values.Count()];
                for (int i = 0; i < Row.Values.Count(); i++)
                {
                    Values[i] = ConvertData(Row.Values[i], CurrentTable);
                }
                Collection.Add(new TablesRow(Values, Row.GridSpan, Row.VerticalMerge, Row.Type, Row.JoinToRow));
            }
            return(Collection);
        }
        static void AddDeviceTables(WordprocessingDocument Protocol, UserSession Session, TablesCreator Creator, string DeviceType, CardData DeviceCard,
                                    DateTime StartDateOfService)
        {
            // Определение точек вставки таблиц для протоколов поверки разных типов приборов
            IEnumerable <VerificationProtocolTableLook> TablesCollection = Creator.VerifyProtokolDeviceTablesCollection.Where(r => r.DeviceTypes.Any(s => s == DeviceType));

            if (TablesCollection.Count() > 0)
            {
                OpenXmlElement IncertElement = Protocol.GetTable("Заключение:").ElementsBefore().Last();
                switch (DeviceType)
                {
                case "ПКВ/М7":
                    IncertElement = Protocol.GetTable("Определение основной абсолютной погрешности измерений интервалов времени").ElementsBefore().Last();
                    break;

                case "ПКВ/У3.0":
                    IncertElement = Protocol.GetTable("Определение основной абсолютной погрешности измерений интервалов времени").ElementsBefore().Last();
                    break;

                case "ПКВ/У3.1":
                    IncertElement = Protocol.GetTable("Определение основной абсолютной погрешности измерений интервалов времени").ElementsBefore().Last();
                    break;

                case "ПКВ/У3.0-01":
                    IncertElement = Protocol.GetTable("Определение основной абсолютной погрешности измерений интервалов времени").ElementsBefore().Last();
                    break;

                /*case "МИКО-2.2":
                 *  IncertElement = Protocol.GetTable("Определение метрологических характеристик").ElementsAfter().First();
                 *  break;
                 * case "МИКО-2.3":
                 *  IncertElement = Protocol.GetTable("Определение метрологических характеристик").ElementsAfter().First();
                 *  break;*/
                case "МИКО-7":
                    IncertElement = Protocol.GetTable("7. Проверка ограничения выходной мощности").ElementsBefore().Last();
                    break;

                    /*case "МИКО-21":
                     *  IncertElement = Protocol.GetTable("Заключение:").ElementsAfter().First();
                     *  break;*/
                }
                //OpenXmlElement IncertElement = Protocol.GetTable("Определение основной абсолютной погрешности измерений силы постоянного электрического тока каналами ВКЛ и ОТКЛ силового коммутатора").ElementsAfter().First();
                Dictionary <String, Table> TablesList = new Dictionary <String, Table>();
                foreach (VerificationProtocolTableLook CurrentTable in TablesCollection)
                {
                    //WordprocessingDocument ParentDocument;
                    string ParentDocumentPath = "";
                    switch (CurrentTable.ParentDocumentCategory)
                    {
                    case VerificationProtocolTableLook.DocumentCategory.AcceptanceTestingProtocol:
                        ParentDocumentPath = CalibrationLib.GetDocumentPath(Session, DeviceCard, CalibrationLib.AcceptanceTestingProtocolCategoryID);
                        break;

                    case VerificationProtocolTableLook.DocumentCategory.CalibrationProtocol:
                        ParentDocumentPath = CalibrationLib.GetDocumentPath(Session, DeviceCard, CalibrationLib.CalibrationProtocolCategoryID);
                        break;

                    case VerificationProtocolTableLook.DocumentCategory.MeasuringData:
                        ParentDocumentPath = CalibrationLib.GetDocumentPath(Session, DeviceCard, CalibrationLib.MeasuringDataCategoryID);
                        break;

                    default:
                        ParentDocumentPath = "";
                        break;
                    }

                    if (ParentDocumentPath.EndsWith(".docx"))
                    {
                        WordprocessingDocument ParentDocument = WordprocessingDocument.Open(ParentDocumentPath, true);

                        if (TablesList.Any(r => r.Key == CurrentTable.TableName))
                        {
                            CurrentTable.AdditionDeviceTable(ParentDocument, TablesList.First(r => r.Key == CurrentTable.TableName).Value);
                        }
                        else
                        {
                            TablesList.Add(CurrentTable.TableName, CurrentTable.GetDeviceTable(ParentDocument));
                        }

                        if (ParentDocument != null)
                        {
                            ParentDocument.Close();
                        }
                    }
                    if (ParentDocumentPath.EndsWith(".json"))
                    {
                        string     fileContent  = File.ReadAllText(ParentDocumentPath);
                        RootObject MeashureData = JsonConvert.DeserializeObject <RootObject>(fileContent);
                        TablesList.Add(CurrentTable.TableName, CurrentTable.GetDeviceTable(MeashureData));
                    }
                    File.Delete(ParentDocumentPath);
                }

                foreach (KeyValuePair <String, Table> T in TablesList)
                {
                    AddNewTable(Protocol, T.Value, IncertElement);
                }
            }
        }
        /// <summary>
        /// Добавить в протокол таблицу с данными измерений датчика.
        /// </summary>
        /// <param name="Protocol">Документ протокола</param>
        /// <param name="Session">пользовательская сессия.</param>
        /// <param name="Creator">Объект создателя таблиц.</param>
        /// <param name="SensorType">Тип датчика.</param>
        /// <param name="SensorCard">Карточка датчика.</param>
        /// <param name="StartDateOfService">Дата начала сервисного обслуживания.</param>
        static void AddSensorTables(WordprocessingDocument Protocol, UserSession Session, TablesCreator Creator, string SensorType, CardData SensorCard,
                                    DateTime StartDateOfService)
        {
            string SensorNumber = SensorCard.GetDeviceNumber();
            IEnumerable <ProtocolTableLook> TablesCollection = Creator.ProtokolSensorTablesCollection.Where(r => r.DeviceTypes.Any(s => s == SensorType));

            if (TablesCollection.Count() == 0)
            {
                XtraMessageBox.Show("Для датчика '" + SensorType + "' не найден шаблон таблицы. Обратитесь к системному администратору.");
            }
            else
            {
                foreach (ProtocolTableLook CurrentTable in TablesCollection)
                {
                    WordprocessingDocument ParentDocument;
                    string TempPath = "";
                    switch (CurrentTable.ParentDocumentCategory)
                    {
                    case ProtocolTableLook.DocumentCategory.AcceptanceTestingProtocol:
                        ParentDocument = CalibrationLib.GetDocument(Session, SensorCard, CalibrationLib.AcceptanceTestingProtocolCategoryID, out TempPath);
                        break;

                    case ProtocolTableLook.DocumentCategory.CalibrationProtocol:
                        ParentDocument = CalibrationLib.GetDocument(Session, SensorCard, CalibrationLib.CalibrationProtocolCategoryID, out TempPath);
                        break;

                    case ProtocolTableLook.DocumentCategory.MeasuringData:
                        ParentDocument = CalibrationLib.GetDocument(Session, SensorCard, CalibrationLib.MeasuringDataCategoryID, out TempPath);
                        break;

                    default:
                        ParentDocument = null;
                        break;
                    }

                    Table NewSensorTable = CurrentTable.GetSensorsTable(ParentDocument, SensorNumber);

                    /*if (Protocol.MainDocumentPart.Document.Body.Elements<Table>().Count() > 0)
                     * {
                     *  List<OpenXmlElement> NewList = Protocol.MainDocumentPart.Document.Body.Elements().ToList();
                     *  int Index = NewList.Count - 4;
                     *  NewList.Insert(Index, CalibrationLib.NewParagraph(-113, -133, JustificationValues.Left, 11));
                     *  NewList.Insert(Index, (OpenXmlElement)NewSensorTable);
                     *  Protocol.MainDocumentPart.Document.Body.RemoveAllChildren();
                     *  foreach (OpenXmlElement Element in NewList)
                     *  { Protocol.MainDocumentPart.Document.Body.Append(Element); }
                     * }
                     * else
                     * {
                     *  SdtBlock Block = Protocol.MainDocumentPart.Document.Body.Elements<SdtBlock>().First();
                     *  SdtContentBlock ContentBlock = Block.Elements<SdtContentBlock>().First();
                     *  List<OpenXmlElement> NewList = ContentBlock.Elements().ToList();
                     *  int Index = NewList.Count - 4;
                     *  NewList.Insert(Index, CalibrationLib.NewParagraph(-113, -133, JustificationValues.Left, 11));
                     *  NewList.Insert(Index, (OpenXmlElement)NewSensorTable);
                     *  ContentBlock.RemoveAllChildren();
                     *  foreach (OpenXmlElement Element in NewList)
                     *  { ContentBlock.Append(Element); }
                     * }*/
                    AddNewTable(Protocol, NewSensorTable, Protocol.GetTable("Дата").ElementsBefore().Last());
                    if (ParentDocument != null)
                    {
                        ParentDocument.Close();
                        File.Delete(TempPath);
                    }
                }
            }
            return;
        }
Пример #8
0
        /// <summary>
        /// Заполнить данные свидетельства о поверке.
        /// </summary>
        /// <param name="Certificate"> Файл свидетельства о поверке.</param>
        /// <param name="CardScript">Скрипт.</param>
        /// <param name="Context">Объектный контекст.</param>
        /// <param name="DeviceCard">Карточка прибора.</param>
        /// <param name="ClientName">Название клиента.</param>
        /// <param name="VerificationDate">Дата поверки.</param>
        /// <param name="AdditionalWaresList">Перечень дополнительных изделий.</param>
        /// <param name="StartDateOfService">Дата поступления на поверку.</param>
        /// <param name="PreviousVerifySerialNumber">Дата поступления на поверку.</param>
        public static void FillData(WordprocessingDocument Certificate, ScriptClassBase CardScript, ObjectContext Context,
                                    CardData DeviceCard, string ClientName, DateTime VerificationDate, List <CardData> AdditionalWaresList, DateTime StartDateOfService, string PreviousVerifySerialNumber)
        {
            // Формирование сертификата
            Guid   DeviceTypeID   = DeviceCard.Sections[CardOrd.Properties.ID].FindRow("@Name = 'Прибор'").GetString(CardOrd.Properties.Value).ToGuid();
            string DeviceTypeName = ApplicationCard.UniversalCard.GetItemName(DeviceTypeID);
            string DeviceNumber   = DeviceCard.GetDeviceNumber();

            DeviceNumber = DeviceNumber.Contains("/") == true?DeviceNumber.Replace("/", " (") + " г)" : DeviceNumber;

            // Данные для заполнения закладочных полей
            string FullDeviceType         = ApplicationCard.UniversalCard.GetItemPropertyValue(DeviceTypeID, "Полное название").ToString() + " " + DeviceTypeName + ",";
            string VerificationDateString = VerificationDate.ToLongDateString();
            int    VerificationInterval   = CalibrationLib.GetVerificationInterval(ApplicationCard.UniversalCard, DeviceTypeID);
            string ValidUntil             = VerificationDate.AddMonths(VerificationInterval).AddDays(-1).ToLongDateString();
            string VerificationMethods    = ApplicationCard.UniversalCard.GetItemPropertyValue(DeviceTypeID, "Методика поверки").ToString();
            string VerificationScope      = ApplicationCard.UniversalCard.GetItemPropertyValue(DeviceTypeID, "Объем поверки") == null ? "в полном объеме" : ApplicationCard.UniversalCard.GetItemPropertyValue(DeviceTypeID, "Объем поверки").ToString();
            string Suitability            = ApplicationCard.UniversalCard.GetItemPropertyValue(DeviceTypeID, "Пригодность к применению") == null ? "" : " " + ApplicationCard.UniversalCard.GetItemPropertyValue(DeviceTypeID, "Пригодность к применению").ToString();
            string RegNum          = "ГР №" + ApplicationCard.UniversalCard.GetItemPropertyValue(DeviceTypeID, "Номер в Госреестре").ToString();
            string AdditionalWares = (AdditionalWaresList.Count > 0 ? "c датчиками " : "-") + AdditionalWaresList.Select(r =>
                                                                                                                         ApplicationCard.UniversalCard.GetItemName(r.Sections[CardOrd.Properties.ID].FindRow("@Name = 'Прибор'").GetString(CardOrd.Properties.Value).ToGuid()) + " № " + (r.GetDeviceNumber().Contains("/") == true ? r.GetDeviceNumber().Replace("/", " (") + " г)" : r.GetDeviceNumber())).Aggregate(AdditionalWaresList.Count == 2 ? " и " : ", ");
            string VerificationMeans = CalibrationLib.GetListOfMeasures(CardScript.Session, DeviceTypeID, false, true);
            // ФИО текущего сотрудника определяется из справочника сотрудников (строка отображения)
            string StaffName = Context.GetCurrentEmployee().FirstName.Substring(0, 1) + "." + Context.GetCurrentEmployee().MiddleName.Substring(0, 1) + ". " + Context.GetCurrentEmployee().LastName;
            // ФИО руководителя отдела Метрологической лаборатории определяется из справочника сотрудников по должности
            StaffEmployee MetrologicalLabManagerEmployee = Context.GetEmployeeByPosition(SKB.Base.Ref.RefServiceCard.Roles.MetrologicalLabManager);
            string        ManagerName = MetrologicalLabManagerEmployee != null?MetrologicalLabManagerEmployee.FirstName.Substring(0, 1) + "." + MetrologicalLabManagerEmployee.MiddleName.Substring(0, 1) + ". " + MetrologicalLabManagerEmployee.LastName : "";

            // Условия поверки
            string TempPath = "";
            WordprocessingDocument ParentDocument = CalibrationLib.GetDocument(CardScript.Session, DeviceCard, CalibrationLib.VerificationProtocolCategoryID, out TempPath);
            Table ParentTable = ParentDocument == null ? null : ParentDocument.GetTable("при следующих значениях влияющих факторов:");

            List <string> Collection = new List <string>();

            if (ParentTable != null)
            {
                for (int i = 1; i < ParentTable.Elements <TableRow>().Count(); i++)
                {
                    Collection.Add(ParentTable.GetCellValue(i, 1) + ": " + ParentTable.GetCellValue(i, 2) + " " + ParentTable.GetCellValue(i, 3) + " ");
                }
            }
            string Factors  = Collection.Count() > 0 ? Collection.Aggregate() : "";
            string Factors2 = "";

            if (Factors.Length > 27)
            {
                int i = Factors.Substring(0, 27).LastIndexOf(" ");
                if (i > 0)
                {
                    Factors2 = Factors.Substring(i);
                    Factors  = Factors.Substring(0, i);
                }
            }

            // Заполнение закладочный полей
            FillBookmarks(Certificate, ValidUntil, FullDeviceType, RegNum, AdditionalWares, PreviousVerifySerialNumber, DeviceNumber, VerificationMethods, VerificationScope, Suitability, VerificationMeans, Factors, Factors2, VerificationDateString, StaffName, ManagerName);

            // Добавление дополнительных данных
            return;
        }