Ejemplo n.º 1
0
        public bool Read()
        {
            if (!EndOfFile)
            {
                if (_parser == null)
                {
                    _parser = Stream == null
                        ? new TextFieldParser(FileName)
                    {
                        TextFieldType = FieldType.Delimited
                    }
                        : new TextFieldParser(Stream, DefaultEncoding)
                    {
                        TextFieldType = FieldType.Delimited
                    };

                    _parser.SetDelimiters(Delimiters);
                }
                if (!_parser.EndOfData)
                {
                    Fields = _parser.ReadFields();
                    return(true);
                }
                _parser.Close();
                _parser.Dispose();
                _parser   = null;
                EndOfFile = true;
            }
            return(false);
        }
Ejemplo n.º 2
0
        public bool Read()
        {
            if (!File.Exists(this.filename))
            {
                return(false);
            }
            TextFieldParser textFieldParser = (TextFieldParser)null;

            this.dataList.Clear();
            try
            {
                textFieldParser = new TextFieldParser(this.filename, this.encode);
                textFieldParser.TextFieldType = FieldType.Delimited;
                textFieldParser.SetDelimiters(",");
                textFieldParser.TrimWhiteSpace = false;
                while (!textFieldParser.EndOfData)
                {
                    this.dataList.Add(textFieldParser.ReadFields());
                }
            }
            catch
            {
                return(false);
            }
            finally
            {
                if (textFieldParser != null)
                {
                    textFieldParser.Close();
                    textFieldParser.Dispose();
                }
            }
            return(true);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Dispose.
        /// </summary>
        public void Dispose()
        {
            _parser?.Dispose();
            _reader?.Dispose();

            _csvStream.Dispose();
        }
        /// <summary>
        /// Loading existing Course data, if any.
        /// </summary>
        /// <returns></returns>
        async Task LoadCourseData()
        {
            TextFieldParser parser = null;

            try
            {
                parser = csv.GetCSVParser(storage);

                // skip over header line.
                parser.ReadLine();

                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();
                    try
                    {
                        if (!courseIdName.ContainsKey(fields[0]))
                        {
                            courseIdName.Add(fields[0], fields[1] + ',' + fields[2]);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Invalid data encountered when initializing in Course records: " + ex.Message);
                    }
                }
            }
            finally
            {
                if (parser != null)
                {
                    parser.Dispose();
                }
            }
        }
Ejemplo n.º 5
0
        private static IEnumerable <string[]> ParseFile(Stream fileStream, string delimiter, bool skipHeaderLine)
        {
            IList <string[]> result          = new List <string[]>();
            TextFieldParser  textFieldParser = null;

            try
            {
                textFieldParser = new TextFieldParser(fileStream)
                {
                    TextFieldType             = FieldType.Delimited,
                    HasFieldsEnclosedInQuotes = true,
                    TrimWhiteSpace            = true
                };
                textFieldParser.SetDelimiters(delimiter);

                while (!textFieldParser.EndOfData)
                {
                    string[] parsedEntry = textFieldParser.ReadFields();
                    if (skipHeaderLine)
                    {
                        skipHeaderLine = false;
                        continue;
                    }

                    result.Add(parsedEntry);
                }
            }
            finally
            {
                textFieldParser?.Dispose();
            }

            return(result);
        }
Ejemplo n.º 6
0
        // Load csv to List<T>
        public List <DenialRecord> CsvList(int columnCount)
        {
            using (TextFieldParser csvParser = new TextFieldParser(filePath))
            {
                csvParser.TextFieldType = FieldType.Delimited;
                csvParser.SetDelimiters(",");
                csvParser.HasFieldsEnclosedInQuotes = false;
                csvParser.TrimWhiteSpace            = true;

                while (!csvParser.EndOfData)
                {
                    try
                    {
                        string[] row = csvParser.ReadFields();
                        if (row.Length <= 7)
                        {
                            DenialRecord dr = new DenialRecord(row[0], row[1], row[2], row[3], row[4], row[5], row[6]);
                            inputList.Add(dr);
                        }
                    }
                    catch (Exception e)
                    {
                        // do something
                        Console.WriteLine("Error is:  {0}", e.ToString());
                    }
                }
                csvParser.Close();
                csvParser.Dispose();
            }
            return(inputList);
        }
Ejemplo n.º 7
0
 void IDisposable.Dispose()
 {
     if (parser_ != null)
     {
         parser_.Dispose();
     }
 }
Ejemplo n.º 8
0
    public Table(string tableFile)
    {
        TextFieldParser parser = new TextFieldParser(tableFile, System.Text.Encoding.GetEncoding("Shift_JIS"));

        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters("=");              // イコールで分割(今は意味なし)
        while (!parser.EndOfData)
        {
            string [] row = parser.ReadFields();
            if (row.Length == 1)
            {
                // ファイルレコード
                string[] field = row[0].Split(',');                // カンマで分割
                int      x1    = int.Parse(field[1]);
                int      y1    = int.Parse(field[2]);
                int      x2    = int.Parse(field[3]);
                int      y2    = int.Parse(field[4]);
                nMinX = x1 < nMinX ? x1 : nMinX;
                nMinY = y1 < nMinY ? y1 : nMinY;
                nMaxX = x2 > nMaxX ? x2 : nMaxX;
                nMaxY = y2 > nMaxY ? y2 : nMaxY;
                list.Add(new tableData(field[0], x1, y1, x2, y2));
            }
        }
        parser.Dispose();
    }
        /// <summary>
        /// process a course CSV file and load the data to memory.
        /// </summary>
        /// <param name="path"></param>
        public void ProcessCSV(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }

            TextFieldParser parser = null;

            // course_id:0; course_name:1; state: 2
            int[] maps = { 0, 0, 0 };
            try
            {
                parser = csv.GetCSVParser(path);
                string[] fields = parser.ReadFields();
                if (fields.Length < 3)
                {
                    throw new Exception("Invalid Student CSV file! four columns are required: course_id, course_name, state");
                }
                for (int i = 0; i < 3; i++)
                {
                    switch (fields[i].ToLower())
                    {
                    case "course_id":
                        maps[i] = 0;
                        break;

                    case "course_name":
                        maps[i] = 1;
                        break;

                    case "state":
                        maps[i] = 2;
                        break;

                    default:
                        throw new Exception(string.Format("Invalid Course CSV file: header value:{0} is not recognized!", fields[i]));
                    }
                }
                while (!parser.EndOfData)
                {
                    fields = parser.ReadFields();
                    string[] f = { "", "", "" };
                    for (int i = 0; i < 3; i++)
                    {
                        f[maps[i]] = fields[i];
                    }

                    Course course = new Course(f[0], f[1], (State)Enum.Parse(typeof(State), f[2]));
                }
            }
            finally
            {
                if (parser != null)
                {
                    parser.Dispose();
                }
            }
        }
Ejemplo n.º 10
0
        //追加する行を受け取り配列を再度確保する
        public string[,] AppendLine(string[,] apTable, string[] append_line, string FilePath, Encoding encode)
        {
            FileStream      fs     = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            TextFieldParser parser = new TextFieldParser(fs, encode);

            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(",");

            row = 0;
            //要素数の決定
            while (!parser.EndOfData)
            {
                int      colcnt = 0;
                string[] line   = parser.ReadFields();
                row++;
                foreach (string tmp in line)
                {
                    colcnt++;
                }
                if (colcnt > col)
                {
                    col = colcnt;
                }
            }
            apTable = new string[row + 1, col];

            {
                //ここから2次元配列に格納
                int      r = 0, c = 0;
                string[] line2;
                parser = new TextFieldParser(FilePath, encode);
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                while (!parser.EndOfData)
                {
                    //1行ずつね
                    line2 = parser.ReadFields();
                    c     = 0;
                    foreach (string tmp in line2)
                    {
                        apTable[r, c] = tmp;
                        c++;
                    }
                    for (; c < this.col; c++)
                    {
                        apTable[r, c] = string.Empty;
                    }
                    r++;
                }

                for (int i = 0; i < append_line.Length; i++)
                {
                    apTable[r, i] = append_line[i];
                }
            }
            parser.Dispose();
            parser.Close();
            return(apTable);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// 終了処理を行います。
 /// </summary>
 public virtual void Dispose()
 {
     Close();
     if (_parser != null)
     {
         _parser.Dispose();
     }
 }
Ejemplo n.º 12
0
        public void Dispose()
        {
            if (m_IsDisposed)
            {
                return;
            }

            m_Parser.Dispose();
            m_IsDisposed = true;
        }
        /// <summary>
        /// Load existing Student data from stored CSV, if any.
        /// </summary>
        /// <returns></returns>
        async Task LoadStudentsFromCSV()
        {
            //Task t = Task.Run(() =>
            //{
            TextFieldParser parser = null;

            try
            {
                parser = csv.GetCSVParser(storege);

                // skip over header line.
                parser.ReadLine();

                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();
                    try
                    {
                        if (studentIdName.ContainsKey((fields[0])))
                        {
                            continue;
                        }

                        // key= id; fields: 1: name; 2: course_id; 3: state.
                        studentIdName.Add(fields[0], fields[1] + ',' + fields[2] + ',' + fields[3]);

                        // mapping the course_id to all student_id that selected the course.
                        if (courseStudents.ContainsKey(fields[2]))
                        {
                            courseStudents[fields[2]] += ',' + fields[0];
                        }
                        else
                        {
                            courseStudents.Add(fields[2], fields[0]);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Invalid data encountered when initializing in Student records: " + ex.Message);
                    }
                }
            }
            finally
            {
                if (parser != null)
                {
                    parser.Dispose();
                }
            }
            //});
            //return t;
        }
Ejemplo n.º 14
0
        public void csvParser()
        {
            TextFieldParser csvReader = new TextFieldParser(SapFolderDirection);

            csvReader.SetDelimiters(new string[] { ";" });
            colFields = csvReader.ReadFields();
            for (int i = 0; i < colFields.Length; i++)
            {
                if (colFields[i] == "")
                {
                    colFields[i] = null;
                }
            }
            csvReader.Dispose();
        }
        public DataParser()
        {
            UpdatePokedex();

            csv = new TextFieldParser(path);
            csv.TextFieldType = FieldType.Delimited;
            csv.SetDelimiters(",");

            buffer = new string[lineLength];
            buffer = csv.ReadFields();  // Reads header
            for (int i = 0; i < entries; i++)
            {
                LineToPokemon();
            }

            csv.Dispose();
        }
Ejemplo n.º 16
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             if (_fileStream != null)
             {
                 _fileStream.Dispose();
             }
             if (_parser != null)
             {
                 _parser.Dispose();
             }
         }
     }
     _disposed = true;
 }
        public void StudentTestInitialize()
        {
            studentData.Clear();
            var tmpPath = Path.Combine(Environment.CurrentDirectory, "Student.csv");

            if (File.Exists(tmpPath))
            {
                File.Delete(tmpPath);
            }

            File.Copy(studentTestFile, tmpPath);

            Task t = studentCsv.LoadDataAsync();

            t.Wait();

            CSVAccess       acc    = new CSVAccess();
            TextFieldParser parser = acc.GetCSVParser(studentTestFile);

            // skip over header line.
            parser.ReadLine();

            while (!parser.EndOfData)
            {
                string[] v      = new string[2];
                string[] fields = parser.ReadFields();
                v[0] = fields[1];
                v[1] = fields[2];
                try
                {
                    if (!studentData.ContainsKey(fields[0]))
                    {
                        studentData.Add(fields[0], v);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            parser.Dispose();
        }
        public void CourseCsvTestInitialize()
        {
            courseData.Clear();
            var tmpPath = Path.Combine(Environment.CurrentDirectory, "Course.csv");

            if (File.Exists(tmpPath))
            {
                File.Delete(tmpPath);
            }

            File.Copy(courseTestFile, tmpPath);

            courseCsv = CourseCSV.Initialize();
            Assert.IsNotNull(courseCsv, "Failed: Initialize CourseCSV object returns null!");

            CSVAccess       acc    = new CSVAccess();
            TextFieldParser parser = acc.GetCSVParser(courseTestFile);

            // skip over header line.
            parser.ReadLine();

            while (!parser.EndOfData)
            {
                string[] v      = new string[2];
                string[] fields = parser.ReadFields();
                v[0] = fields[1];
                v[1] = fields[2];
                try
                {
                    if (!courseData.ContainsKey(fields[0]))
                    {
                        courseData.Add(fields[0], v);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Initializing unit test got exception: " + ex.Message);
                }
            }

            parser.Dispose();
        }
Ejemplo n.º 19
0
        public void readAndSendSql(string direction, int index)
        {
            TextFieldParser csvReader = new TextFieldParser(direction);

            csvReader.SetDelimiters(new string[] { ";" });
            colFields = csvReader.ReadFields();
            for (int i = 0; i < colFields.Length; i++)
            {
                if (colFields[i] == "")
                {
                    colFields[i] = null;
                }
            }
            csvReader.Dispose();
            conn.Open();
            SqlCommand kmt = new SqlCommand("Insert into  tbl_csv VALUES  ('" + colFields[0] + "','" + colFields[1] + "','" + colFields[2] + "','" + colFields[3] + "','" + colFields[4] + "','" + colFields[5] + "','" + colFields[6] + "','" + colFields[7] + "','" + colFields[8] + "','" + colFields[9] + "','" + colFields[10] + "','" + colFields[11] + "','" + colFields[12] + "','" + colFields[13] + "','" + colFields[14] + "','" + colFields[15] + "')", conn);

            kmt.ExecuteNonQuery();
            conn.Close();
        }
Ejemplo n.º 20
0
        private bool disposedValue = false;                // To detect redundant calls

        // IDisposable
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposedValue)
            {
                if (disposing)
                {
                    if (m_DataTable != null)
                    {
                        m_DataTable.Dispose();
                    }

                    m_strFilePath           = null;
                    m_boolContainsHeader    = default(bool);
                    m_intNumberOfColumns    = default(int);
                    m_FieldEnclosedInQuotes = default(bool);
                    tfpTxtParser.Dispose();
                    strFirstLine = null;
                }
            }
            this.disposedValue = true;
        }
Ejemplo n.º 21
0
        void CountDataLength(string FilePath)
        {
            using (TextFieldParser tfp = new TextFieldParser(FilePath))
            {
                tfp.TextFieldType = FieldType.Delimited;
                tfp.SetDelimiters(",");

                string[] firstRow = tfp.ReadFields();

                rows = 1;
                cols = firstRow.Length;

                while (!tfp.EndOfData)
                {
                    tfp.ReadFields();
                    rows++;
                }

                tfp.Close();
                tfp.Dispose();
            }
        }
Ejemplo n.º 22
0
        void Parse(string FilePath)
        {
            using (TextFieldParser tfp = new TextFieldParser(FilePath))
            {
                data = new string[rows, cols];

                tfp.TextFieldType = FieldType.Delimited;
                tfp.SetDelimiters(",");

                for (int i = 0; i < rows; i++)
                {
                    string[] temp = tfp.ReadFields();
                    for (int j = 0; j < cols; j++)
                    {
                        data[i, j] = temp[j];
                    }
                }

                tfp.Close();
                tfp.Dispose();
            }
        }
Ejemplo n.º 23
0
        public static DataTable ReadFile(string fileName, string delimiter = ",", bool firstRowIsHeader = true)
        {
            if (!File.Exists(fileName))
            {
                return(new DataTable());
            }
            TextFieldParser parser = new TextFieldParser(fileName);

            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(delimiter);
            bool      columnInformationTaken = false;
            DataTable table  = new DataTable();
            bool      failed = false;

            while (!parser.EndOfData)
            {
                string[] fields = parser.ReadFields();
                if (!columnInformationTaken)
                {
                    if (firstRowIsHeader)
                    {
                        foreach (string field in fields)
                        {
                            table.Columns.Add(field);
                        }
                    }
                    else
                    {
                        for (int c = 1; c <= fields.Length; c++)
                        {
                            table.Columns.Add("Column" + c.ToString());
                        }
                        table.Rows.Add(fields);
                    }
                    columnInformationTaken = true;
                }

                else
                {
                    if (table.Columns.Count != fields.Length)
                    {
                        ExtensionMethods.TraceError("Data source attribute count and data fed is not equal, could not parse data!");
                        failed = true;
                        break;
                    }
                    table.Rows.Add(fields);
                }
            }
            parser.Close();
            if (failed)
            {
                parser.Dispose();
                parser = null;
                table.Dispose();
                table = null;
                return(new DataTable());
            }
            else
            {
                return(table);
            }
        }
Ejemplo n.º 24
0
 public void CloseFile()
 {
     _parser.Close();
     _parser.Dispose();
 }
 public void Dispose()
 {
     parser.Dispose();
 }
Ejemplo n.º 26
0
        public static void PopulateDataGridView(DataGridView dataGridView)
        {
            dataGridView.Rows.Clear();
            dataGridView.Columns.Clear();
            dataGridView.Refresh();

            if (File.Exists(filePath))
            {
                FileInfo fi = new FileInfo(filePath);

                if (fi.Length > 0)
                {
                    try
                    {
                        using (StreamReader sr = new StreamReader(filePath))
                        {
                            foreach (string entry in sr.ReadLine().Split(seperator))
                            {
                                dataGridView.Columns.Add(columns.ToString().Replace(";", ""), entry);
                            }
                            sr.Close();
                            sr.Dispose();
                        }
                        using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            using (BufferedStream bs = new BufferedStream(fs))
                                using (var streamReader = new StreamReader(fs))
                                    using (TextFieldParser csvParser = new TextFieldParser(streamReader))
                                    {
                                        csvParser.CommentTokens = new string[] { "#" };
                                        csvParser.SetDelimiters(new string[] { ";" });
                                        csvParser.HasFieldsEnclosedInQuotes = true;
                                        csvParser.ReadLine();
                                        while (!csvParser.EndOfData)
                                        {
                                            string[] fields = csvParser.ReadFields();
                                            dataGridView.Rows.Add(fields);
                                        }

                                        csvParser.Close();
                                        csvParser.Dispose();

                                        streamReader.Close();
                                        streamReader.Dispose();

                                        bs.Close();
                                        bs.Dispose();

                                        fs.Close();
                                        fs.Dispose();
                                    }
                        isDone = true;
                    }
                    catch
                    {
                        filePath = null;
                        MessageBoxProcessor.Show("Beim Laden der Datei ist ein Fehler aufgetreten!", "Datei konnte nicht geladen werden", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    isDone = true;
                }
            }
        }
Ejemplo n.º 27
0
        public DataPage()
        {
            InitializeComponent();
            SheetName.Text = "Starting up SaintCoinach...";
            //  const string GameDirectory = @"C:\Program Files (x86)\Steam\steamapps\common\FINAL FANTASY XIV Online";
            ARealmReversed Realm = new ARealmReversed(MainWindow.GamePath, SaintCoinach.Ex.Language.English);

            Realm.Packs.GetPack(new SaintCoinach.IO.PackIdentifier("exd", SaintCoinach.IO.PackIdentifier.DefaultExpansion, 0)).KeepInMemory = false;

            var            Race               = Realm.GameData.GetSheet <SaintCoinach.Xiv.Race>();
            var            Tribe              = Realm.GameData.GetSheet <SaintCoinach.Xiv.Tribe>();
            var            Items              = Realm.GameData.GetSheet <SaintCoinach.Xiv.Item>();
            var            Stains             = Realm.GameData.GetSheet <SaintCoinach.Xiv.Stain>();
            var            ENpcBase           = Realm.GameData.GetSheet <SaintCoinach.Xiv.ENpcBase>();
            var            Territory          = Realm.GameData.GetSheet <SaintCoinach.Xiv.TerritoryType>();
            var            Weather            = Realm.GameData.GetSheet <SaintCoinach.Xiv.Weather>();
            var            CharaMakeCustomize = Realm.GameData.GetSheet <SaintCoinach.Xiv.CharaMakeCustomize>();
            var            CharaMakeType      = Realm.GameData.GetSheet <SaintCoinach.Xiv.CharaMakeType>();
            var            eNpcResidents      = Realm.GameData.GetSheet <SaintCoinach.Xiv.ENpcResident>();
            var            TitleSheet         = Realm.GameData.GetSheet <SaintCoinach.Xiv.Title>();
            var            StatusSheet        = Realm.GameData.GetSheet <SaintCoinach.Xiv.Status>();
            HashSet <byte> StatusIds          = new HashSet <byte>();

            AllEquipment               = Realm.GameData.GetSheet <SaintCoinach.Xiv.Item>().ToArray();
            ExdData.Items              = new Dictionary <int, ExdData.Item>();
            ExdData.Residents          = new Dictionary <int, ExdData.Resident>();
            ExdData.CharaMakeFeatures  = new Dictionary <int, ExdData.CharaMakeCustomizeFeature>();
            ExdData.CharaMakeFeatures2 = new Dictionary <int, ExdData.CharaMakeCustomizeFeature2>();
            ExdData.TerritoryTypes     = new Dictionary <int, ExdData.TerritoryType>();
            ExdData.BGMs               = new Dictionary <int, ExdData.BGM>();
            ExdData.Emotes             = new Dictionary <int, ExdData.Emote>();
            ExdData.Monsters           = new Dictionary <int, ExdData.Monster>();
            ExdData.Stain              = new List <string>();

            Task.Run(() =>
            {
                var size = AllEquipment.Length;

                for (int i = 0; i < size; i++)
                {
                    if (AllEquipment[i].EquipSlotCategory.Key == 0)
                    {
                        if (AllEquipment[i].Key == 0)
                        {
                            var itemX = new ExdData.Item
                            {
                                Index             = AllEquipment[i].Key,
                                Name              = AllEquipment[i].Name,
                                ClassJobCategory  = AllEquipment[i].ClassJobCategory,
                                EquipSlotCategory = AllEquipment[i].EquipSlotCategory,
                                ModelMain         = AllEquipment[i].ModelMain,
                                ModelSub          = AllEquipment[i].ModelSub,
                                IsDyeable         = AllEquipment[i].IsDyeable,
                            };
                            if (AllEquipment[i].Key == 0)
                            {
                                itemX.Name = "None";
                            }
                            if (AllEquipment[i].Icon == null)
                            {
                                itemX.Icon = null;
                            }
                            else
                            {
                                itemX.Icon = AllEquipment[i].Icon;
                            }
                            App.AllEquipmentX.Add(itemX);
                        }
                        continue;
                    }

                    var item = new ExdData.Item
                    {
                        Index             = AllEquipment[i].Key,
                        Name              = AllEquipment[i].Name,
                        ClassJobCategory  = AllEquipment[i].ClassJobCategory,
                        EquipSlotCategory = AllEquipment[i].EquipSlotCategory,
                        ModelMain         = AllEquipment[i].ModelMain,
                        ModelSub          = AllEquipment[i].ModelSub,
                        IsDyeable         = AllEquipment[i].IsDyeable,
                    };
                    if (AllEquipment[i].Key == 0)
                    {
                        item.Name = "None";
                    }
                    if (AllEquipment[i].Icon == null)
                    {
                        item.Icon = null;
                    }
                    else
                    {
                        item.Icon = AllEquipment[i].Icon;
                    }
                    App.AllEquipmentX.Add(item);
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        SheetName.Text  = "Equipment";
                        PB.Value        = (i * 100) / size;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }

                for (int i = 0; i < Race.Count; i++)
                {
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        if (i == 0)
                        {
                            ResourcePage.Resourcepage.RaceBox.Items.Add("None");
                        }
                        else
                        {
                            ResourcePage.Resourcepage.RaceBox.Items.Add(Race[i].Feminine);
                        }

                        SheetName.Text  = Race.Name;
                        PB.Value        = (i * 100) / Race.Count;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                for (int i = 0; i < Tribe.Count; i++)
                {
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        if (i == 0)
                        {
                            ResourcePage.Resourcepage.ClanBox.Items.Add("None");
                        }
                        else
                        {
                            ResourcePage.Resourcepage.ClanBox.Items.Add(Tribe[i].Feminine);
                        }
                        SheetName.Text  = Tribe.Name;
                        PB.Value        = (i * 100) / Tribe.Count;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                size = Stains.Count;
                for (int i = 0; i < size; i++)
                {
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        string DyeName = Stains[i].Name;
                        if (DyeName.Length <= 0)
                        {
                            DyeName = "None";
                        }
                        ExdData.Stain.Add(DyeName);
                        SheetName.Text  = "Dyes";
                        PB.Value        = (i * 100) / size;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                size           = Territory.Count;
                int TerritoryI = 0;
                foreach (var TerritoryIndex in Territory)
                {
                    TerritoryI++;
                    ExdData.TerritoryType territory = new ExdData.TerritoryType
                    {
                        Index       = TerritoryIndex.Key,
                        WeatherRate = new ExdData.WeatherRate()
                    };
                    territory.WeatherRate.AllowedWeathers = new List <ExdData.Weather>();
                    foreach (var WeatherRate in TerritoryIndex.WeatherRate.PossibleWeathers)
                    {
                        territory.WeatherRate.Index = WeatherRate.Key;
                        //   Test.Icon
                        if (WeatherRate.Key != 0)
                        {
                            territory.WeatherRate.AllowedWeathers.Add(new ExdData.Weather()
                            {
                                Index = WeatherRate.Key, Name = WeatherRate.Name, Icon = WeatherRate.Icon
                            });
                        }
                        else
                        {
                            territory.WeatherRate.AllowedWeathers.Add(new ExdData.Weather()
                            {
                                Index = WeatherRate.Key, Name = "None", Icon = null
                            });
                        }
                    }
                    if (TerritoryIndex.RegionPlaceName.Name == "Norvrandt")
                    {
                        territory.WeatherRate.AllowedWeathers.Add(new ExdData.Weather()
                        {
                            Index = 118, Name = "Everlasting Light #1", Icon = Weather[118].Icon
                        });
                        territory.WeatherRate.AllowedWeathers.Add(new ExdData.Weather()
                        {
                            Index = 129, Name = "Everlasting Light #2", Icon = Weather[129].Icon
                        });
                    }
                    ExdData.TerritoryTypes.Add(TerritoryIndex.Key, territory);
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        SheetName.Text  = "Territory";
                        PB.Value        = (TerritoryI * 100) / size;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                size = Weather.Count;
                for (int i = 0; i < size; i++)
                {
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        byte[] Bytes = { (byte)Weather[i].Key, (byte)Weather[i].Key };
                        if (Weather[i].Icon != null)
                        {
                            ZonePage.Zonepage.WeatherBox2.Items.Add(new ExdData.Weather
                            {
                                Index = Convert.ToInt32(Weather[i].Key),
                                Key   = BitConverter.ToUInt16(Bytes, 0),
                                Name  = Weather[i].Name.ToString(),
                                Icon  = Weather[i].Icon,
                            });
                        }
                        else
                        {
                            ZonePage.Zonepage.WeatherBox2.Items.Add(new ExdData.Weather
                            {
                                Index = Convert.ToInt32(Weather[i].Key),
                                Key   = BitConverter.ToUInt16(Bytes, 0),
                                Name  = Weather[i].Name.ToString(),
                                Icon  = null,
                            });
                        }
                        SheetName.Text  = "Weather";
                        PB.Value        = (i * 100) / size;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }

                size = eNpcResidents.Count + 1000000;
                for (int i = 1000000; i < size; i++)
                {
                    ExdData.Residents.Add(eNpcResidents[i].Key, new ExdData.Resident {
                        Index = eNpcResidents[i].Key, Name = eNpcResidents[i].Singular
                    });
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        SheetName.Text  = "NPC Names";
                        PB.Value        = ((i - 1000000) * 100) / (size - 1000000);
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                size = ENpcBase.Count + 1000000;
                for (int i = 1000000; i < size; i++)
                {
                    GearSet gear          = new GearSet();
                    List <byte> customize = new List <byte>();
                    customize.AddRange(new List <byte>()
                    {
                        Convert.ToByte(ENpcBase[i].Race.Key), Convert.ToByte(ENpcBase[i].Gender)
                        , Convert.ToByte(ENpcBase[i].BodyType), Convert.ToByte(ENpcBase[i].Height)
                        , Convert.ToByte(ENpcBase[i].Tribe.Key), Convert.ToByte(ENpcBase[i].Face), Convert.ToByte(ENpcBase[i].HairStyle), Convert.ToByte(ENpcBase[i].HairHighlight)
                        , Convert.ToByte(ENpcBase[i].SkinColor), Convert.ToByte(ENpcBase[i].EyeHeterochromia), Convert.ToByte(ENpcBase[i].HairColor), Convert.ToByte(ENpcBase[i].HairHighlightColor)
                        , Convert.ToByte(ENpcBase[i].FacialFeature), Convert.ToByte(ENpcBase[i].FacialFeatureColor), Convert.ToByte(ENpcBase[i].Eyebrows), Convert.ToByte(ENpcBase[i].EyeColor)
                        , Convert.ToByte(ENpcBase[i].EyeShape), Convert.ToByte(ENpcBase[i].Nose), Convert.ToByte(ENpcBase[i].Jaw), Convert.ToByte(ENpcBase[i].Mouth)
                        , Convert.ToByte(ENpcBase[i].LipColor), Convert.ToByte(ENpcBase[i].BustOrTone1), Convert.ToByte(ENpcBase[i].ExtraFeature1), Convert.ToByte(ENpcBase[i].ExtraFeature2OrBust)
                        , Convert.ToByte(ENpcBase[i].FacePaint), Convert.ToByte(ENpcBase[i].FacePaintColor)
                    });
                    gear.Customize  = customize.ToArray();
                    gear.ModelChara = ENpcBase[i].ModelChara.Key;
                    if (ENpcBase[i].NpcEquip.Key > 0)
                    {
                        gear.MainWep   = new WepTuple(ENpcBase[i].NpcEquip.ModelMain.Value1, ENpcBase[i].NpcEquip.ModelMain.Value2, ENpcBase[i].NpcEquip.ModelMain.Value3, (ushort)ENpcBase[i].NpcEquip.DyeMain.Key);
                        gear.OffWep    = new WepTuple(ENpcBase[i].NpcEquip.ModelSub.Value1, ENpcBase[i].NpcEquip.ModelSub.Value2, ENpcBase[i].NpcEquip.ModelSub.Value3, (ushort)ENpcBase[i].NpcEquip.DyeOff.Key);
                        gear.HeadGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelHead[0] + ENpcBase[i].NpcEquip.ModelHead[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelHead[2], (byte)ENpcBase[i].NpcEquip.DyeHead.Key);
                        gear.BodyGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelBody[0] + ENpcBase[i].NpcEquip.ModelBody[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelBody[2], (byte)ENpcBase[i].NpcEquip.DyeBody.Key);
                        gear.HandsGear = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelHands[0] + ENpcBase[i].NpcEquip.ModelHands[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelHands[2], (byte)ENpcBase[i].NpcEquip.DyeHands.Key);
                        gear.LegsGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelLegs[0] + ENpcBase[i].NpcEquip.ModelLegs[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelLegs[2], (byte)ENpcBase[i].NpcEquip.DyeLegs.Key);
                        gear.FeetGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelFeet[0] + ENpcBase[i].NpcEquip.ModelFeet[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelFeet[2], (byte)ENpcBase[i].NpcEquip.DyeFeet.Key);
                        gear.EarGear   = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelEars[0] + ENpcBase[i].NpcEquip.ModelEars[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelEars[2], 0);
                        gear.NeckGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelNeck[0] + ENpcBase[i].NpcEquip.ModelNeck[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelNeck[2], 0);
                        gear.WristGear = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelWrists[0] + ENpcBase[i].NpcEquip.ModelWrists[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelWrists[2], 0);
                        gear.RRingGear = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelRightRing[0] + ENpcBase[i].NpcEquip.ModelRightRing[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelRightRing[2], 0);
                        gear.LRingGear = new GearTuple(Convert.ToUInt16((ENpcBase[i].NpcEquip.ModelLeftRing[0] + ENpcBase[i].NpcEquip.ModelLeftRing[1] * 256)), (byte)ENpcBase[i].NpcEquip.ModelLeftRing[2], 0);
                    }
                    else
                    {
                        gear.MainWep   = new WepTuple(ENpcBase[i].ModelMain.Value1, ENpcBase[i].ModelMain.Value2, ENpcBase[i].ModelMain.Value3, (ushort)ENpcBase[i].DyeMain.Key);
                        gear.OffWep    = new WepTuple(ENpcBase[i].ModelSub.Value1, ENpcBase[i].ModelSub.Value2, ENpcBase[i].ModelSub.Value3, (ushort)ENpcBase[i].DyeOff.Key);
                        gear.HeadGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelHead[0] + ENpcBase[i].ModelHead[1] * 256)), (byte)ENpcBase[i].ModelHead[2], (byte)ENpcBase[i].DyeHead.Key);
                        gear.BodyGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelBody[0] + ENpcBase[i].ModelBody[1] * 256)), (byte)ENpcBase[i].ModelBody[2], (byte)ENpcBase[i].DyeBody.Key);
                        gear.HandsGear = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelHands[0] + ENpcBase[i].ModelHands[1] * 256)), (byte)ENpcBase[i].ModelHands[2], (byte)ENpcBase[i].DyeHands.Key);
                        gear.LegsGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelLegs[0] + ENpcBase[i].ModelLegs[1] * 256)), (byte)ENpcBase[i].ModelLegs[2], (byte)ENpcBase[i].DyeLegs.Key);
                        gear.FeetGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelFeet[0] + ENpcBase[i].ModelFeet[1] * 256)), (byte)ENpcBase[i].ModelFeet[2], (byte)ENpcBase[i].DyeFeet.Key);
                        gear.EarGear   = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelEars[0] + ENpcBase[i].ModelEars[1] * 256)), (byte)ENpcBase[i].ModelEars[2], 0);
                        gear.NeckGear  = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelNeck[0] + ENpcBase[i].ModelNeck[1] * 256)), (byte)ENpcBase[i].ModelNeck[2], 0);
                        gear.WristGear = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelWrists[0] + ENpcBase[i].ModelWrists[1] * 256)), (byte)ENpcBase[i].ModelWrists[2], 0);
                        gear.RRingGear = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelRightRing[0] + ENpcBase[i].ModelRightRing[1] * 256)), (byte)ENpcBase[i].ModelRightRing[2], 0);
                        gear.LRingGear = new GearTuple(Convert.ToUInt16((ENpcBase[i].ModelLeftRing[0] + ENpcBase[i].ModelLeftRing[1] * 256)), (byte)ENpcBase[i].ModelLeftRing[2], 0);
                    }
                    ExdData.Residents[ENpcBase[i].Key].Gear = gear;
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        SheetName.Text  = "NPC Data";
                        PB.Value        = ((i - 1000000) * 100) / (size - 1000000);
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                size = CharaMakeCustomize.Count;
                for (int i = 0; i < size; i++)
                {
                    var feature = new ExdData.CharaMakeCustomizeFeature
                    {
                        Index     = CharaMakeCustomize[i].Key,
                        FeatureID = CharaMakeCustomize[i].FeatureID
                    };
                    if (CharaMakeCustomize[i].Icon == null)
                    {
                        feature.Icon = null;
                    }
                    else
                    {
                        feature.Icon = CharaMakeCustomize[i].Icon;
                    }
                    ExdData.CharaMakeFeatures.Add(i, feature);

                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        SheetName.Text  = "CharaMakeCustomize";
                        PB.Value        = (i * 100) / size;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                size = CharaMakeType.Count;
                for (int i = 0; i < size; i++)
                {
                    var feature = new ExdData.CharaMakeCustomizeFeature2
                    {
                        Index  = CharaMakeType[i].Key,
                        Gender = CharaMakeType[i].Gender,
                        Race   = CharaMakeType[i].Race.Key,
                        Tribe  = CharaMakeType[i].Tribe.Key
                    };
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        feature.Features = FeatureD(CharaMakeType[i].FacialFeatureIcon);
                        ExdData.CharaMakeFeatures2.Add(CharaMakeType[i].Key, feature);

                        SheetName.Text  = "CharaMakeType";
                        PB.Value        = (i * 100) / size;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                size = Realm.GameData.GetSheet <SaintCoinach.Xiv.BGM>().Count();
                using (TextFieldParser parser = new TextFieldParser(new StringReader(Properties.Resources.BGM)))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int rowCount = 0;
                    parser.ReadFields();
                    while (!parser.EndOfData)
                    {
                        ExdData.BGM bGM = new ExdData.BGM();
                        //Processing row
                        string[] fields = parser.ReadFields();
                        int fCount      = 0;
                        bGM.Index       = int.Parse(fields[0]);
                        foreach (string field in fields)
                        {
                            fCount++;

                            if (fCount == 2)
                            {
                                bGM.Name = field;
                            }
                            if (fCount == 3)
                            {
                                bGM.Location = field;
                            }
                            if (fCount == 4)
                            {
                                bGM.Note = field;
                            }
                        }
                        this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                        {
                            rowCount++;
                            ExdData.BGMs.Add(bGM.Index, bGM);
                            ZonePage.Zonepage.BGMBox.Items.Add(new ExdData.BGM {
                                Index = bGM.Index, Name = bGM.Name, Location = bGM.Location
                            });

                            SheetName.Text  = "BGMs";
                            PB.Value        = (rowCount * 100) / size;
                            Percentage.Text = $"{PB.Value}%";
                        });
                    }
                    parser.Dispose();
                }
                size = 7756;
                using (TextFieldParser parser = new TextFieldParser(new StringReader(Properties.Resources.actiontimeline)))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int rowCount = 0;
                    parser.ReadFields();
                    while (!parser.EndOfData)
                    {
                        ExdData.Emote emote = new ExdData.Emote();
                        //Processing row
                        string[] fields = parser.ReadFields();
                        int fCount      = 0;
                        emote.Index     = int.Parse(fields[0]);
                        foreach (string field in fields)
                        {
                            fCount++;

                            if (fCount == 2)
                            {
                                emote.Name = field;
                            }
                        }
                        this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                        {
                            rowCount++;
                            if (emote.Name.Contains("normal/"))
                            {
                                emote.Name = emote.Name.Remove(0, 7).ToString(); emote.Realist = true;
                            }
                            if (emote.Name.Contains("mon_sp/"))
                            {
                                emote.Name = emote.Name.Remove(0, 7).ToString(); emote.SpeacialReal = true;
                            }
                            if (emote.Name.Contains("battle/"))
                            {
                                emote.Name = emote.Name.Remove(0, 7).ToString(); emote.BattleReal = true;
                            }
                            if (emote.Name.Contains("human_sp/"))
                            {
                                emote.Name = emote.Name.Remove(0, 9).ToString(); emote.SpeacialReal = true;
                            }
                            ExdData.Emotes.Add(emote.Index, emote);
                            if (emote.Realist == true)
                            {
                                ModelDataPage.Page.PlayerList.Items.Add(new ExdData.Emote {
                                    Index = emote.Index, Name = emote.Name
                                });
                            }
                            else if (emote.SpeacialReal == true)
                            {
                                ModelDataPage.Page.MonsterList.Items.Add(new ExdData.Emote {
                                    Index = emote.Index, Name = emote.Name
                                });
                            }
                            else if (emote.BattleReal == true)
                            {
                                ModelDataPage.Page.BattleList.Items.Add(new ExdData.Emote {
                                    Index = emote.Index, Name = emote.Name
                                });
                            }
                            ModelDataPage.Page.AllList.Items.Add(new ExdData.Emote {
                                Index = emote.Index, Name = emote.Name
                            });
                            SheetName.Text  = "Emotes";
                            PB.Value        = (rowCount * 100) / size;
                            Percentage.Text = $"{PB.Value}%";
                        });
                    }
                    parser.Dispose();
                }
                size            = 3000;
                ExdData.Emotesx = ExdData.Emotes.Values.ToArray();
                using (TextFieldParser parser = new TextFieldParser(new StringReader(Properties.Resources.MonsterList)))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int rowCount = 0;
                    parser.ReadFields();
                    while (!parser.EndOfData)
                    {
                        rowCount++;
                        ExdData.Monster monster = new ExdData.Monster();
                        //Processing row
                        string[] fields = parser.ReadFields();
                        int fCount      = 0;
                        monster.Index   = int.Parse(fields[0]);
                        foreach (string field in fields)
                        {
                            fCount++;

                            if (fCount == 2)
                            {
                                monster.Name = field;
                            }
                        }
                        if (monster.Name.Length >= 1)
                        {
                            monster.Real = true;
                        }
                        ExdData.Monsters.Add(monster.Index, monster);
                        this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                        {
                            if (monster.Real)
                            {
                                ResourcePage.Resourcepage.ModelCharaList.Items.Add(new ExdData.Monster {
                                    Index = monster.Index, Name = monster.Name
                                });
                            }

                            SheetName.Text  = "ModelChara";
                            PB.Value        = (rowCount * 100) / size;
                            Percentage.Text = $"{PB.Value}%";
                        });
                    }
                    parser.Dispose();
                }
                ExdData.MonsterX = ExdData.Monsters.Values.ToArray();
                size             = TitleSheet.Count;
                for (int i = 0; i < size; i++)
                {
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        string Title = TitleSheet[i].Feminine;
                        if (Title.Length <= 0)
                        {
                            Title = "No Title";
                        }
                        ResourcePage.Resourcepage.TitleBox.Items.Add(Title);

                        SheetName.Text  = "Title";
                        PB.Value        = (i * 100) / size;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
                size = StatusSheet.Count;
                for (int i = 0; i < size; i++)
                {
                    if (StatusIds.Contains(StatusSheet[i].VFX) || StatusSheet[i].VFX <= 0 && i != 0)
                    {
                        continue;
                    }
                    this.Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                    {
                        StatusIds.Add(StatusSheet[i].VFX);
                        string name = StatusSheet[i].Name.ToString();
                        if (name.Length <= 0)
                        {
                            name = "None";
                        }
                        PropertiesPage.Page.StatusBox.Items.Add(new ComboBoxItem()
                        {
                            Content = name, Tag = StatusSheet[i].Key
                        });

                        SheetName.Text  = "Status Effect";
                        PB.Value        = (i * 100) / size;
                        Percentage.Text = $"{PB.Value}%";
                    });
                }
            }).ContinueWith(t => this.Dispatcher.Invoke(() =>
            {
                MainWindow.Main.InitializeModel();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }));
        }
Ejemplo n.º 28
0
        public CsvFile ReadFile(String fullname, dtoCsvSettings settings, int lines)
        {
            CsvFile         result = null;
            TextFieldParser parser = null;

            try{
                result = new CsvFile();
                using (parser = new TextFieldParser(fullname, System.Text.Encoding.Default))
                {
                    parser.Delimiters     = settings.GetColumnDelimiters;
                    parser.TrimWhiteSpace = true;
                    long rowIndex = 1;
                    while ((lines <= 0 && !parser.EndOfData) || (rowIndex <= lines))
                    {
                        try
                        {
                            string[] parts = parser.ReadFields();
                            if (!(settings.RowsToSkip > 0 && rowIndex <= settings.RowsToSkip))
                            {
                                if (rowIndex == 1 && settings.FirstRowColumnNames)
                                {
                                    List <TextColumn> columns = new List <TextColumn>();
                                    columns.AddRange((from i in Enumerable.Range(1, parts.Count()).ToList()
                                                      select new TextColumn()
                                    {
                                        Number = i, Value = parts[i - 1]
                                    }).ToList());
                                    result.ColumHeader.AddRange(columns);
                                }
                                else
                                {
                                    List <string> cells = parts.ToList();
                                    if (cells.Where(c => !string.IsNullOrEmpty(c)).Any())
                                    {
                                        TextRow row = new TextRow();
                                        row.AddRange(cells);
                                        result.Rows.Add(row);
                                    }
                                    else
                                    {
                                        rowIndex--;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                        rowIndex++;
                    }
                    if (result.Rows.Count > 0)
                    {
                        int colCount = result.ColumHeader.Count;
                        int colToAdd = (from r in result.Rows select r.Count).Max();
                        if (colToAdd > 0 && colCount < colToAdd)
                        {
                            result.ColumHeader.AddRange((from i in Enumerable.Range(colCount + 1, colToAdd - colCount).ToList() select new TextColumn()
                            {
                                Number = i
                            }).ToList());
                        }
                        colCount = result.ColumHeader.Count;
                        foreach (TextRow tRow in result.Rows.Where(r => r.Count < colCount).ToList())
                        {
                            tRow.AddRange((from i in Enumerable.Range(1, colCount - tRow.Count).ToList() select "").ToList());
                        }
                    }
                }
                parser.Dispose();
                parser = null;
            }
            catch (Exception ex) {
                if (parser != null)
                {
                    parser.Dispose();
                }
                result = null;
            }
            return(result);
        }
Ejemplo n.º 29
0
        private DataTable ReadCSVFileUsingVB(ref List <string> csvRows, ref List <string> emptyRowWarnings, ref int columnCount)
        {
            string localFileName = Job.FileName;

            if (Job.IsHavingSpecialHeaderAndOrFooter)
            {
                localFileName = Job.FileNameWithoutHeaderAndOrFooter;
            }

            if (!File.Exists(localFileName))
            {
                return(new DataTable());
            }
            TextFieldParser parser = new TextFieldParser(localFileName);

            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(string.IsNullOrEmpty(DataSource.Delimiter) ? "," : DataSource.Delimiter);
            bool      columnInformationTaken = false;
            DataTable table  = new DataTable();
            bool      failed = false;

            while (!parser.EndOfData)
            {
                string[] fields = parser.ReadFields();
                if (!columnInformationTaken)
                {
                    if (DataSource.IsFirstRowHeader)
                    {
                        foreach (string field in fields)
                        {
                            table.Columns.Add(field);
                        }
                        columnCount = table.Columns.Count;
                    }
                    else
                    {
                        foreach (IdpeAttribute attribute in DataSource.AcceptableAttributes)
                        {
                            table.Columns.Add(attribute.Name);
                        }
                        if (table.Columns.Count != fields.Length)
                        {
                            DataSource.TraceError("1.Data source attribute count and data fed is not equal, could not parse data! Acceptable attributes = {0}, input file columns = {1}",
                                                  table.Columns.Count, fields.Length);
                            failed = true;
                            break;
                        }
                        table.Rows.Add(fields);
                        columnCount = fields.Length;
                    }
                    columnInformationTaken = true;
                }

                else
                {
                    if (table.Columns.Count != fields.Length)
                    {
                        DataSource.TraceError("2.Data source attribute count and data fed is not equal, could not parse data! Acceptable attributes = {0}, input file columns = {1}",
                                              table.Columns.Count, fields.Length);
                        failed = true;
                        break;
                    }
                    table.Rows.Add(fields);
                }

                string commaSeparatedList = fields.Aggregate((a, x) => a + "\",\"" + x).ToString();
                csvRows.Add("\"" + commaSeparatedList + "\"");
            }
            parser.Close();
            if (failed)
            {
                parser.Dispose();
                parser = null;
                table.Dispose();
                table = null;
                return(new DataTable());
            }
            else
            {
                return(table);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Sets the results from a stream reader represeting a csv file previously exported by this webpart
        /// </summary>
        /// <param name="reader"></param>
        public void SetFromCsv(StreamReader reader)
        {
            this.Reset();
            this._filledFromResults = false;
            this._pageCount         = 1;

            var parser = new TextFieldParser(reader);

            parser.Delimiters                = new string[] { "," };
            parser.TrimWhiteSpace            = true;
            parser.HasFieldsEnclosedInQuotes = true;
            parser.TextFieldType             = FieldType.Delimited;

            if (parser.EndOfData)
            {
                // they gave us an empty stream
                return;
            }

            try
            {
                // the first line is expected to have headers so we clear it
                var headers = parser.ReadFields().Select(f => f.ToUpper()).ToArray();
                var mappers = new List <Action <DataGridViewRow, string> >(headers.Length);
                Func <string, Action <DataGridViewRow, string> > mappingBinder = (string field) => (row, value) => row.Cells[field].Value = value;

                for (var i = 0; i < headers.Length; i++)
                {
                    switch (headers[i])
                    {
                    case "DISTINGUISHEDNAME":
                        mappers.Add(mappingBinder(StringLiterals.DistinguishedName));
                        break;

                    case "OBJECTCLASS":
                        mappers.Add(mappingBinder(StringLiterals.ObjectClass));
                        break;

                    case "ATTRIBUTE":
                        mappers.Add(mappingBinder(StringLiterals.Attribute));
                        break;

                    case "ERROR":
                        mappers.Add(mappingBinder(StringLiterals.Error));
                        break;

                    case "VALUE":
                        mappers.Add(mappingBinder(StringLiterals.Value));
                        break;

                    case "UPDATE":
                        mappers.Add(mappingBinder(StringLiterals.Update));
                        break;

                    case "PROPOSEDACTION":
                        mappers.Add(mappingBinder(StringLiterals.ProposedAction));
                        break;

                    case "ACTION":
                        mappers.Add((DataGridViewRow row, string value) =>
                        {
                            row.Cells[StringLiterals.Action].Value = new string[] { "EDIT", "REMOVE", "COMPLETE", "UNDO", "FAIL" }.Contains(value) ? value : string.Empty;
                        });
                        break;
                    }
                }

                // now loop on all the rows and return them to the grid
                while (!parser.EndOfData)
                {
                    var row    = this.Rows[this.Rows.Add()];
                    var fields = parser.ReadFields();

                    for (var i = 0; i < fields.Length; i++)
                    {
                        // map the field into the row
                        mappers[i](row, fields[i]);
                    }
                }
            }
            catch (Exception err)
            {
                this.OnStatusUpdate?.Invoke(StringLiterals.Exception + "Import CSV Line: [" + parser.LineNumber + "] " + err.Message);
            }
            finally
            {
                parser.Dispose();
            }

            if (this.RowCount >= 1)
            {
                this.Sort(this.Columns[StringLiterals.DistinguishedName], ListSortDirection.Ascending);
                this.CurrentCell = this.Rows[0].Cells[StringLiterals.DistinguishedName];
            }

            this._totalResults = this.RowCount;
        }