Ejemplo n.º 1
0
        static List <Data> ParseType1(string filePath)
        {
            char        splitter = ';';
            string      line     = "EMPTY";
            List <Data> ret      = new List <Data>();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            System.IO.StreamReader sr = new System.IO.StreamReader(filePath, Encoding.GetEncoding("windows-1251"));//, Encoding.UTF8);//Encoding.GetEncoding("windows-1251")) ;

            try
            {
                // PARCE HEADER

                // Верхнеуссурийский стационар БПИ 2014г
                line = sr.ReadLine();
                string[] cells = line.Split(splitter);
                if (cells[0].IndexOf("Верхнеуссурийский стационар БПИ") < 0)
                {
                    throw new Exception("IndexOf(\"Верхнеуссурийский стационар БПИ\") < 0.");
                }

                // Приборы (две строки в файле)
                List <string> sdevices = new List <string>
                {
                    "н.опр. - не определялось", "Полевой анализатор YSI ProPlus", "\"Полевой рН метр \"\"Эксперт\"\"\"", "Макросостав",
                    "н.обн. - ниже предела обнаружения", "Электропроводность (SPC)", "Сумма ионов (TDS)", "Хроматограф LC 10Avp", "YSI pro plus"
                };

                for (int i = 0; i < 2; i++)
                {
                    line  = sr.ReadLine();
                    cells = line.Split(splitter);
                    foreach (string cell in cells)
                    {
                        string item = cell.Trim();
                        if (!string.IsNullOrEmpty(item))
                        {
                            if (!sdevices.Exists(x => x.IndexOf(item) >= 0))
                            {
                                throw new Exception($"Device [{item}] is not exists.");
                            }
                        }
                    }
                }

                // Переменные

                line  = sr.ReadLine();
                cells = line.Split(splitter);
                for (int i = 0; i < _fileVarColumnNames.Count; i++)
                {
                    if (_fileVarColumnNames[i].Trim() != cells[i].Trim())
                    {
                        throw new Exception($"Variable [{_fileVarColumnNames[i].Trim()}] != [{cells[i].Trim()}].");
                    }
                }


                // READ DATA BODY

                while (!sr.EndOfStream)
                {
                    line = sr.ReadLine().Trim();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }
                    cells = line.Split(splitter);

                    Data data = new Data {
                        Date = DateTime.Parse(cells[0]), SampleNum = int.Parse(cells[1]), PointName = cells[2]
                    };
                    for (int i = 3; i < _fileVarColumnNames.Count; i++)
                    {
                        string cell       = cells[i].Trim();
                        double value      = double.NaN;
                        double value1     = double.NaN;
                        string valueAddon = null;

                        if (!string.IsNullOrEmpty(cell))
                        {
                            value = StrVia.ParseDouble(cell);
                            if (double.IsNaN(value))
                            {
                                if (cell != "н.опр." && cell == "#ЗНАЧ!" && cell == "проба не отбиралась" && cell == "too few water")
                                {
                                    if (cell == "н.обн.")
                                    {
                                        value      = 0;
                                        valueAddon = "н.обн.";
                                    }
                                    else if (cell.ElementAt(0) == '<')
                                    {
                                        value = StrVia.ParseDouble(cell.Remove(0, 1));
                                        if (double.IsNaN(value))
                                        {
                                            throw new Exception($"1) Не удалось разобрать строку для ячейки i=[{i}] значение [{cell}]. Строка \n[{line}]");
                                        }
                                        valueAddon = "<";
                                    }
                                    else if (cell.IndexOf('/') >= 0)
                                    {
                                        string[] cell1 = cell.Split('/');
                                        value  = StrVia.ParseDouble(cell1[0]);
                                        value1 = StrVia.ParseDouble(cell1[1]);
                                        if (double.IsNaN(value) || double.IsNaN(value1))
                                        {
                                            throw new Exception($"3) Не удалось разобрать строку для ячейки i=[{i}] значение [{cell}]. Строка \n[{line}]");
                                        }
                                        valueAddon = "<";
                                    }
                                    else
                                    {
                                        throw new Exception($"2) Не удалось разобрать строку для ячейки i=[{i}] значение [{cell}]. Строка \n[{line}]");
                                    }
                                }
                            }
                        }
                        data.Values.Add(value);
                        data.Values1.Add(value1);
                        data.ValueAddons.Add(valueAddon);
                    }
                    ret.Add(data);

                    //if (ret.Count == 5) break;
                }
                return(ret);
            }
            catch (Exception ex)
            {
                Console.WriteLine(line + "\n\n" + ex.ToString());
                return(null);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
Ejemplo n.º 2
0
        static List <Data> ParseType2(HttpClient client, string filePath, List <Site> sites)
        {
            Site site = GetFileSite(client, filePath, sites);

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

            char   splitter = ';';
            string line     = "EMPTY";

            Dictionary <string /*filecolumn name*/, Varoff> columnXVaroff = new Dictionary <string, Varoff>
            {
                { "Rivlevel from sensor, m", new Varoff {
                      VariableId = 2, OffsetTypeId = 0, OffsetValue = 0
                  } },
                { "Rivlevel BHS, m", null },
                { "AtmPress, mmHg", new Varoff {
                      VariableId = 1249, OffsetTypeId = 102, OffsetValue = 2
                  } },
                { "DewPoint, °C", new Varoff {
                      VariableId = 1350, OffsetTypeId = 102, OffsetValue = 2
                  } },
                { "Rhum, %", new Varoff {
                      VariableId = 1352, OffsetTypeId = 102, OffsetValue = 2
                  } },
                { "Prec, mm", new Varoff {
                      VariableId = 1360, OffsetTypeId = 102, OffsetValue = 2
                  } },
                { "TypePrec", new Varoff {
                      VariableId = -1023, OffsetTypeId = 102, OffsetValue = 2
                  } },                                                                            // Знак минус означает необх. перекодировки (текст->код)
                { "Temp, °C", new Varoff {
                      VariableId = 1300, OffsetTypeId = 102, OffsetValue = 2
                  } },
            };
            Dictionary <string, double> typePrecipitationXCode = new Dictionary <string, double>
            {
                { "нет осадков", 4 },
                { "жидкие", 1 },
                { "ледяной дождь", 6 },
                { "мокрый снег", 5 },
                { "твёрдые", 2 }
            };

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            System.IO.StreamReader sr = new System.IO.StreamReader(filePath, Encoding.GetEncoding("windows-1251"));//.UTF8);//.GetEncoding("windows-1251")) ;

            try
            {
                // READ HEADER

                line = sr.ReadLine();
                string[] cells = line.Split(splitter);

                if (cells[0] != "Datetime")
                {
                    throw new Exception("First column is not Datetime.");
                }

                List <Data> ret = new List <Data>();

                for (int i = 1; i < cells.Length; i++)
                {
                    if (!columnXVaroff.TryGetValue(cells[i], out Varoff varoff))
                    {
                        throw new Exception($"Unknown column {cells[i]}.");
                    }

                    ret.Add(new Data {
                        Site = site, Varoff = varoff, DateValues = varoff == null ? null : new List <DateValue>(100000)
                    });
                }

                // READ DATA BODY
                int iLineCount = 0;
                while (!sr.EndOfStream)
                {
                    iLineCount++;
                    line = sr.ReadLine().Trim();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }
                    cells = line.Split(splitter);

                    DateTime date = DateTime.Parse(cells[0]);

                    for (int i = 1; i < cells.Length; i++)
                    {
                        if (ret[i - 1].Varoff != null)
                        {
                            double value = double.NaN;
                            if (ret[i - 1].Varoff.VariableId < 0)
                            {
                                if (ret[i - 1].Varoff.VariableId == -1023)
                                {
                                    if (!typePrecipitationXCode.TryGetValue(cells[i].Trim(), out value))
                                    {
                                        throw new Exception($"Unknown string categorical value {cells[i].Trim()} in column #{i} for variableId ={ret[i - 1].Varoff.VariableId}.");
                                    }
                                }
                                else
                                {
                                    throw new Exception($"Unknown categorical value column #{i} for variableId ={ret[i - 1].Varoff.VariableId}.");
                                }
                            }
                            else
                            {
                                value = StrVia.ParseDouble(cells[i]);
                            }

                            if (double.IsNaN(value))
                            {
                                throw new Exception($"Value for date {date} in column #{i} for variableId ={ret[i - 1].Varoff.VariableId} is NaN.");
                            }

                            ret[i - 1].DateValues.Add(new DateValue {
                                Date = date, Value = value
                            });
                        }
                    }
                    //if (iLineCount == 10) break;
                }
                return(ret);
            }
            catch (Exception ex)
            {
                Console.WriteLine(line + "\n\n" + ex.ToString());
                return(null);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }