Example #1
0
    private static DataTable GetDataTableFromCSVFile(string csv_file_path)
    {
        DataTable csvData = new DataTable();

        try
        {
        using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
        {
            csvReader.SetDelimiters(new string[] { "," });
            csvReader.HasFieldsEnclosedInQuotes = true;
            string[] colFields = csvReader.ReadFields();

            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }

            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == "")
                    {
                        fieldData[i] = null;
                    }
                }

                csvData.Rows.Add(fieldData);
             }
         }
         }
         catch (Exception ex)
         {
         }

         return csvData;
    }
Example #2
0
        public DataTable CSVToTable(string filePath, D_EDI_Entity dee)
        {
            DataTable csvData = new DataTable();
            int       count   = 1;

            string firstColHeader = "2";   //Todo:何を設定するかは後で

            try
            {
                using (TextFieldParser csvReader = new TextFieldParser(filePath, Encoding.GetEncoding(932), true))
                {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    //read column names
                    string[] colFields = csvReader.ReadFields();
                    char     c         = 'A';

                    int errNo = 0;

                    //CSVファイルの項目数チェック
                    if (colFields.Length != COL_COUNT)
                    {
                        errNo = 1;

                        while (colFields.Count() > COL_COUNT)
                        {
                            colFields = colFields.Take(colFields.Count() - 1).ToArray();
                        }

                        while (colFields.Count() < COL_COUNT)
                        {
                            Array.Resize(ref colFields, colFields.Length + 1);
                            colFields[colFields.Length - 1] = null;
                        }
                    }

                    ErrCheck(colFields, ref errNo);

                    //最終項目にエラー番号をセット
                    Array.Resize(ref colFields, colFields.Length + 1);
                    colFields[colFields.Length - 1] = errNo.ToString();

                    //1行目の一番左の項目が”B”でなければ1行目は無視する
                    if (!colFields[0].Equals("B"))
                    {
                        firstColHeader = "1";
                    }
                    else
                    {
                        dee.OrderDetailsSu++;
                    }

                    foreach (string column in colFields)
                    {
                        if (firstColHeader.Equals("1")) //first row is column name
                        {
                            if (!csvData.Columns.Contains(column))
                            {
                                DataColumn datacolumn = new DataColumn(column);
                                datacolumn.AllowDBNull = true;
                                csvData.Columns.Add(datacolumn);
                            }
                            else
                            {
                                DataColumn datacolumn = new DataColumn(column + "_" + count++);
                                datacolumn.AllowDBNull = true;
                                csvData.Columns.Add(datacolumn);
                            }
                        }
                        else//2
                        {
                            DataColumn datacolumn = new DataColumn(c++.ToString());
                            datacolumn.AllowDBNull = true;
                            csvData.Columns.Add(datacolumn);
                        }
                    }

                    if (firstColHeader.Equals("2"))  // first row is data
                    {
                        csvData.Rows.Add(colFields); //add first row as data row

                        if (errNo == 0)
                        {
                            dee.ImportDetailsSu++;
                        }
                        else
                        {
                            dee.ErrorSu++;
                        }
                    }

                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();

                        dee.OrderDetailsSu = dee.OrderDetailsSu + 1;

                        //CSVファイルの項目数チェック
                        if (fieldData.Length != COL_COUNT)
                        {
                            errNo = 1;
                        }


                        while (fieldData.Count() > COL_COUNT)
                        {
                            fieldData = fieldData.Take(fieldData.Count() - 1).ToArray();
                        }

                        while (fieldData.Count() < COL_COUNT)
                        {
                            Array.Resize(ref fieldData, fieldData.Length + 1);
                            fieldData[fieldData.Length - 1] = null;
                        }

                        //Making empty value as null
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }

                        ErrCheck(fieldData, ref errNo);

                        //最終項目にエラー番号をセット
                        Array.Resize(ref fieldData, fieldData.Length + 1);
                        fieldData[fieldData.Length - 1] = errNo.ToString();

                        csvData.Rows.Add(fieldData);

                        if (errNo == 0)
                        {
                            dee.ImportDetailsSu++;
                        }
                        else
                        {
                            dee.ErrorSu++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(csvData);
        }
Example #3
0
        protected override void Seed(BandMate.Models.ApplicationDbContext context)
        {
            //Seed the subscription types
            SubscriptionType monthlySubscription = new SubscriptionType();

            monthlySubscription.Name  = "Monthly Subscription";
            monthlySubscription.Price = 9.99d;

            SubscriptionType annualSubscription = new SubscriptionType();

            annualSubscription.Name  = "Annual Subscription";
            annualSubscription.Price = 108.00d;

            context.SubscriptionTypes.Add(monthlySubscription);
            context.SubscriptionTypes.Add(annualSubscription);

            context.SaveChanges();

            //Seed the product types
            ProductType standardProductType = new ProductType();

            standardProductType.Name = "Standard Product";

            ProductType garmentProductType = new ProductType();

            garmentProductType.Name = "Garment";

            context.ProductTypes.Add(standardProductType);
            context.ProductTypes.Add(garmentProductType);

            context.SaveChanges();

            ////Seed the sizes
            //Size small = new Size();
            //small.Name = "Small";
            //small.Abbreviation = "S";

            //Size medium = new Size();
            //medium.Name = "Medium";
            //medium.Abbreviation = "M";

            //Size large = new Size();
            //large.Name = "Large";
            //large.Abbreviation = "L";

            //Size xLarge = new Size();
            //xLarge.Name = "X-Large";
            //xLarge.Abbreviation = "XL";

            //Size xxLarge = new Size();
            //xxLarge.Name = "XX-Large";
            //xxLarge.Abbreviation = "XXL";

            //context.Sizes.Add(small);
            //context.Sizes.Add(medium);
            //context.Sizes.Add(large);
            //context.Sizes.Add(xLarge);
            //context.Sizes.Add(xxLarge);

            //context.SaveChanges();

            //Seed notification preferences
            NotificationPreference emailPreference = new NotificationPreference();

            emailPreference.Name = "Email";

            NotificationPreference textPreference = new NotificationPreference();

            textPreference.Name = "Text";

            context.NotificationPreferences.Add(emailPreference);
            context.NotificationPreferences.Add(textPreference);

            context.SaveChanges();

            //Seed States table with all US States from CSV
            string seedFile = "~/CSV/SeedData/";//states.csv removed from end of seedFile
            string filePath = GetMapPath(seedFile);

            bool fileExists = File.Exists(filePath + "states.csv");

            if (fileExists)
            {
                List <State> states = new List <State>();
                using (TextFieldParser parser = new TextFieldParser(filePath + "states.csv"))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    State state;
                    while (!parser.EndOfData)
                    {
                        string[] fields = parser.ReadFields();
                        if (fields.Any(x => x.Length == 0))
                        {
                            Console.WriteLine("We found an empty value in your CSV. Please check your file and try again.\nPress any key to return to main menu.");
                            Console.ReadKey(true);
                        }
                        state              = new State();
                        state.Name         = fields[0];
                        state.Abbreviation = fields[1];
                        states.Add(state);
                    }
                }
                context.States.AddOrUpdate(c => c.Abbreviation, states.ToArray());
                context.SaveChanges();
            }
        }
        private bool AnimalTest2()
        {
            for (int x = 0; x < 2; x++)
            {
                for (int y = 0; y < 1000; y++)
                {
                    string[] fields = null;

                    var lines     = File.ReadLines(Path.Combine(Directory.GetCurrentDirectory(), "animal.csv"));
                    int lineCount = File.ReadAllLines(Path.Combine(Directory.GetCurrentDirectory(), "animal.csv")).Length;

                    if (y > lineCount - 1)
                    {
                        break;
                    }

                    var line = new List <string>(lines)[y];

                    TextFieldParser parser = new TextFieldParser(new StringReader(line));
                    parser.HasFieldsEnclosedInQuotes = true;
                    parser.SetDelimiters(",");
                    fields = parser.ReadFields();

                    using (Animal animal = new Animal(x == 0 ? _legacySourcePath : _modernSourcePath))
                    {
                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalName, ComparisonType.EqualTo, fields[0]);
                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalRecd, ComparisonType.EqualTo, fields[1]);

                        if (fields[2].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalCodes, ComparisonType.EqualTo, fields[2]);
                        }

                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalAdded, ComparisonType.EqualTo, DateTime.Parse(fields[3]));

                        if (fields[4].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalRabies, ComparisonType.EqualTo, fields[4]);
                        }

                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalBirthday, ComparisonType.EqualTo, DateTime.Parse(fields[5]));
                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalVisit, ComparisonType.EqualTo, int.Parse(fields[6]));
                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalFlags, ComparisonType.EqualTo, int.Parse(fields[7]));
                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalSex, ComparisonType.EqualTo, fields[8]);

                        if (fields[9].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalAllergy, ComparisonType.EqualTo, fields[9]);
                        }

                        if (fields[10].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalBreed, ComparisonType.EqualTo, fields[10]);
                        }

                        if (fields[11].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalSpecies, ComparisonType.EqualTo, fields[11]);
                        }

                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalWeight, ComparisonType.EqualTo, fields[12]);

                        if (fields[13].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalRegistration, ComparisonType.EqualTo, fields[13]);
                        }

                        if (fields[14].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalMeasure, ComparisonType.EqualTo, fields[14]);
                        }

                        if (fields[15].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalColor, ComparisonType.EqualTo, fields[15]);
                        }

                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalClient, ComparisonType.EqualTo, fields[16]);

                        if (fields[17].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalPhoto, ComparisonType.EqualTo, fields[17]);
                        }

                        if (!fields[18].Contains("1900"))
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalSuspend, ComparisonType.EqualTo, DateTime.Parse(fields[18]));
                        }

                        if (!fields[19].Contains("1900"))
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalDeath, ComparisonType.EqualTo, DateTime.Parse(fields[19]));
                        }

                        if (fields[20].Length > 0)
                        {
                            animal.AddFilterCriteria(Animal.AnimalFields.AnimalLocator, ComparisonType.EqualTo, fields[20]);
                        }

                        animal.AddFilterCriteria(Animal.AnimalFields.AnimalLastCompany, ComparisonType.EqualTo, int.Parse(fields[21]));

                        var animalList = animal.AnimalList();

                        if (animalList.Count == 0)
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
Example #5
0
        public void MakeResidentList()
        {
            Residents = new Dictionary <int, Resident>();

            try
            {
                using (TextFieldParser parser = new TextFieldParser(new StringReader(Resources.enpcresident_exh_en)))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int rowCount = 0;
                    parser.ReadFields();
                    while (!parser.EndOfData)
                    {
                        //Processing row
                        rowCount++;
                        string[] fields = parser.ReadFields();
                        int      fCount = 0;

                        int    id   = 0;
                        string name = "";

                        foreach (string field in fields)
                        {
                            fCount++;

                            if (fCount == 1)
                            {
                                id = int.Parse(field);
                            }

                            if (fCount == 2)
                            {
                                name = field;
                            }
                        }
                        //  Console.WriteLine($"{id} - {name}");
                        Residents.Add(id, new Resident {
                            Index = id, Name = name
                        });
                    }
                    //    Console.WriteLine($"{rowCount} residentNames read");
                }
                using (TextFieldParser parser = new TextFieldParser(new StringReader(Resources.enpcbase_exh)))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int rowCount = 0;
                    parser.ReadFields();
                    while (!parser.EndOfData)
                    {
                        //Processing row
                        rowCount++;
                        string[] fields = parser.ReadFields();
                        int      fCount = 0;

                        int         id         = 0;
                        List <byte> customize  = new List <byte>();
                        GearSet     gear       = new GearSet();
                        int         dDataCount = 0;
                        int         modelId    = 0;

                        foreach (string field in fields)
                        {
                            fCount++;

                            if (fCount == 1)
                            {
                                id = int.Parse(field);
                            }

                            if (fCount == 37)
                            {
                                modelId = int.Parse(field);
                            }

                            if (fCount >= 38 && fCount <= 63)
                            {
                                try
                                {
                                    customize.Add(byte.Parse(field));
                                    dDataCount++;
                                }
                                catch (Exception exc)
                                {
                                    throw exc;
                                    //Console.WriteLine("Invalid: " + field);
                                }
                            }

                            if (fCount == 67)
                            {
                                gear.MainWep = EquipmentFlyOut.CommaToWepTuple(field);
                            }

                            if (fCount == 69)
                            {
                                gear.OffWep = EquipmentFlyOut.CommaToWepTuple(field);
                            }

                            if (fCount >= 71 && fCount <= 90)
                            {
                                Int32 fieldint = 0;

                                if (fCount != 73)
                                {
                                    fieldint = Int32.Parse(field);
                                }

                                var bytes = BitConverter.GetBytes(fieldint);

                                var model = BitConverter.ToUInt16(bytes, 0);

                                switch (fCount - 1)
                                {
                                case 70:
                                    gear.HeadGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 71:
                                    gear.HeadGear = new GearTuple(gear.HeadGear.Item1, gear.HeadGear.Item2,
                                                                  int.Parse(field));
                                    break;

                                case 72:
                                    break;

                                case 73:
                                    gear.BodyGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 74:
                                    gear.BodyGear = new GearTuple(gear.BodyGear.Item1, gear.BodyGear.Item2,
                                                                  int.Parse(field));
                                    break;

                                case 75:
                                    gear.HandsGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 76:
                                    gear.HandsGear = new GearTuple(gear.HandsGear.Item1, gear.HandsGear.Item2,
                                                                   int.Parse(field));
                                    break;

                                case 77:
                                    gear.LegsGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 78:
                                    gear.LegsGear = new GearTuple(gear.LegsGear.Item1, gear.LegsGear.Item2,
                                                                  int.Parse(field));
                                    break;

                                case 79:
                                    gear.FeetGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 80:
                                    gear.FeetGear = new GearTuple(gear.FeetGear.Item1, gear.FeetGear.Item2,
                                                                  int.Parse(field));
                                    break;

                                case 81:
                                    gear.EarGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 82:
                                    gear.EarGear = new GearTuple(gear.EarGear.Item1, gear.EarGear.Item2,
                                                                 int.Parse(field));
                                    break;

                                case 83:
                                    gear.NeckGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 84:
                                    gear.NeckGear = new GearTuple(gear.NeckGear.Item1, gear.NeckGear.Item2,
                                                                  int.Parse(field));
                                    break;

                                case 85:
                                    gear.WristGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 86:
                                    gear.WristGear = new GearTuple(gear.WristGear.Item1, gear.WristGear.Item2,
                                                                   int.Parse(field));
                                    break;

                                case 87:
                                    gear.LRingGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 88:
                                    gear.LRingGear = new GearTuple(gear.LRingGear.Item1, gear.LRingGear.Item2,
                                                                   int.Parse(field));
                                    break;

                                case 89:
                                    gear.RRingGear = new GearTuple(model, bytes[2], 0);
                                    break;

                                case 90:
                                    gear.RRingGear = new GearTuple(gear.RRingGear.Item1, gear.RRingGear.Item2,
                                                                   int.Parse(field));
                                    break;
                                }
                            }
                        }
                        //            Console.WriteLine($"{id} - {wepCSV} - {dDataCount}");

                        gear.Customize = customize.ToArray();

                        try
                        {
                            Residents[id].Gear = gear;
                        }
                        catch (KeyNotFoundException)
                        {
                            Console.WriteLine("Did not find corresponding entry for: " + id);
                        }
                    }
                    //    Console.WriteLine($"{rowCount} idLookMappings read");
                }
            }
            catch (Exception exc)
            {
                Residents = null;
#if DEBUG
                throw exc;
#endif
            }
        }
Example #6
0
        public void EmoteList()
        {
            Emotes = new Dictionary <int, Emote>();
            {
                try
                {
                    using (TextFieldParser parser = new TextFieldParser(new StringReader(Resources.actiontimeline)))
                    {
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");
                        int rowCount = 0;
                        parser.ReadFields();
                        while (!parser.EndOfData)
                        {
                            rowCount++;
                            Emote emote = new 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;
                                }
                            }
                            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;
                            }
                            //    Console.WriteLine($"{rowCount} - {emote.Name}");
                            Emotes.Add(emote.Index, emote);
                        }
                        //    Console.WriteLine($"{rowCount} Emotes read");
                    }
                }

                catch (Exception exc)
                {
                    Emotes = null;
#if DEBUG
                    throw exc;
#endif
                }
            }
        }
Example #7
0
        /// <summary>
        /// Read file
        /// </summary>
        /// <param name="data">The target SIMCA data</param>
        /// <param name="graph">The target graph</param>
        private void ReadFile(SimcaData data, UserControlSimcaGraph graph)
        {
            string formatDlgTitle = "Select {0} data file";
            string formatErrMsg   = string.Empty;

            // type
            string typeName  = "score";
            Label  pathLabel = _labelScorePath;

            if (data == _scoreData)
            {
                typeName  = "score";
                pathLabel = _labelScorePath;
            }

            if (data == _loadingData)
            {
                typeName  = "loding";
                pathLabel = _labelLoadingPath;
            }

            if (data == _sPlotData)
            {
                typeName  = "S";
                pathLabel = _labelSPlotPath;
            }

            // Show file open dialog
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.FileName         = string.Empty;
            ofd.InitialDirectory = string.Empty;
            ofd.Filter           = "csv file(*.csv)|*.csv";
            ofd.FilterIndex      = 0;
            ofd.Title            = string.Format(formatDlgTitle, typeName);
            ofd.RestoreDirectory = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                // Tab select
                _tabControlPlot.SelectedIndex = (int)data.DataType;

                // Grid tab select
                if (_formGridInstance != null)
                {
                    _formGridInstance.TabSelect(data.DataType);
                }

                // Read file data
                SimcaData.SIMCA_READ_ERR_CODE errorCode = SimcaData.SIMCA_READ_ERR_CODE.OK;
                data.Clear();
                try
                {
                    using (TextFieldParser parser = new TextFieldParser(
                               ofd.FileName,
                               System.Text.Encoding.GetEncoding("Shift_JIS")))
                    {
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");
                        while (parser.EndOfData == false)
                        {
                            errorCode = data.Add(parser.ReadFields(), _dbData);
                            if (errorCode != SimcaData.SIMCA_READ_ERR_CODE.OK)
                            {
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    formatErrMsg = ex.Message;
                    errorCode    = SimcaData.SIMCA_READ_ERR_CODE.NG_READ;
                }

                if (errorCode == SimcaData.SIMCA_READ_ERR_CODE.OK)
                {
                    errorCode = data.CheckData(_dbData.GetSelectedMatrixIndex());
                }

                if (errorCode == SimcaData.SIMCA_READ_ERR_CODE.NG_CLASS)
                {
                    string workMsg = string.Format(WARN_MSG_FMT_MSG_CLASS, Path.GetFileName(ofd.FileName));
                    MessageBox.Show(
                        workMsg,
                        "Warning",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
                    errorCode = SimcaData.SIMCA_READ_ERR_CODE.OK;
                }

                if (errorCode == SimcaData.SIMCA_READ_ERR_CODE.OK)
                {
                    graph.SetData(data);
                    _filePath[(int)data.DataType] = ofd.FileName;
                    LabelSetText(pathLabel, ofd.FileName);

                    if (_formGridInstance != null)
                    {
                        _formGridInstance.Update(data);
                    }
                    return;
                }

                if (errorCode == SimcaData.SIMCA_READ_ERR_CODE.NG_DATA)
                {
                    formatErrMsg = ERR_MSG_FMT_FILE_READ_DATA;
                }
                else if (errorCode == SimcaData.SIMCA_READ_ERR_CODE.NG_READ)
                {
                    // formatErrMsg = ERR_MSG_FMT_READ_FILE;
                }
                else
                {
                    formatErrMsg = ERR_MSG_FMT_FILE_READ_FMT;
                }

                string work = string.Format(formatErrMsg, typeName, Path.GetFileName(ofd.FileName));
                work = char.ToUpper(work[0]) + work.Substring(1);
                MessageBox.Show(
                    work,
                    "Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                graph.SetDefaultData();
                data.Clear();
                if (_formGridInstance != null)
                {
                    _formGridInstance.Update(data);
                }

                pathLabel.Text = string.Empty;
                _filePath[(int)data.DataType] = string.Empty;
            }
        }
Example #8
0
        /// <summary>
        /// Load file via VB TextFieldParser
        /// </summary>
        /// <returns></returns>
        public (bool Success, List <DataItem>, List <DataItemInvalid>, int EmptyLineCount) LoadCsvFileTextFieldParser()
        {
            mHasException = false;

            var validRows   = new List <DataItem>();
            var invalidRows = new List <DataItemInvalid>();
            var validateBad = 0;

            int index = 0;

            int   district    = 0;
            int   grid        = 0;
            int   ucrNcicCode = 0;
            float latitude    = 0;
            float longitude   = 0;

            var emptyLineCount = 0;
            var line           = "";

            try
            {
                /*
                 * If interested in blank line count
                 */
                using (var reader = File.OpenText(_inputFileName))
                {
                    while ((line = reader.ReadLine()) != null) // EOF
                    {
                        if (string.IsNullOrWhiteSpace(line))
                        {
                            emptyLineCount++;
                        }
                    }
                }

                using (var parser = new TextFieldParser(_inputFileName))
                {
                    parser.Delimiters = new[] { "," };
                    while (true)
                    {
                        string[] parts = parser.ReadFields();

                        if (parts == null)
                        {
                            break;
                        }

                        index      += 1;
                        validateBad = 0;

                        if (parts.Length != 9)
                        {
                            invalidRows.Add(new DataItemInvalid()
                            {
                                Row  = index,
                                Line = string.Join(",", parts)
                            });

                            continue;
                        }

                        // Skip first row which in this case is a header with column names
                        if (index <= 1)
                        {
                            continue;
                        }

                        /*
                         * These columns are checked for proper types
                         */
                        var validRow =
                            DateTime.TryParse(parts[0], out var cdatetime) &&
                            float.TryParse(parts[7].Trim(), out latitude) &&
                            float.TryParse(parts[8].Trim(), out longitude) &&
                            int.TryParse(parts[2], out district) &&
                            int.TryParse(parts[4], out grid) &&
                            !string.IsNullOrWhiteSpace(parts[5]) &&
                            int.TryParse(parts[6], out ucrNcicCode);

                        /*---------------------------------------------------------------
                        * Questionable fields
                        *  ---------------------------------------------------------------*/
                        if (string.IsNullOrWhiteSpace(parts[1]))
                        {
                            validateBad += 1;
                        }
                        if (string.IsNullOrWhiteSpace(parts[3]))
                        {
                            validateBad += 1;
                        }

                        // NICI code must be 909 or greater
                        if (ucrNcicCode < 909)
                        {
                            validateBad += 1;
                        }

                        if (validRow)
                        {
                            validRows.Add(new DataItem()
                            {
                                Id          = index,
                                Date        = cdatetime,
                                Address     = parts[1],
                                District    = district,
                                Beat        = parts[3],
                                Grid        = grid,
                                Description = parts[5],
                                NcicCode    = ucrNcicCode,
                                Latitude    = latitude,
                                Longitude   = longitude,
                                Inspect     = validateBad > 0
                            });
                        }
                        else
                        {
                            // fields to review in specific rows
                            invalidRows.Add(new DataItemInvalid()
                            {
                                Row  = index,
                                Line = string.Join(",", parts)
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                mHasException  = true;
                mLastException = ex;
            }

            return(IsSuccessFul, validRows, invalidRows, emptyLineCount);
        }
Example #9
0
        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                return;

                OpenFileDialog op = new OpenFileDialog();
                op.Filter = "Spread Sheet files (*.csv)|*.csv|All files (*.csv)|*.csv";
                if (op.ShowDialog() == DialogResult.OK)
                {
                    using (TextFieldParser parser = new TextFieldParser(op.FileName))
                    {
                        dt.Rows.Clear();
                        DateTime?d  = null;
                        DateTime d1 = DateTime.Now;
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");
                        int a = 0;
                        int c = 0;
                        while (!parser.EndOfData)
                        {
                            //Processing row
                            a += 1;
                            DataRow rd = dt.NewRow();
                            // MessageBox.Show(a.ToString());
                            string[] fields = parser.ReadFields();
                            c = 0;
                            foreach (string field in fields)
                            {
                                c += 1;
                                //TODO: Process field

                                if (a > 1)
                                {
                                    if (c == 1)
                                    {
                                        rd["ModelName"] = Convert.ToString(field).Trim();
                                    }
                                    else if (c == 2)
                                    {
                                        rd["ModelDescription"] = Convert.ToString(field);
                                    }
                                    else if (c == 3)
                                    {
                                        rd["ModelActive"] = Convert.ToBoolean(field);
                                    }
                                    else if (c == 4)
                                    {
                                        rd["LineName"] = Convert.ToString(field).Trim();
                                    }
                                    else if (c == 5)
                                    {
                                        rd["MCName"] = Convert.ToString(field);
                                    }
                                    else if (c == 6)
                                    {
                                        rd["Limit"] = Convert.ToBoolean(field);
                                    }
                                    else if (c == 7)
                                    {
                                        if (DateTime.TryParse(Convert.ToString(field), out d1))
                                        {
                                            rd["ExpireDate"] = Convert.ToDateTime(field);
                                        }
                                        else
                                        {
                                            rd["ExpireDate"] = d;
                                        }
                                    }
                                }
                                else
                                {
                                    if (c == 1)
                                    {
                                        rd["ModelName"] = "";
                                    }
                                    else if (c == 2)
                                    {
                                        rd["ModelDescription"] = "";
                                    }
                                    else if (c == 3)
                                    {
                                        rd["ModelActive"] = false;
                                    }
                                    else if (c == 4)
                                    {
                                        rd["LineName"] = "";
                                    }
                                    else if (c == 5)
                                    {
                                        rd["MCName"] = "";
                                    }
                                    else if (c == 6)
                                    {
                                        rd["Limit"] = false;
                                    }
                                    else if (c == 7)
                                    {
                                        rd["ExpireDate"] = d;
                                    }
                                }
                            }
                            dt.Rows.Add(rd);
                        }
                    }
                    if (dt.Rows.Count > 0)
                    {
                        dbClss.AddHistory(this.Name, "Import", "Import file CSV in to System", "");
                        ImportData();
                        MessageBox.Show("Import Completed.");

                        DataLoad();
                    }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); dt.Rows.Clear(); }
        }
Example #10
0
        public void QuoteTest2()
        {
            for (int x = 0; x < 2; x++)
            {
                for (int y = 0; y < 1000; y++)
                {
                    string[] fields = null;

                    var lines     = File.ReadLines(Path.Combine(Directory.GetCurrentDirectory(), "quote.csv"));
                    int lineCount = File.ReadAllLines(Path.Combine(Directory.GetCurrentDirectory(), "quote.csv")).Length;

                    if (y > lineCount - 1)
                    {
                        break;
                    }

                    var line = new List <string>(lines)[y];

                    TextFieldParser parser = new TextFieldParser(new StringReader(line));
                    parser.HasFieldsEnclosedInQuotes = true;
                    parser.SetDelimiters(",");
                    fields = parser.ReadFields();

                    using (Quote quote = new Quote(x == 0 ? _legacySourcePath : _modernSourcePath))
                    {
                        if (fields[0].Length > 0)
                        {
                            quote.AddFilterCriteria(Quote.QuoteFields.QuoteName, ComparisonType.EqualTo, fields[0]);
                        }

                        if (fields[1].Length > 0)
                        {
                            quote.AddFilterCriteria(Quote.QuoteFields.QuoteRecd, ComparisonType.EqualTo, fields[1]);
                        }

                        if (!fields[2].Contains("1900"))
                        {
                            quote.AddFilterCriteria(Quote.QuoteFields.QuoteDate, ComparisonType.EqualTo, DateTime.Parse(fields[2]));
                        }

                        if (fields[3].Length > 0)
                        {
                            quote.AddFilterCriteria(Quote.QuoteFields.QuoteDoctor, ComparisonType.EqualTo, fields[3]);
                        }

                        if (fields[5].Length > 0)
                        {
                            quote.AddFilterCriteria(Quote.QuoteFields.QuoteExpiresIn, ComparisonType.EqualTo, Convert.ToInt32(fields[5]));
                        }

                        if (fields[6].Length > 0)
                        {
                            quote.AddFilterCriteria(Quote.QuoteFields.QuoteAnimal, ComparisonType.EqualTo, Convert.ToInt32(fields[6]));
                        }

                        var quoteList = quote.QuoteList();

                        if (quoteList.Count == 0)
                        {
                            Assert.Fail("Match failed on line: " + (y + 1).ToString());
                        }
                    }
                }
            }

            Assert.IsTrue(true, "QuoteTest2 Passed!!");
        }
Example #11
0
    public static void FillCodeStructure()
    {
        int num  = default(int);
        int num2 = default(int);

        try
        {
            ProjectData.ClearProjectError();
            num = -2;
            string     sCodesFilePath = GetCodesFilePath();
            Collection colCodesAndDescriptionHashtable = new Collection();
            int        i = 0;
            if (Strings.Len(Microsoft.VisualBasic.FileSystem.Dir(sCodesFilePath)) != 0)
            {
                TextFieldParser parser = new TextFieldParser(sCodesFilePath, Encoding.Default);
                parser.SetDelimiters(",");
                while (!parser.EndOfData)
                {
                    string currentRow = parser.ReadLine();
                    if (currentRow.IndexOf(",") != -1)
                    {
                        string strIndex            = currentRow.Substring(0, currentRow.IndexOf(","));
                        string sCodeAndDescription = currentRow.Substring(checked (currentRow.IndexOf(",") + 1));
                        colCodesAndDescriptionHashtable.Add(sCodeAndDescription, "I" + strIndex);
                    }
                }
            }
            else
            {
                FillDefaults(colCodesAndDescriptionHashtable);
            }
            Codes.CodesStructureFilled = true;
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Crown);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownPave1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownPave2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownBase);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownSub);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETW);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWPave1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWPave2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWBase);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWSub);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Lane);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LanePave1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LanePave2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneBase);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneSub);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPS);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSPave1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSPave2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSBase);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSSub);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSBaseIn);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSSubIn);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ESUnpaved);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DaylightSub);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Daylight);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DaylightFill);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DaylightCut);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DitchIn);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DitchOut);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.BenchIn);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.BenchOut);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.FlowlineDitch);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LMedDitch);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RMedDitch);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Flange);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Flowline_Gutter);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.TopCurb);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.BottomCurb);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.BackCurb);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.SidewalkIn);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.SidewalkOut);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.HingeCut);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.HingeFill);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Top);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Datum);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Pave);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Pave1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Pave2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Base);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.SubBase);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Gravel);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.TopCurbNew);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.BackCurbNew);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Curb);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Sidewalk);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Hinge);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EOV);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EOVOverlay);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Level);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Mill);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Overlay);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownOverlay);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Barrier);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EBD);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownDeck);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Deck);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Girder);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EBS);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ESL);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DaylightBallast);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ESBS);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DaylightSubballast);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Ballast);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Sleeper);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Subballast);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Rail);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.R1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.R2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.R3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.R4);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.R5);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.R6);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Bridge);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Ditch);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownFin);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownSubBase);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWSubBase);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.MarkedPoint);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Guardrail);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Median);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWOverlay);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.TrenchBottom);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.TrenchDaylight);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.TrenchBedding);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.TrenchBackfill);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Trench);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneBreak);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneBreakOverlay);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Sod);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DaylightStrip);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.sForeslopeStripping);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Stripping);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ChannelFlowline);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Channe_Bottom);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ChannelTop);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ChannelExtension);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ChannelBackslope);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LiningMaterial);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DitchBack);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DitchFace);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DitchTop);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DitchBottom);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Backfill);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.BackfillFace);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DitchLidFace);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LidTop);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DitchBackFill);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Lid);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainBottom);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainBottomOutside);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainTopOutside);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainTopInside);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainBottomInside);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainCenter);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.FlowLine);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainTop);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainStructure);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.DrainArea);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWFront);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWTop);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWBack);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWHinge);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWInside);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWOutside);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Wall);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWall);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWallB1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWallB2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWallB3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWallB4);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWallK1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.RWallK2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.FootingBottom);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.WalkEdge);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Lot);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Slope_Link);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Channel_Side);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Bench);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownPave3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LanePave3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWBase1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownBase1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneBase1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWBase2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownBase2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneBase2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWBase3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownBase3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneBase3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWSub1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownSub1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneSub1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWSub2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownSub2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneSub2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWSub3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.CrownSub3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.LaneSub3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Pave3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Base1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Base2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Base3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Subbase1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Subbase2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Subbase3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSBase1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSBase2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSBase3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSSubBase1);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSSubBase2);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSSubBase3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.ETWPave3);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSBase4);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.Base4);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.SR);
            GetFromCollection(colCodesAndDescriptionHashtable, ref i, ref Codes.EPSPave3);
        }
        catch (object obj) when((obj is Exception && num != 0) & (num2 == 0))
        {
            ProjectData.SetProjectError((Exception)obj);
            /*Error near IL_1431: Could not find block for branch target IL_13f9*/;
        }
        if (num2 != 0)
        {
            ProjectData.ClearProjectError();
        }
    }
Example #12
0
        public static Room RoomParse(Game1 game, string roomID)
        {
            int    i, j, k;
            string grabType;
            int    row;
            int    column;
            string roomTextureID;

            string[] readLine;

            bool              isChestContents = false;
            bool              chestFlag       = false;
            Chest             grabChest       = null;
            string            parsedID        = roomID.Substring(0, 3);
            string            roomFile        = parsedID + ".csv";
            string            roomPath        = Path.Combine(roomCSVPath, roomFile);
            List <INpc>       npcHolder       = new List <INpc>();
            List <IObstacle>  obstacleHolder  = new List <IObstacle>();
            List <IWorldItem> worldItemHolder = new List <IWorldItem>();

            object[] args;
            INpc     goriyaBoomerang1;
            INpc     goriyaBoomerang2;
            INpc     goriyaBoomerang3;
            INpc     topFireball;
            INpc     midFireball;
            INpc     botFireball;

            using (TextFieldParser csvParser = new TextFieldParser(roomPath))
            {
                csvParser.CommentTokens = commentTokens;
                csvParser.SetDelimiters(delimiters);

                //Read first line to grab RoomID for texture
                readLine      = csvParser.ReadFields();
                roomTextureID = readLine[0];

                goriyaBoomerang1 = new GoriyaBoomerang();
                goriyaBoomerang2 = new GoriyaBoomerang();
                goriyaBoomerang3 = new GoriyaBoomerang();
                topFireball      = new Fireball();
                midFireball      = new Fireball();
                botFireball      = new Fireball();

                while (!csvParser.EndOfData)
                {
                    i = 0;
                    j = 0;
                    k = 0;
                    // Read current line fields, pointer moves to the next line.
                    readLine = csvParser.ReadFields();
                    while (i < readLine.Length)
                    {
                        grabType = readLine[i];
                        i++;
                        row = Int32.Parse(readLine[i]);
                        i++;
                        column = Int32.Parse(readLine[i]);

                        float[] coords = RowsColumns.ConvertRowsColumns(row, column);

                        Type resolvedType = Type.GetType(grabType);

                        if (resolvedType == typeof(Goriya))
                        {
                            if (j == 0)
                            {
                                args = new object[] { coords[0], coords[1], (GoriyaBoomerang)goriyaBoomerang1, game };
                            }
                            else if (j == 1)
                            {
                                args = new object[] { coords[0], coords[1], (GoriyaBoomerang)goriyaBoomerang2, game };
                            }
                            else
                            {
                                args = new object[] { coords[0], coords[1], (GoriyaBoomerang)goriyaBoomerang3, game };
                            }
                        }
                        else if (resolvedType == typeof(Boss))
                        {
                            args = new object[] { coords[0], coords[1], (Fireball)topFireball, (Fireball)midFireball, (Fireball)botFireball, game };
                        }
                        else if (resolvedType == typeof(Chest))
                        {
                            chestFlag = true;
                            args      = new object[] { coords[0], coords[1] };
                        }
                        else if (resolvedType == typeof(Gel) || resolvedType == typeof(Bat) || resolvedType == typeof(Skeleton))
                        {
                            args = new object[] { coords[0], coords[1], game };
                        }
                        else
                        {
                            args = new object[] { coords[0], coords[1] };
                        }

                        object grabObj = (Activator.CreateInstance(resolvedType, args));

                        if (grabObj is INpc)
                        {
                            npcHolder.Add((INpc)grabObj);
                            Type npcType = grabObj.GetType();
                            if (npcType == typeof(Goriya))
                            {
                                if (j == 0)
                                {
                                    npcHolder.Add(goriyaBoomerang1);
                                }
                                else if (j == 1)
                                {
                                    npcHolder.Add(goriyaBoomerang2);
                                }
                                else
                                {
                                    npcHolder.Add(goriyaBoomerang3);
                                }
                            }
                            else if (npcType == typeof(Boss))
                            {
                                npcHolder.Add(topFireball);
                                npcHolder.Add(midFireball);
                                npcHolder.Add(botFireball);
                            }

                            Debug.Print("Added NPC");
                        }
                        else if (grabObj is IObstacle)
                        {
                            obstacleHolder.Add((IObstacle)grabObj);
                            Debug.Print("Added Obstacle");
                        }
                        else if (grabObj is IWorldItem && isChestContents)
                        {
                            isChestContents = false;
                            grabChest.putItemInChest((IWorldItem)grabObj);
                            Debug.Print("Added item into Chest");
                        }
                        else if (grabObj is IWorldItem && chestFlag)
                        {
                            grabChest = (Chest)grabObj;
                            worldItemHolder.Add(grabChest);
                            Debug.Print("Added Chest Item");
                        }
                        else if (grabObj is IWorldItem)
                        {
                            worldItemHolder.Add((IWorldItem)grabObj);
                            Debug.Print("Added World Item");
                        }
                        else
                        {
                            Debug.Print("Couldn't finalize interface of Object");
                        }

                        if (chestFlag)
                        {
                            chestFlag       = false;
                            isChestContents = true;
                        }
                        i++;
                        j++;
                        k++;
                    }
                }
            }

            return(new Room(game, npcHolder, obstacleHolder, worldItemHolder, roomTextureID));
        }
Example #13
0
        public void Import()
        {
            using (var reader = new StreamReader(filePath, Encoding.Default))
            {
                string line;
                int    lineNumber = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    lineNumber++;
                    try
                    {
                        string[] data = new string[2];

                        using (TextFieldParser parser = new TextFieldParser(new StringReader(line))
                        {
                            HasFieldsEnclosedInQuotes = true
                        })
                        {
                            parser.SetDelimiters(",");

                            while (!parser.EndOfData)
                            {
                                data = parser.ReadFields();
                            }
                        }

                        Guid firstGuid  = Guid.Empty;
                        Guid secondGuid = Guid.Empty;

                        if (settings.FirstAttributeIsGuid)
                        {
                            firstGuid = new Guid(data[0]);
                        }
                        else
                        {
                            var records = service.RetrieveMultiple(new QueryExpression(settings.FirstEntity)
                            {
                                Criteria =
                                {
                                    Conditions =
                                    {
                                        new ConditionExpression(settings.FirstAttributeName, ConditionOperator.Equal,
                                                                data[0])
                                    }
                                }
                            });

                            if (records.Entities.Count == 1)
                            {
                                firstGuid = records.Entities.First().Id;
                            }
                            else if (records.Entities.Count > 1)
                            {
                                RaiseError(this,
                                           new ResultEventArgs
                                {
                                    LineNumber = lineNumber,
                                    Message    = string.Format("More than one record ({0}) were found with the value specified", settings.FirstEntity)
                                });

                                continue;
                            }
                            else
                            {
                                RaiseError(this,
                                           new ResultEventArgs
                                {
                                    LineNumber = lineNumber,
                                    Message    = string.Format("No record ({0}) was found with the value specified", settings.FirstEntity)
                                });

                                continue;
                            }
                        }

                        if (settings.SecondAttributeIsGuid)
                        {
                            secondGuid = new Guid(data[1]);
                        }
                        else
                        {
                            var records = service.RetrieveMultiple(new QueryExpression(settings.SecondEntity)
                            {
                                Criteria =
                                {
                                    Conditions =
                                    {
                                        new ConditionExpression(settings.SecondAttributeName, ConditionOperator.Equal,
                                                                data[1])
                                    }
                                }
                            });

                            if (records.Entities.Count == 1)
                            {
                                secondGuid = records.Entities.First().Id;
                            }
                            else if (records.Entities.Count > 1)
                            {
                                RaiseError(this,
                                           new ResultEventArgs
                                {
                                    LineNumber = lineNumber,
                                    Message    = string.Format("More than one record ({0}) were found with the value specified", settings.SecondEntity)
                                });

                                continue;
                            }
                            else
                            {
                                RaiseError(this,
                                           new ResultEventArgs
                                {
                                    LineNumber = lineNumber,
                                    Message    = string.Format("No record ({0}) was found with the value specified", settings.SecondEntity)
                                });

                                continue;
                            }
                        }

                        if (settings.Relationship == "listcontact_association" ||
                            settings.Relationship == "listaccount_association" ||
                            settings.Relationship == "listlead_association")
                        {
                            var request = new AddListMembersListRequest
                            {
                                ListId    = settings.FirstEntity == "list" ? firstGuid : secondGuid,
                                MemberIds = new[] { settings.FirstEntity == "list" ? secondGuid : firstGuid }
                            };

                            service.Execute(request);
                        }
                        else
                        {
                            var request = new AssociateRequest
                            {
                                Target          = new EntityReference(settings.FirstEntity, firstGuid),
                                Relationship    = new Relationship(settings.Relationship),
                                RelatedEntities = new EntityReferenceCollection
                                {
                                    new EntityReference(settings.SecondEntity, secondGuid)
                                }
                            };

                            if (request.Target.LogicalName == request.RelatedEntities.First().LogicalName)
                            {
                                request.Relationship.PrimaryEntityRole = EntityRole.Referenced;
                            }

                            service.Execute(request);
                        }

                        OnRaiseSuccess(new ResultEventArgs {
                            LineNumber = lineNumber
                        });
                    }
                    catch (FaultException <OrganizationServiceFault> error)
                    {
                        if (error.Detail.ErrorCode.ToString("X") == "80040237")
                        {
                            OnRaiseError(new ResultEventArgs {
                                LineNumber = lineNumber, Message = "Relationship was not created because it already exists"
                            });
                        }
                        else
                        {
                            OnRaiseError(new ResultEventArgs {
                                LineNumber = lineNumber, Message = error.Message
                            });
                        }
                    }
                }
            }
        }
Example #14
0
        /// <summary>
        /// Method for genetic code upload
        /// </summary>
        public static void UploadGeneticCode()
        {
            string path = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "gencode_Standard.csv");

            oneFoldFamilies   = new Dictionary <string, List <string> >();
            twoFoldFamilies   = new Dictionary <string, List <string> >();
            threeFoldFamilies = new Dictionary <string, List <string> >();
            fourFoldFamilies  = new Dictionary <string, List <string> >();
            stopCodons        = new List <string>();

            using (TextFieldParser parser = new TextFieldParser(path))
            {
                parser.SetDelimiters(new string[] { ";" });

                if (parser.EndOfData)
                {
                    // modern dialog initialization
                    string message = "The genetic code file is empty.";
                    ModernDialog.ShowMessage(message.ToString(), "Warning", MessageBoxButton.OK);
                }
                else
                {
                    while (!parser.EndOfData)
                    {
                        string[]      fields  = parser.ReadFields();
                        List <string> tmpList = new List <string>();

                        for (int i = 1; i < fields.Count(); i++)
                        {
                            tmpList.Add(fields[i]);
                        }

                        if (tmpList.Count() == 1)
                        {
                            oneFoldFamilies.Add(fields[0], tmpList);
                        }

                        if (tmpList.Count() == 2)
                        {
                            twoFoldFamilies.Add(fields[0], tmpList);
                        }

                        if (tmpList.Count() == 3)
                        {
                            if (fields[0] != "STOP")
                            {
                                threeFoldFamilies.Add(fields[0], tmpList);
                            }
                            else
                            {
                                stopCodons = tmpList;
                            }
                        }

                        if (tmpList.Count() == 4)
                        {
                            fourFoldFamilies.Add(fields[0], tmpList);
                        }
                    }
                }
            }
        }
        public void ParseBankRecords(string file)
        {
            List <BankRecord> records = new List <BankRecord>();

            TextFieldParser parser = new TextFieldParser(file);

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

            while (!parser.EndOfData)
            {
                try
                {
                    string[] fields = parser.ReadFields();

                    string   mutationType   = fields[4];
                    string   nameDefinition = String.Empty;
                    string   announcement   = String.Empty;
                    string[] parts;

                    switch (mutationType)
                    {
                    case "BA":
                        parts          = fields[8].Split(new string[] { " / " }, StringSplitOptions.None);
                        nameDefinition = parts.First();
                        announcement   = parts.Last() + fields[1];
                        break;

                    case "GT":
                    case "OV":
                    default:
                        nameDefinition = fields[1];
                        announcement   = fields[8];
                        break;

                    case "VZ":
                    case "IC":
                    case "DV":
                        nameDefinition = fields[8];
                        announcement   = fields[1];
                        break;

                    case "GM":

                        // If there exist angle brackets in the second field, return the first two parts divided by those brackets
                        if (fields[1].Contains('>'))
                        {
                            parts          = fields[1].Split(new string[] { ">" }, StringSplitOptions.None);
                            nameDefinition = String.Join(" ", new string[] { parts[0], parts[1] });
                            announcement   = fields[1].Split(new string[] { ">" }, StringSplitOptions.None).Last() + fields[8];
                        }
                        else
                        {
                            parts          = fields[8].Split(new string[] { " / " }, StringSplitOptions.None);
                            nameDefinition = parts.First();
                            announcement   = parts.Last() + fields[1];
                        }
                        break;
                    }

                    BankRecord record = new BankRecord()
                    {
                        ExecutionDate   = DateTime.Parse(fields[0], CultureInfo.CurrentCulture),
                        RequestDate     = DateTime.Parse(fields[0], CultureInfo.CurrentCulture),
                        Name            = nameDefinition,
                        BankNum         = fields[2],
                        OtherBankNumber = fields[3],
                        Type            = fields[5] == "Bij" ? BankRecord.TransactionType.CREDIT : BankRecord.TransactionType.DEBIT,
                        Amount          = Double.Parse(fields[6]),
                        Description1    = announcement
                    };

                    records.Add(record);
                }
                catch (ArgumentException e)
                {
                    // This record is either corrupt, or we've reached the end of the list: just continue on.
                    continue;
                }
            }

            // Save the records and other info into the database.
            using (var db = new BankTransactionsContext())
            {
                BankTransactionsUpload upload = new BankTransactionsUpload()
                {
                    fileName   = file,
                    filePath   = System.IO.Path.Combine(ConfigurationManager.BaseLocation, "Uploaded/" + DateTime.Now.Ticks + "_" + System.IO.Path.GetFileName(file)),
                    user       = "******",
                    bankRecord = records
                };
                db.SaveChanges();
            }

            parser.Close();
        }
Example #16
0
        private void btnimport1_Click(object sender, EventArgs e)
        {
            //file chooser
            int          size   = -1;
            DialogResult result = openFileDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                string file     = openFileDialog1.FileName;
                string filePath = Path.GetDirectoryName(file);

                try
                {
                    string text = File.ReadAllText(file);
                    size = text.Length;
                }
                catch (IOException)
                {
                    MessageBox.Show("There was an error reading the file");
                }


                //sends opf filename to ReadCSV
                ReadCSV temp = new ReadCSV();
                temp.importcsv(openFileDialog1.FileName);


                //imports the data to a datatable
                DataTable importedData = new DataTable();

                TextFieldParser parser = new TextFieldParser(openFileDialog1.FileName);

                parser.HasFieldsEnclosedInQuotes = true;
                parser.SetDelimiters(",");

                string[] fields;

                bool firstline = true;
                while (!parser.EndOfData)
                {
                    fields = parser.ReadFields();
                    if (firstline)
                    {
                        foreach (string field in fields)
                        {
                            importedData.Columns.Add(field);
                        }
                        firstline = false;

                        continue;
                    }
                }

                dataGridView1.DataSource = importedData;


                //refreshes combolist
                populatecombobox();


                //connects to sql server and fills 2nd datagrid
                using (connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter("select * from Player", connection);
                    DataSet        ds      = new DataSet();
                    adapter.Fill(ds);
                    dataGridView2.DataSource = ds.Tables[0];
                    dataGridView2.Refresh();
                }
            }
        }
Example #17
0
        public void TestTest2()
        {
            for (int x = 0; x < 2; x++)
            {
                for (int y = 0; y < 1000; y++)
                {
                    string[] fields = null;

                    var lines     = File.ReadLines(Path.Combine(Directory.GetCurrentDirectory(), "test.csv"));
                    int lineCount = File.ReadAllLines(Path.Combine(Directory.GetCurrentDirectory(), "test.csv")).Length;

                    if (y > lineCount - 1)
                    {
                        break;
                    }

                    var line = new List <string>(lines)[y];

                    TextFieldParser parser = new TextFieldParser(new StringReader(line));
                    parser.HasFieldsEnclosedInQuotes = true;
                    parser.SetDelimiters(",");
                    fields = parser.ReadFields();

                    using (Test test = new Test(x == 0 ? _legacySourcePath : _modernSourcePath))
                    {
                        if (fields[0].Length > 0)
                        {
                            test.AddFilterCriteria(Test.TestFields.TestRecd, ComparisonType.EqualTo, fields[0]);
                        }

                        if (fields[1].Length > 0)
                        {
                            test.AddFilterCriteria(Test.TestFields.TestHistory, ComparisonType.EqualTo, Convert.ToInt32(fields[1]));
                        }

                        if (!fields[2].Contains("1900"))
                        {
                            test.AddFilterCriteria(Test.TestFields.TestDate, ComparisonType.EqualTo, DateTime.Parse(fields[2]));
                        }

                        if (fields[3].Length > 0)
                        {
                            test.AddFilterCriteria(Test.TestFields.TestName, ComparisonType.EqualTo, fields[3]);
                        }

                        if (fields[4].Length > 0)
                        {
                            test.AddFilterCriteria(Test.TestFields.TestInstrument, ComparisonType.EqualTo, fields[4]);
                        }

                        if (fields[5].Length > 0)
                        {
                            test.AddFilterCriteria(Test.TestFields.TestStatus, ComparisonType.EqualTo, Convert.ToInt32(fields[5]));
                        }

                        if (fields[6].Length > 0)
                        {
                            test.AddFilterCriteria(Test.TestFields.TestPatient, ComparisonType.EqualTo, Convert.ToInt32(fields[6]));
                        }

                        var testList = test.TestList();

                        if (testList.Count == 0)
                        {
                            Assert.Fail("Match failed on line: " + (y + 1).ToString());
                        }
                    }
                }
            }

            Assert.IsTrue(true, "TestTest2 Passed!!");
        }
        /// <summary>
        /// Parse the input catalog file into catalog items.
        /// </summary>
        private IEnumerable <SarCatalogItem> ParseCatalogFile(
            string catalogFilePath,
            ConcurrentDictionary <string, uint> featureNamesIndex,
            FileParsingReport parsingReport)
        {
            using (var reader = new TextFieldParser(catalogFilePath)
            {
                Delimiters = new[] { "," }
            })
            {
                while (!reader.EndOfData)
                {
                    string[] fields;
                    try
                    {
                        parsingReport.TotalLinesCount++;
                        fields = reader.ReadFields();
                    }
                    catch (MalformedLineException)
                    {
                        parsingReport.Errors.Add(
                            new ParsingError(Path.GetFileName(catalogFilePath), reader.ErrorLineNumber,
                                             ParsingErrorReason.MalformedLine));
                        if (parsingReport.Errors.Count > _maximumParsingErrorsCount)
                        {
                            parsingReport.IsCompletedSuccessfuly = false;
                            yield break;
                        }

                        continue;
                    }

                    ParsingErrorReason?parsingError;
                    ParsingErrorReason?parsingWarning;
                    SarCatalogItem     catalogItem = ParseCatalogItem(fields, featureNamesIndex, out parsingError, out parsingWarning);
                    if (parsingError.HasValue)
                    {
                        parsingReport.Errors.Add(
                            new ParsingError(Path.GetFileName(catalogFilePath), reader.LineNumber - 1, parsingError.Value));
                        if (parsingReport.Errors.Count > _maximumParsingErrorsCount)
                        {
                            parsingReport.IsCompletedSuccessfuly = false;
                            yield break;
                        }

                        continue;
                    }

                    if (parsingWarning.HasValue)
                    {
                        parsingReport.Warnings.Add(
                            new ParsingError(Path.GetFileName(catalogFilePath), reader.LineNumber - 1, parsingWarning.Value));

                        continue;
                    }

                    parsingReport.SuccessfulLinesCount++;
                    yield return(catalogItem);
                }
            }

            // no more lines to parse - mark the parsing as successful
            parsingReport.IsCompletedSuccessfuly = true;
        }
        public List <MCQquestions> ReadQuestionFile(int id)
        {
            List <MCQquestions> mcq = new List <MCQquestions>();

            try
            {
                List <string[]> data = new List <string[]>();
                string          path = (from q in oe.Questions
                                        where q.FileID == id
                                        select q.FileName
                                        ).FirstOrDefault();
                TextFieldParser parser = new TextFieldParser(path, Encoding.Default);
                parser.HasFieldsEnclosedInQuotes = true;
                parser.SetDelimiters(",");
                string[] fields;
                while (!parser.EndOfData)
                {
                    fields = parser.ReadFields();
                    if (fields[0] == "")
                    {
                        continue;
                    }
                    data.Add(fields);
                }
                parser.Close();
                int[] arr = new int[data.Count];           //for Random Questions
                arr[0] = 0;
                Random rand = new Random();
                for (int i = 1; i <= 10; i++)
                {
                    int number;
                    do
                    {
                        number = rand.Next(1, data.Count);
                    } while (arr.Contains(number));
                    arr[i] = number;
                }
                int k = 0;
                mcq.Add(new MCQquestions
                {
                    Que_No   = data[0][0],
                    Question = data[0][1],
                    OP1      = data[0][2],
                    OP2      = data[0][3],
                    OP3      = data[0][4],
                    OP4      = data[0][5],
                    Ans      = data[0][6]
                });

                for (int i = 1; i <= 10; i++)
                {
                    foreach (var rows in data)
                    {
                        if (rows[0] == arr[i].ToString())
                        {
                            mcq.Add(new MCQquestions
                            {
                                Que_No   = i.ToString(),
                                Question = rows[1],
                                OP1      = rows[2],
                                OP2      = rows[3],
                                OP3      = rows[4],
                                OP4      = rows[5],
                                Ans      = rows[6]
                            });
                            break;
                        }
                    }
                }
                //IEnumerable<MCQquestions> m = mcq as IEnumerable<MCQquestions>;
                return(mcq);
            }

            catch (Exception e)
            {
                return(mcq);
            }
        }
Example #20
0
        public static void Import(Stream csvStream,
                                  ref List <BoxPosition> boxPositions,
                                  ref Vector3D dimCase, ref double weightCase,
                                  ref Vector3D dimPallet, ref double weightPallet,
                                  ref double maxPalletHeight,
                                  ref bool layersMirrorX, ref bool layersMirrorY,
                                  ref List <bool> interlayers)
        {
            using (TextFieldParser csvParser = new TextFieldParser(csvStream))
            {
                csvParser.CommentTokens = new string[] { "#" };
                csvParser.SetDelimiters(new string[] { ";" });
                csvParser.HasFieldsEnclosedInQuotes = false;

                // Skip the row with the column names
                csvParser.ReadLine();
                csvParser.ReadLine();

                double zMin = double.MaxValue;
                maxPalletHeight = 1700.0;

                while (!csvParser.EndOfData)
                {
                    // Read current line fields, pointer moves to the next line.
                    string[] fields = csvParser.ReadFields();

                    string f1 = fields[1];
                    if (f1.Contains("Program:StackBuilder.Box") && f1.EndsWith(".C"))
                    {
                        try
                        {
                            int angle = int.Parse(fields[3]);
                            fields = csvParser.ReadFields();
                            double x = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                            fields = csvParser.ReadFields();
                            double y = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                            fields = csvParser.ReadFields();
                            double z = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                            if (angle == 0 && x == 0 && y == 0 && z == 0)
                            {
                                continue;
                            }
                            if (z < zMin)
                            {
                                zMin = z;
                            }

                            HalfAxis.HAxis axisL = HalfAxis.HAxis.AXIS_X_P;
                            HalfAxis.HAxis axisW = HalfAxis.HAxis.AXIS_Y_P;
                            switch (angle)
                            {
                            case 0:
                                axisL = HalfAxis.HAxis.AXIS_X_P;
                                axisW = HalfAxis.HAxis.AXIS_Y_P;
                                break;

                            case 90:
                                axisL = HalfAxis.HAxis.AXIS_Y_P;
                                axisW = HalfAxis.HAxis.AXIS_X_N;
                                break;

                            case 180:
                                axisL = HalfAxis.HAxis.AXIS_X_N;
                                axisW = HalfAxis.HAxis.AXIS_Y_N;
                                break;

                            case 270:
                                axisL = HalfAxis.HAxis.AXIS_Y_N;
                                axisW = HalfAxis.HAxis.AXIS_X_P;
                                break;

                            default:
                                break;
                            }
                            if (Math.Abs(z - zMin) < 1.0E-06)
                            {
                                boxPositions.Add(new BoxPosition(new Vector3D(x, y, z), axisL, axisW));
                            }
                        }
                        catch (Exception ex)
                        {
                            _log.Error(ex.ToString());
                        }
                    }
                    else if (f1.Contains("Program:StackBuilder.InterlayerOnOff"))
                    {
                        interlayers.Add(string.Equals(fields[3], "TRUE", StringComparison.InvariantCultureIgnoreCase));
                    }
                    else if (f1.Contains("Program:StackBuilder.BoxDimension.L"))
                    {
                        dimCase.X  = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                        fields     = csvParser.ReadFields();
                        dimCase.Y  = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                        fields     = csvParser.ReadFields();
                        dimCase.Z  = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                        fields     = csvParser.ReadFields();
                        weightCase = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                    }
                    else if (f1.Contains("Program:StackBuilder.PalletDimension"))
                    {
                        dimPallet.X  = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                        fields       = csvParser.ReadFields();
                        dimPallet.Y  = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                        fields       = csvParser.ReadFields();
                        dimPallet.Z  = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                        fields       = csvParser.ReadFields();
                        weightPallet = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                    }
                    else if (f1.Contains("Program:StackBuilder.MaxPalletHeight"))
                    {
                        maxPalletHeight = double.Parse(fields[3], NumberFormatInfo.InvariantInfo);
                    }
                    else if (f1.Contains("Program:StackBuilder.LayersMirrorXOnOff"))
                    {
                        layersMirrorX = String2Bool(fields[3]);
                    }
                    else if (f1.Contains("Program:StackBuilder.LayersMirrorYOnOff"))
                    {
                        layersMirrorY = String2Bool(fields[3]);
                    }
                }
            }

            // reset position
            for (int i = 0; i < boxPositions.Count; ++i)
            {
                var            bpos       = boxPositions[i];
                HalfAxis.HAxis axisLength = bpos.DirectionLength;
                HalfAxis.HAxis axisWidth  = bpos.DirectionWidth;
                Vector3D       vI         = HalfAxis.ToVector3D(axisLength);
                Vector3D       vJ         = HalfAxis.ToVector3D(axisWidth);
                Vector3D       vK         = Vector3D.CrossProduct(vI, vJ);
                var            v          = bpos.Position - 0.5 * dimCase.X * vI - 0.5 * dimCase.Y * vJ - 0.5 * dimCase.Z * vK - dimPallet.Z * Vector3D.ZAxis;
                boxPositions[i] = new BoxPosition(v, axisLength, axisWidth);
            }
        }
        public IEnumerable <dynamic> parse(csvUploadRequest request)
        {
            // TextFieldParser is in the Microsoft.VisualBasic.FileIO namespace.
            using (TextFieldParser parser = new TextFieldParser(request.FilePath))
            {
                parser.CommentTokens = new string[] { "#" };
                parser.SetDelimiters(new string[] { "," });
                parser.HasFieldsEnclosedInQuotes = true;

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


                string[] headerFields  = parser.ReadFields();
                string[] propertyNames = headerFields.Select(str => str.Replace(" ", "_")).ToArray <string>(); //(*)

                while (!parser.EndOfData)
                {
                    string[] fields     = parser.ReadFields();
                    dynamic  baseObject = new ExpandoObject();
                    IDictionary <string, object> baseDataUnderlyingObject = baseObject;

                    dynamic dataObject = new ExpandoObject();
                    IDictionary <string, object> dataUnderlyingObject = dataObject;

                    //dynamic searchDataObject = new ExpandoObject();
                    //IDictionary<string, object> searchDataUnderlyingObject = searchDataObject;

                    //dynamic authData = new ExpandoObject();
                    //IDictionary<string, object> authDataUnderlyingObject = authData;

                    //dynamic authSearchDataObject = new ExpandoObject();
                    //IDictionary<string, object> authSearchDataUnderlyingObject = authSearchDataObject;


                    for (int i = 0; i < headerFields.Length; i++)
                    {
                        var propName   = propertyNames[i];
                        var fieldValue = fields[i];

                        dataUnderlyingObject.Add(propName, fieldValue);

                        //var authField = (from a in request.AuthFieldNames
                        //                 where a.ToUpper() == propName.ToUpper()
                        //                 select a).FirstOrDefault();

                        //if (!string.IsNullOrEmpty(authField))
                        //{
                        //    authDataUnderlyingObject.Add(propName, fieldValue);
                        //    ExtractSearchData(request, authSearchDataUnderlyingObject, propName, fieldValue);
                        //}
                        //else
                        //{
                        //    authDataUnderlyingObject.Add(propName, fieldValue);
                        //    dataUnderlyingObject.Add(propName, fieldValue);
                        //    ExtractSearchData(request, authSearchDataUnderlyingObject, propName, fieldValue);
                        //    ExtractSearchData(request, searchDataUnderlyingObject, propName, fieldValue);
                        //}
                    }

                    baseDataUnderlyingObject.Add("Data", dataObject);
                    //baseDataUnderlyingObject.Add("SearchData", searchDataObject);
                    //baseDataUnderlyingObject.Add("AuthData", authData);
                    //baseDataUnderlyingObject.Add("AuthSearchData", authSearchDataObject);
                    yield return(baseObject);
                }
            }
        }
Example #22
0
        public static string ValidateUploadedFileData(string uploadPath)
        {
            string resp     = "OK";
            int    lineNumb = 1;

            DataTable csvData = new DataTable();

            try
            {
                using (TextFieldParser csvReader = new TextFieldParser(uploadPath))
                {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    while (!csvReader.EndOfData)
                    {
                        if (resp.Trim().Equals("OK"))
                        {
                            string[] fieldData = csvReader.ReadFields();
                            if (fieldData.Length == 14)
                            {
                                for (int i = 0; i < fieldData.Length; i++)
                                {
                                    if ((i == 0 || i == 7) && lineNumb == 1)
                                    {
                                        DateTime temp;
                                        if (DateTime.TryParseExact(fieldData[i], "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp))
                                        {
                                            resp = "VALIDATION FAIL. UPLOADED FILE SHOULD HAVE COLUMN HEADERS ON LINE " + lineNumb;
                                            break;
                                        }
                                    }
                                    else if ((i == 6 || i == 8 || i == 9 || i == 10 || i == 11 || i == 12 || i == 13) && lineNumb == 1)
                                    {
                                        Double temp;

                                        if (Double.TryParse(fieldData[i], out temp))
                                        {
                                            resp = "VALIDATION FAIL. UPLOADED FILE SHOULD HAVE COLUMN HEADERS ON LINE " + lineNumb;
                                            break;
                                        }
                                    }
                                    else if ((i == 5 || i == 7) && lineNumb != 1)
                                    {
                                        DateTime temp;
                                        if (!DateTime.TryParseExact(fieldData[i], "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp))
                                        {
                                            resp = "ERROR. UPLOADED FILE HAS INVALID DATE (" + fieldData[i] + ") ON LINE " + lineNumb + " FIELD " + (i + 1);
                                            break;
                                        }
                                    }
                                    else if ((i == 6 || i == 8 || i == 9 || i == 10 || i == 11 || i == 12 || i == 13) && lineNumb != 1)
                                    {
                                        Double temp;

                                        if (!Double.TryParse(fieldData[i], out temp))
                                        {
                                            resp = "VALIDATION FAIL. UPLOADED FILE HAS INVALID NUMERIC ENTRY (" + fieldData[i] + ")  ON LINE " + lineNumb + " FIELD " + (i + 1);
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                resp = "VALIDATION FAIL. UPLOADED FILE HAS " + fieldData.Length + " FIELDS ON LINE " + lineNumb + ". EXPECTING 14 FIELDS";
                                break;
                            }
                            lineNumb++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                resp = ex.Message;
            }
            return(resp);
        }
Example #23
0
        public void MakeItemList()
        {
            Items = new Dictionary <int, Item>();
            {
                try
                {
                    using (TextFieldParser parser = new TextFieldParser(new StringReader(Resources.Item)))
                    {
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");
                        int rowCount = 0;
                        while (!parser.EndOfData)
                        {
                            //Processing row
                            rowCount++;

                            var      item   = new Item();
                            string[] fields = parser.ReadFields();
                            int      fCount = 0;
                            int      index  = 0;

                            if (rowCount == 1)
                            {
                                continue;
                            }

                            foreach (string field in fields)
                            {
                                fCount++;


                                if (fCount == 1)
                                {
                                    int.TryParse(field, out index);
                                }

                                if (fCount == 2)
                                {
                                    item.Name = field;
                                }

                                if (fCount == 3)
                                {
                                    int cat = int.Parse(field);
                                    switch (cat)
                                    {
                                    case 34:
                                        item.Type = ItemType.Head;
                                        break;

                                    case 35:
                                        item.Type = ItemType.Body;
                                        break;

                                    case 37:
                                        item.Type = ItemType.Hands;
                                        break;

                                    case 36:
                                        item.Type = ItemType.Legs;
                                        break;

                                    case 38:
                                        item.Type = ItemType.Feet;
                                        break;

                                    case 41:
                                        item.Type = ItemType.Ears;
                                        break;

                                    case 40:
                                        item.Type = ItemType.Neck;
                                        break;

                                    case 42:
                                        item.Type = ItemType.Wrists;
                                        break;

                                    case 43:
                                        item.Type = ItemType.Ring;
                                        break;

                                    default:
                                        item.Type = ItemType.Wep;
                                        break;
                                    }
                                }

                                if (fCount == 4)
                                {
                                    var tfield = field.Replace(" ", "");
                                    if (item.Type == ItemType.Wep)
                                    {
                                        item.ModelMain = tfield;
                                    }
                                    else
                                    {
                                        item.ModelMain = tfield;
                                    }
                                }

                                if (fCount == 5)
                                {
                                    var tfield = field.Replace(" ", "");
                                    if (item.Type == ItemType.Wep)
                                    {
                                        item.ModelOff = tfield;
                                    }
                                    else
                                    {
                                        item.ModelOff = tfield;
                                    }
                                }
                            }
                            //   Debug.WriteLine(item.Name + " - " + item.Type);
                            Items.Add(index, item);
                        }
                        //    Debug.WriteLine($"ExdCsvReader: {rowCount} items read");
                    }
                }
                catch (Exception exc)
                {
                    Items = null;
#if DEBUG
                    throw exc;
#endif
                }
            }
        }
Example #24
0
        public static async Task LogOnMessageDeleted(DiscordClient client, MessageDeleteEventArgs e)
        {
            if (e.Guild != null)
            {
                if (!Bot.GetMultiplySettingsSeparated(Bot.BotSettings.IgnoredChannels).Contains(e.Channel.Id)
                    ) // в лог не должны отправляться сообщения,
                      // удаленные из лога
                {
                    try
                    {
                        //Каналы авто-очистки отправляются в отдельный канал.
                        if (e.Channel.Id == Bot.BotSettings.FindChannel ||
                            e.Channel.Id == Bot.BotSettings.FleetCreationChannel ||
                            e.Channel.Id == Bot.BotSettings.CodexReserveChannel)
                        {
                            await e.Guild.GetChannel(Bot.BotSettings.AutoclearLogChannel)
                            .SendMessageAsync("**Удаление сообщения**\n" +
                                              $"**Автор:** {e.Message.Author.Username}#{e.Message.Author.Discriminator} ({e.Message.Author.Id})\n" +
                                              $"**Канал:** {e.Channel}\n" +
                                              $"**Содержимое: ```{e.Message.Content}```**");
                        }
                        else
                        {
                            using (TextFieldParser parser = new TextFieldParser("generated/attachments_messages.csv"))
                            {
                                parser.TextFieldType = FieldType.Delimited;
                                parser.SetDelimiters(",");
                                while (!parser.EndOfData)
                                {
                                    string[] fields = parser.ReadFields();
                                    if (Convert.ToUInt64(fields[0]) == e.Message.Id)
                                    {
                                        var attachment =
                                            (await e.Guild.GetChannel(Bot.BotSettings.AttachmentsLog)
                                             .GetMessageAsync(Convert.ToUInt64(fields[1]))).Attachments[0];

                                        var file = $"generated/attachments/{attachment.FileName}";

                                        var wClient = new WebClient();
                                        wClient.DownloadFile(attachment.Url, file);
                                        await e.Guild.GetChannel(Bot.BotSettings.FulllogChannel)
                                        .SendFileAsync(file, "**Удаление сообщения**\n" +
                                                       $"**Автор:** {e.Message.Author.Username}#{e.Message.Author.Discriminator} ({e.Message.Author.Id})\n" +
                                                       $"**Канал:** {e.Channel}\n" +
                                                       $"**Содержимое: ```{e.Message.Content}```**");

                                        File.Delete(file);
                                        return;
                                    }
                                }
                            }
                            await e.Guild.GetChannel(Bot.BotSettings.FulllogChannel)
                            .SendMessageAsync("**Удаление сообщения**\n" +
                                              $"**Автор:** {e.Message.Author.Username}#{e.Message.Author.Discriminator} ({e.Message.Author.Id})\n" +
                                              $"**Канал:** {e.Channel}\n" +
                                              $"**Содержимое: ```{e.Message.Content}```**");
                        }
                    }
                    catch (NullReferenceException)
                    {
                        //Ничего не делаем
                    }
                }
            }
        }
        ObservableCollection <Filter> LoadFilters()
        {
            var filters = new ObservableCollection <Filter>();

            if (!File.Exists(Properties.Settings.Default.filtersPath))
            {
                ToolbarLogger.GetLogger("EverythingToolbar").Info("Filters.csv could not be found at " + Properties.Settings.Default.filtersPath);

                string everythingIniPath = Path.Combine(Properties.Settings.Default.filtersPath, "..", "Everything.ini");
                if (!File.Exists(everythingIniPath))
                {
                    ToolbarLogger.GetLogger("EverythingToolbar").Info("Everything.ini could not be found.");
                    MessageBox.Show("Pleae select Filters.csv. It gets created after editing filters in Everything for the first time.");
                    using (OpenFileDialog openFileDialog = new OpenFileDialog())
                    {
                        openFileDialog.InitialDirectory = "c:\\";
                        openFileDialog.Filter           = "Filters.csv|Filters.csv|All files (*.*)|*.*";
                        openFileDialog.FilterIndex      = 1;

                        if (openFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            Properties.Settings.Default.filtersPath = openFileDialog.FileName;
                            Properties.Settings.Default.Save();
                        }
                        else
                        {
                            return(defaultUserFilters);
                        }
                    }
                }
                else
                {
                    ToolbarLogger.GetLogger("EverythingToolbar").Info("Filters.csv does not exist. Using default filters.");
                    return(defaultUserFilters);
                }
            }

            try
            {
                using (TextFieldParser csvParser = new TextFieldParser(Properties.Settings.Default.filtersPath))
                {
                    csvParser.CommentTokens = new string[] { "#" };
                    csvParser.SetDelimiters(new string[] { "," });
                    csvParser.HasFieldsEnclosedInQuotes = true;

                    // Skip header row
                    csvParser.ReadLine();

                    while (!csvParser.EndOfData)
                    {
                        string[] fields = csvParser.ReadFields();

                        // Skip default filters
                        string search = fields[6].Trim();
                        if (search == "file:" ||
                            search == "folder:" ||
                            search == "")
                        {
                            continue;
                        }

                        // Everything's default filters are uppercase
                        fields[0] = fields[0].Replace("AUDIO", "Audio");
                        fields[0] = fields[0].Replace("COMPRESSED", "Compressed");
                        fields[0] = fields[0].Replace("DOCUMENT", "Document");
                        fields[0] = fields[0].Replace("EXECUTABLE", "Executable");
                        fields[0] = fields[0].Replace("PICTURE", "Picture");
                        fields[0] = fields[0].Replace("VIDEO", "Video");

                        filters.Add(new Filter()
                        {
                            Name             = fields[0],
                            IsMatchCase      = fields[1] == "1",
                            IsMatchWholeWord = fields[2] == "1",
                            IsMatchPath      = fields[3] == "1",
                            IsRegExEnabled   = fields[5] == "1",
                            Search           = fields[6],
                            Macro            = fields[7]
                        });
                    }
                }
            }
            catch (Exception e)
            {
                ToolbarLogger.GetLogger("EverythingToolbar").Error(e, "Parsing Filters.csv failed.");
                return(defaultUserFilters);
            }

            return(filters);
        }
Example #26
0
 public string ManageLicensesWithTextFile(Stream stream)
 {
     try
     {
         TextFieldParser tfp = new TextFieldParser(stream);
         tfp.TextFieldType = FieldType.Delimited;
         tfp.SetDelimiters("|");
         DataTable licensesInTextFile = new DataTable();
         licensesInTextFile.Columns.Add("license_code");
         licensesInTextFile.Columns.Add("license");
         while (!tfp.EndOfData)
         {
             string[] fields = tfp.ReadFields();
             DataRow  dr     = licensesInTextFile.NewRow();
             dr.ItemArray = fields;
             licensesInTextFile.Rows.Add(dr);
             if (fields.Count() == 2)
             {
                 DataTable license = licenseDAO.SelectLicense(fields[0]);
                 if (license.Rows.Count == 0)
                 {
                     licenseDAO.InsertLicense(fields[0], fields[1]);
                 }
                 else
                 {
                     if (license.Rows[0][1].ToString() != fields[1])
                     {
                         licenseDAO.UpdateLicense(fields[0], fields[1]);
                     }
                 }
                 license.Clear();
             }
             else
             {
                 return("Please upload a text file with the correct format. " +
                        "Make sure to follow this format: [License Code]|[License Value]");
             }
         }
         tfp.Close();
         DataTable            licensesInDatabase    = licenseDAO.SelectAllLicense();
         IEnumerable <string> licensesNotInTextFile = licensesInDatabase.AsEnumerable().Select(r => r.Field <string>("license_code"))
                                                      .Except(licensesInTextFile.AsEnumerable().Select(r => r.Field <string>("license_code")));
         if (licensesNotInTextFile.Any())
         {
             DataTable licensesToBeDeleted = (from row in licensesInDatabase.AsEnumerable()
                                              join id in licensesNotInTextFile
                                              on row.Field <string>("license_code") equals id
                                              select row).CopyToDataTable();
             foreach (DataRow dr in licensesToBeDeleted.Rows)
             {
                 licenseDAO.DeleteLicense(dr[0].ToString());
             }
         }
         return("License data successfully edited.");
     }
     catch (Exception e1)
     {
         Debug.WriteLine("Text File Parse Exception Type: " + e1.GetType() +
                         "\nMessage: " + e1.Message +
                         "\nStack Trace: " + e1.StackTrace);
         return("Sorry, an error occured. Please try again.");
     }
 }
        private bool ClientTest2()
        {
            for (int x = 0; x < 2; x++)
            {
                for (int y = 0; y < 1000; y++)
                {
                    string[] fields = null;

                    var lines     = File.ReadLines(Path.Combine(Directory.GetCurrentDirectory(), "client.csv"));
                    int lineCount = File.ReadAllLines(Path.Combine(Directory.GetCurrentDirectory(), "client.csv")).Length;

                    if (y > lineCount - 1)
                    {
                        break;
                    }

                    var line = new List <string>(lines)[y];

                    TextFieldParser parser = new TextFieldParser(new StringReader(line));
                    parser.HasFieldsEnclosedInQuotes = true;
                    parser.SetDelimiters(",");
                    fields = parser.ReadFields();

                    using (Client client = new Client(x == 0 ? _legacySourcePath : _modernSourcePath))
                    {
                        if (fields[0].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientRecd, ComparisonType.EqualTo, fields[0]);
                        }

                        if (fields[1].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientTitle, ComparisonType.EqualTo, fields[1]);
                        }

                        if (fields[2].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientLast, ComparisonType.EqualTo, fields[2]);
                        }

                        if (fields[3].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientAddress, ComparisonType.EqualTo, fields[3]);
                        }

                        if (fields[4].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientAddress2, ComparisonType.EqualTo, fields[4]);
                        }

                        if (fields[5].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientCity, ComparisonType.EqualTo, fields[5]);
                        }

                        if (fields[6].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientState, ComparisonType.EqualTo, fields[6]);
                        }

                        if (fields[7].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientZip, ComparisonType.EqualTo, fields[7]);
                        }

                        if (fields[8].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientArea, ComparisonType.EqualTo, fields[8]);
                        }

                        if (fields[9].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientPhone, ComparisonType.EqualTo, fields[9]);
                        }

                        if (fields[10].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientFirst, ComparisonType.EqualTo, fields[10]);
                        }

                        if (fields[11].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientBusiness, ComparisonType.EqualTo, fields[11]);
                        }

                        if (fields[12].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientCodes, ComparisonType.EqualTo, fields[12]);
                        }

                        if (fields[13].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientClass, ComparisonType.EqualTo, Convert.ToInt32(fields[13]));
                        }

                        if (fields[14].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientReference, ComparisonType.EqualTo, fields[14]);
                        }

                        if (!fields[15].Contains("1900"))
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientUntil, ComparisonType.EqualTo, DateTime.Parse(fields[15]));
                        }

                        if (fields[17].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientFlags, ComparisonType.EqualTo, Convert.ToInt32(fields[17]));
                        }

                        if (!fields[18].Contains("1900"))
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientAdded, ComparisonType.EqualTo, DateTime.Parse(fields[18]));
                        }

                        if (fields[19].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientDoctor, ComparisonType.EqualTo, fields[19]);
                        }

                        if (fields[20].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientCompany, ComparisonType.EqualTo, Convert.ToInt32(fields[20]));
                        }

                        if (fields[21].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientSpouse, ComparisonType.EqualTo, fields[21]);
                        }

                        if (fields[22].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientEmail, ComparisonType.EqualTo, fields[22]);
                        }

                        if (fields[23].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientCounty, ComparisonType.EqualTo, fields[23]);
                        }

                        if (fields[24].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientFolder, ComparisonType.EqualTo, Convert.ToInt32(fields[24]));
                        }

                        if (fields[25].Length > 0)
                        {
                            client.AddFilterCriteria(Client.ClientFields.ClientCell, ComparisonType.EqualTo, fields[25]);
                        }

                        var clientList = client.ClientList();

                        if (clientList.Count == 0)
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
Example #28
0
        static void Main(string[] args)
        {
            Console.WriteLine("This is our world now");

            // ignore invalid certs so we can capture 404s
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            // iterate through the domains in sites.csv
            using (TextFieldParser parser = new TextFieldParser("../../../../../sites.csv"))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                parser.ReadFields(); // skip header

                String header = "awsOrigin,domain,lat,lng,locationVerified,httpResponseCode,contentLength,facebookUrl,siteName,twitterUsername,itunesAppStoreUrl,twitterAccountCreatedAt,twitterUserId,twitterFollowers,twitterFollowing,twitterTweets,siteOperator";
                String lines  = header;
                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();

                    // extract a line from sites.csv
                    String awsOrigin               = fields[0];
                    String domain                  = fields[1];
                    String lat                     = fields[2];
                    String lng                     = fields[3];
                    String locationVerified        = fields[4];
                    String httpResponseCode        = fields[5];
                    String contentLength           = fields[6];
                    String facebookUrl             = fields[7];
                    String siteName                = fields[8];
                    String twitterUsername         = fields[9];
                    String itunesAppStoreUrl       = fields[10];
                    String twitterAccountCreatedAt = fields[11];
                    String twitterUserId           = "";
                    String twitterFollowers        = "";
                    String twitterFollowing        = "";
                    String twitterTweets           = "";
                    String siteOperator            = "";

                    try
                    {
                        twitterUserId    = fields[12];
                        twitterFollowers = fields[13];
                        twitterFollowing = fields[14];
                        twitterTweets    = fields[15];
                        siteOperator     = fields[16];
                    }
                    catch (Exception ex)
                    {
                        String x = ex.Message;
                    }

                    // get the http response code
                    try
                    {
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://" + domain);
                        request.Method = "GET";

                        //Fake firefox-like header. Valid HTTP request headers, particularly the user-agent are used to determine if
                        //web request are valid. We can emulate different browsers using different headersl
                        request.Headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";

                        using (var response = request.GetResponse())
                            using (var stream = response.GetResponseStream())
                                using (var reader = new StreamReader(stream))
                                {
                                    HttpWebResponse webResponse = ((HttpWebResponse)response);
                                    HttpStatusCode  statusCode  = ((HttpWebResponse)response).StatusCode;
                                    httpResponseCode = ((int)statusCode).ToString();
                                    contentLength    = response.ContentLength.ToString();

                                    String responseString = reader.ReadToEnd();
                                    if (responseString.ToLower().Contains("corona"))
                                    {
                                        File.AppendAllText("../../../../../reports/corona/corona - " + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", domain + "\r\n");
                                    }
                                    if (responseString.ToLower().Contains("covid-19"))
                                    {
                                        File.AppendAllText("../../../../../reports/corona/covid-19 - " + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", domain + "\r\n");
                                    }
                                }

                        if (siteOperator == "")
                        {
                            request = (HttpWebRequest)WebRequest.Create("https://" + domain + "/privacy");
                            using (var response = request.GetResponse())
                                using (var stream = response.GetResponseStream())
                                    using (var reader = new StreamReader(stream))
                                    {
                                        HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode;
                                        httpResponseCode = ((int)statusCode).ToString();
                                        contentLength    = response.ContentLength.ToString();

                                        String responseString = reader.ReadToEnd();
                                        if (responseString.Contains("Locality Labs"))
                                        {
                                            siteOperator = "Locality Labs";
                                        }
                                        if (responseString.Contains("Metric Media"))
                                        {
                                            siteOperator = "Metric Media";
                                        }
                                    }
                        }
                    }
                    catch (WebException we)
                    {
                        if (we.Response != null)
                        {
                            HttpStatusCode statusCode = ((HttpWebResponse)we.Response).StatusCode;
                            httpResponseCode = ((int)statusCode).ToString();
                            contentLength    = we.Response.ContentLength.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                    }

                    // write a new line for the updated sites.csv
                    String line = awsOrigin + ",";
                    line += domain + ",";
                    line += lat + ",";
                    line += lng + ",";
                    line += locationVerified + ",";
                    line += httpResponseCode + ",";
                    line += contentLength + ",";
                    line += facebookUrl + ",";
                    line += siteName + ",";
                    line += twitterUsername + ",";
                    line += itunesAppStoreUrl + ",";
                    line += twitterAccountCreatedAt + ",";
                    line += twitterUserId + ",";
                    line += twitterFollowers + ",";
                    line += twitterFollowing + ",";
                    line += twitterTweets + ",";
                    line += siteOperator;

                    lines += "\r\n" + line;

                    Console.WriteLine(domain + ": " + httpResponseCode + ", " + contentLength);
                }
                File.WriteAllText("../../../../../sites.csv", lines);
            }
        }
Example #29
0
        private static FlatFileImportResult PerformImport(TextFieldParser objParser, FlatFileTemplate objFileTemplate, DataColumnMapping columnMapping)
        {
            var result = new FlatFileImportResult();

            objParser.SetDelimiters(objFileTemplate.Delimiters);
            objParser.SetFieldWidths(objFileTemplate.FieldWidths);
            objParser.HasFieldsEnclosedInQuotes = objFileTemplate.HasFieldsEnclosedInQuotes;
            objParser.TextFieldType             = objFileTemplate.TextFieldType;
            objParser.TrimWhiteSpace            = objFileTemplate.TrimWhiteSpace;

            var importAborted  = false;
            var rawFieldValues = new List <string>();

            try
            {
                var mappedColumnCount = objFileTemplate.Columns.Count(columnMapping.ContainsSourceColumn);
                if (mappedColumnCount == 0)
                {
                    importAborted = true;
                    result.Errors.Add(new FlatFileImportException("The specified FeedFileColumnMapping object did not contain mappings for any of the columns defined in the specified FeedFileTemplate object."));
                }

                while (!objParser.EndOfData && !importAborted)
                {
                    try
                    {
                        var currentLineNumber = objParser.LineNumber;
                        if (currentLineNumber <= objFileTemplate.HeaderLinesToSkip)
                        {
                            result.HeaderLines.Add(objParser.ReadLine());
                            continue;
                        }

                        try
                        {
                            var fields = objParser.ReadFields();
                            if (fields == null)
                            {
                                throw new InvalidOperationException("Unable to read fields.");
                            }

                            rawFieldValues.AddRange(fields);
                        }
                        catch
                        {
                            // If we have a read error, we need to abort the read
                            importAborted = true;
                            throw;
                        }

                        result.TotalRecords++;

                        if (rawFieldValues.Count > objFileTemplate.Columns.Count)
                        {
                            result.SkippedRecords++;
                            throw new FlatFileFormatException("Line " + currentLineNumber + ": File has more fields than expected. Skipping line.");
                        }

                        if (rawFieldValues.Count < objFileTemplate.Columns.Count)
                        {
                            result.SkippedRecords++;
                            throw new FlatFileFormatException("Line " + currentLineNumber + ": File has fewer fields than expected. Skipping line.");
                        }

                        var dicNamedImportValues = new Dictionary <string, string>();
                        for (var i = 0; i < objFileTemplate.Columns.Count; i++)
                        {
                            dicNamedImportValues.Add(objFileTemplate.Columns[i], rawFieldValues[i]);
                        }

                        var dicNamedDestinationValues = dicNamedImportValues.Keys.Where(columnMapping.ContainsSourceColumn).ToDictionary(columnMapping.GetDestinationColumn, sourceColumn => columnMapping.TransformValue(sourceColumn, dicNamedImportValues[sourceColumn]));

                        if (dicNamedDestinationValues.Count > 0)
                        {
                            result.ImportedData.Add(dicNamedDestinationValues);
                        }
                        else
                        {
                            result.Warnings.Add("Line " + currentLineNumber + ": No data imported because none of the columns were mapped. Skipping line.");
                            result.SkippedRecords++;
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Errors.Add(ex);
                    }
                    finally
                    {
                        rawFieldValues.Clear();
                    }
                }
            }
            finally
            {
                objParser.Close();
            }

            if (result.ImportedData.Count == 0)
            {
                var errorString = "No data was imported because ";
                if (importAborted)
                {
                    errorString += "the import was aborted.";
                }
                else if (result.TotalRecords == 0)
                {
                    errorString += "the file had no records.";
                }
                else if (result.SkippedRecords == result.TotalRecords)
                {
                    errorString += "all records were skipped.";
                }

                result.Errors.Add(new FlatFileImportException(errorString));
            }

            return(result);
        }
Example #30
0
        private List <ReflectedTimeSeriesPoint> LoadPoints(string path)
        {
            if (!File.Exists(path))
            {
                throw new ExpectedException($"CSV file '{path}' does not exist.");
            }

            var points = new List <ReflectedTimeSeriesPoint>();

            var parser = new TextFieldParser(path)
            {
                TextFieldType  = FieldType.Delimited,
                Delimiters     = new[] { "," },
                TrimWhiteSpace = true
            };

            if (!string.IsNullOrWhiteSpace(Context.CsvComment))
            {
                parser.CommentTokens = new[] { Context.CsvComment };
            }

            var skipCount = Context.CsvSkipRows;

            while (!parser.EndOfData)
            {
                if (skipCount > 0)
                {
                    --skipCount;
                    continue;
                }

                var lineNumber = parser.LineNumber;

                var fields = parser.ReadFields();
                if (fields == null)
                {
                    continue;
                }

                var point = ParsePoint(fields);

                if (point == null)
                {
                    if (Context.CsvIgnoreInvalidRows)
                    {
                        continue;
                    }

                    throw new ExpectedException($"Can't parse '{path}' ({lineNumber}): {string.Join(", ", fields)}");
                }

                points.Add(point);
            }

            if (Context.CsvRealign)
            {
                points = points
                         .OrderBy(p => p.Time)
                         .ToList();

                if (points.Any())
                {
                    // ReSharper disable once PossibleInvalidOperationException
                    var delta = points.First().Time.Value - Context.StartTime;

                    foreach (var point in points)
                    {
                        // ReSharper disable once PossibleInvalidOperationException
                        point.Time = point.Time.Value.Minus(delta);
                    }
                }
            }

            Log.Info($"Loaded {points.Count} points from '{path}'.");

            return(points);
        }
Example #31
0
        // Process csv file and import data into the application.
        private void ImportData(Stream csvStream)
        {
            this.lblInfo.Text = "";

            // Create data table to hold the data in memory.
            DataTable dt = new DataTable();

            // Parse the csv file and add the data to the data table.
            using (var csvFile = new TextFieldParser(csvStream))
            {
                csvFile.TextFieldType = FieldType.Delimited;
                csvFile.SetDelimiters(",");
                csvFile.HasFieldsEnclosedInQuotes = true;

                // Read the first row of data (which should contain column names).
                string[] fields = csvFile.ReadFields();

                // Add columns to data table, using first (header) row.
                DataColumn col          = null;
                List <int> fieldIndices = new List <int>();

                if (!csvFile.EndOfData)
                {
                    // The FirstName field is required, since it's used for the partition key and row key.
                    if (!fields.Contains("FirstName"))
                    {
                        this.lblInfo.Text      = "The .csv file must contain a FirstName field, named in the first row of data.";
                        this.lblInfo.ForeColor = System.Drawing.Color.Red;
                    }

                    // Create array of property names from ContactEntity.
                    List <string> propertyNames = new List <string>();
                    foreach (PropertyInfo info in typeof(ContactEntity).GetProperties())
                    {
                        propertyNames.Add(info.Name);
                    }

                    // Add a field to the data table if it matches one defined by ContactEntity.
                    for (int i = 0; i < fields.Length; i++)
                    {
                        if (propertyNames.Contains(fields[i]))
                        {
                            col = new DataColumn(fields[i]);
                            dt.Columns.Add(col);

                            // Track the field's index, so we know which ones to add data for below.
                            // This way any fields other than those named by ContactEntity will be ignored.
                            fieldIndices.Add(i);
                        }
                    }
                }

                // Add data from each row to data table where it matches column name.
                DataRow row = null;
                while (!csvFile.EndOfData)
                {
                    // Get the current row from the csv file.
                    string[] currentRow = csvFile.ReadFields();

                    // Create a new row in the data table.
                    row = dt.NewRow();

                    // Copy the data from the csv to the data table.
                    foreach (var index in fieldIndices)
                    {
                        row[index] = currentRow[index];
                    }

                    // Add the row.
                    dt.Rows.Add(row);
                }
            }

            // Insert values from the data table into a Windows Azure table.
            try
            {
                DataLayer.BulkInsertContacts(dt);

                // Redirect to main page.
                Response.Redirect("Default.aspx");
            }
            catch (ApplicationException e)
            {
                this.lblInfo.Text      = "Error importing csv file: " + e.Message;
                this.lblInfo.ForeColor = System.Drawing.Color.Red;
            }
        }
Example #32
0
    /// <summary>
    /// RCAFF
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
        Console.WriteLine("**************************************************");
        Console.WriteLine("Rating Curve based Automatic Flood Forecasting Tool");
        Console.WriteLine("**************************************************");
        Console.WriteLine("A flood inundation delineation forecasting tool using \n a rating curve library approach.");
        Console.WriteLine("This tool was developed as part of a project for the");
        Console.WriteLine("National Flood Interoperability Experiment (NFIE) Summer Institue");
        Console.WriteLine("held at the Univeristy of Alabama in Tuscaloosa");
        Console.WriteLine("from June 1st to July 17th 2015");
        Console.WriteLine("Contact: [email protected]");
        Console.WriteLine("**************************************************");
        Console.WriteLine("");

        Console.CancelKeyPress += Console_CancelKeyPress;

        ConfigureGdal();

        bool first = true;

        //Infinite loop to process arguments
        while (true)
        {
        #if !DEBUG

            //try
            //{
        #endif
            //if initially starting
            if (first)
            {
                first = false;
            }
            else
            {
                Console.Write("Type Commmand>>>>");

                string argString = Console.ReadLine();

                if (argString != null)
                {
                    //Parsing out arguments
                    using (var textStream = new StringReader(argString))
                    {
                        using (var parser = new TextFieldParser(textStream))
                        {
                            parser.Delimiters = new string[] { " " };
                            parser.HasFieldsEnclosedInQuotes = true;
                            args = parser.ReadFields();
                        }
                    }
                }

            }

            String projectFile = null;
            String outputShapefile = null;
            String ratingsCurveXMLLib = null;
            String forecastXML = null;
            String comidFile = null;

            bool verbose = true;
            bool run = false;
            bool exportToGIS = false;
            bool exp = false;
            bool createRatingsCurveLib = false;
            bool help = false;
            bool runForeCast = false;
            bool exportForeCast = false;
            bool expCOMID = false;
            bool getValuesAt = false;
            string folder = "";
            double? x = null, y = null;
            string getValuesAtOutputFile = "";

            //Read arguments
            if (args != null)
                for (int i = 0; i < args.Length; i++ /**/)
                {
                    switch (args[i].ToLower())
                    {
                        case "-help":

                            //Run hec ras model
                            //Console.WriteLine("");
                            //Console.WriteLine("run\tRuns current plan for project");
                            //Console.WriteLine("\tInput Arguments");
                            //Console.WriteLine("\t***************");
                            //Console.WriteLine("\trequired -prj [input project file .prj]");
                            //Console.WriteLine("\toptional -verbose [print messages and progress]");
                            //Console.WriteLine("\toptional -exp [export results to shapefile]");

                            //export shapefile
                            Console.WriteLine("");
                            Console.WriteLine("expGIS\tExport boundaries and cross sections to shapefiles");
                            Console.WriteLine("\tInput Arguments");
                            Console.WriteLine("\t***************");
                            Console.WriteLine("\trequired -prj [input project file .prj]");
                            Console.WriteLine("\trequired -shp [output shapefile]");
                            Console.WriteLine("");

                            //create ratings curve library file
                            Console.WriteLine("");
                            Console.WriteLine("rclib\tCreate ratings curve library");
                            Console.WriteLine("\tInput Arguments");
                            Console.WriteLine("\t***************");
                            Console.WriteLine("\trequired -prj [input project file .prj]");
                            Console.WriteLine("\trequired -libxml [output library]");
                            Console.WriteLine("");

                            //create initial COMID mapping file
                            Console.WriteLine("");
                            Console.WriteLine("expcomid\tCreate intial COMID mapping file for rating curve");
                            Console.WriteLine("\tInput Arguments");
                            Console.WriteLine("\t***************");
                            Console.WriteLine("\trequired -libxml [Ratings curve library file]");
                            Console.WriteLine("\trequired -comid [output COMID mapping file]");
                            Console.WriteLine("");

                            //export forecast file
                            Console.WriteLine("");
                            Console.WriteLine("expfcfile\tExports forecast file based on ratings curve library file");
                            Console.WriteLine("\tInput Arguments");
                            Console.WriteLine("\t***************");
                            Console.WriteLine("\trequired -libxml [Ratings curve library file]");
                            Console.WriteLine("\trequired -comid [Comma separated file mapping comid to cross section and multiplication factors to apply to them. " +
                                "Every cross section must be mapped to a COMID and must have a valid multiplication factor. " +
                                "The Format of this file is [River Reach ID], [Cross Section ID], [COMID], [Multiplication Factor. " +
                                            "Use expCOMID command to export a COMID file you can start with]");
                            Console.WriteLine("\trequired -fxml [Path to output forecast file]");
                            Console.WriteLine("");

                            //run forecast file
                            Console.WriteLine("");
                            Console.WriteLine("runfcfile\tRun forecast file");
                            Console.WriteLine("\tInput Arguments");
                            Console.WriteLine("\t***************");
                            Console.WriteLine("\trequired -fxml [forecast xml file]");
                            Console.WriteLine("");

                            help = true;

                            break;
                        case "run":
                            run = true;
                            break;
                        case "expgis":
                            exportToGIS = true;
                            break;
                        case "rclib":
                            createRatingsCurveLib = true;
                            break;
                        case "expcomid":
                            expCOMID = true;
                            break;
                        case "expfcfile":
                            exportForeCast = true;
                            break;
                        case "runfcfile":
                            runForeCast = true;
                            break;
                        case "-verbose":
                            verbose = true;
                            break;
                        case "-prj":
                            if (i + 1 < args.Length)
                            {
                                projectFile = args[i + 1];
                                i++;
                            }
                            break;
                        case "-exp":
                            exp = true;
                            break;

                        case "-libxml":
                            if (i + 1 < args.Length)
                            {
                                ratingsCurveXMLLib = args[i + 1];
                                i++;
                            }
                            break;
                        case "-comid":
                            if (i + 1 < args.Length)
                            {
                                comidFile = args[i + 1];
                                i++;
                            }
                            break;
                        case "-fxml":
                            if (i + 1 < args.Length)
                            {
                                forecastXML = args[i + 1];
                                i++;
                            }
                            break;
                        case "-shp":
                            if (i + 1 < args.Length)
                            {
                                outputShapefile = args[i + 1];
                                i++;
                            }
                            break;
                        case "gvals":
                            if (i + 1 < args.Length)
                            {
                                getValuesAt = true;
                                folder = args[i + 1];
                                x = double.Parse(args[i + 2]);
                                y = double.Parse(args[i + 3]);
                                getValuesAtOutputFile = args[i + 4];
                            }
                            break;

                    }
                }

            //Execution
            # region Execute HECRAS Model

            if (run == true)
            {
                if (projectFile != null && File.Exists(projectFile))
                {
                    Console.WriteLine("Executing HEC-RAS project " + projectFile + "...\n");

                    HecRasModel model = new HecRasModel(new FileInfo(projectFile));

                    //If verbose
                    if (verbose)
                    {
                        model.Controller.ComputeProgressBar += controller_ComputeProgressBar;
                        model.Controller.ComputeProgressMessage += hecController_ComputeProgressMessage;
                    }

                    int numMessage = 0;
                    Array messages = null;

                    //Run the model
                    model.Controller.Compute_CurrentPlan(ref numMessage, ref messages);

                    //Print model messages
                    for (int m = 0; m < numMessage; m++)
                    {
                        Console.WriteLine("Message [" + m + "] => " + messages.GetValue(m).ToString());
                    }

                    //write profiles to export as GIS
                    model.WriteProfilesToExportAsGIS();

                    //Export to shapefile
                    if (exp)
                    {
                        model = new HecRasModel(new FileInfo(projectFile));
                        model.SaveProfilesToShapeFile(new FileInfo(outputShapefile));
                    }

                    Console.WriteLine("Finished executing HEC-RAS project " + projectFile + "\n");
                }
                else
                {
                    Console.WriteLine("Requires a valid HEC-RAS input file .prj");
                }
            }
            # endregion

            # region Export HECRAS to GIS

            else if (exportToGIS)
            {
                if (projectFile != null)
                {
                    Console.WriteLine("Exporting HEC-RAS to shapefiles using " + projectFile + "...\n");
                    HecRasModel model = new HecRasModel(new FileInfo(projectFile));

                    if (outputShapefile != null)
                    {
                        model.SaveProfilesToShapeFile(new FileInfo(outputShapefile));
                        Console.WriteLine("Finished exporting HEC-RAS profiles to shapefiles using " + projectFile + "\n");
                    }
                    else
                    {
                        Console.WriteLine("Please specifiy output shapefile");
                    }
                }
                else
                {
                    Console.WriteLine("Please specifiy project file to export");
                }
            }

            #endregion

            #region Create ratings curve library for lookup

            else if (createRatingsCurveLib)
            {
                if (projectFile != null)
                {
                    if (ratingsCurveXMLLib != null)
                    {

                        Console.WriteLine("Exporting HEC-RAS model to ratings curve library using " + projectFile + "...\n");

                        HecRasModel model = new HecRasModel(new FileInfo(projectFile));
                        model.WriteProfilesToExportAsGIS();

                        //save to be safe
                        model.ReadRatingsCurves();

                        using (TextWriter writer = new StreamWriter(ratingsCurveXMLLib))
                        {
                            XmlSerializer sr = new XmlSerializer(typeof(HecRasModel));
                            sr.Serialize(writer, model);
                        }

                        Console.WriteLine("Finished exporting HEC-RAS model to ratings curve library using " + projectFile + "\n");
                    }
                    else
                    {
                        Console.WriteLine("Please specifiy output library file");
                    }

                }
                else
                {
                    Console.WriteLine("Please specifiy project file to export");
                }
            }

            # endregion

            #region Export Initialization COMID file

            else if (expCOMID)
            {
                if (ratingsCurveXMLLib != null || !File.Exists(ratingsCurveXMLLib))
                {
                    if (comidFile != null)
                    {
                        Console.WriteLine("Exporting COMID mapping file using " + ratingsCurveXMLLib + "...\n");

                        using (TextReader reader = new StreamReader(ratingsCurveXMLLib))
                        {
                            XmlSerializer sr = new XmlSerializer(typeof(HecRasModel));
                            HecRasModel model = (HecRasModel)sr.Deserialize(reader);
                            model.OpenHECRASProjectFile();
                            model.ReadProfiles();
                            model.ReadSteadyStateFlowData();

                            List<River> rivers = model.Rivers.Values.ToList();

                            Console.WriteLine("\nAvailable Rivers or Tributaries");
                            Console.WriteLine("=================================");

                            for (int i = 0; i < model.Rivers.Count; i++)
                            {
                                Console.WriteLine("Index: " + i + " River Name: " + rivers[i].Name);
                            }

                            Console.WriteLine("Enter index for main river to use to derive multiplication factors");
                            string indexAsString = Console.ReadLine();
                            int riverIndex;

                            if (int.TryParse(indexAsString, out riverIndex) && riverIndex >= 0 && riverIndex < rivers.Count)
                            {
                                River river = rivers[riverIndex];
                                List<Reach> reaches = river.Reaches.Values.ToList();

                                Console.WriteLine("\nAvailable Steady State Profiles");
                                Console.WriteLine("=================================");

                                for (int i = 0; i < model.Profiles.Count; i++)
                                {
                                    Console.WriteLine("Index: " + i + " Profile Names: " + model.Profiles[i]);
                                }

                                Console.WriteLine("=================================");
                                Console.WriteLine("Enter index for profile to use");
                                indexAsString = Console.ReadLine();

                                int profileIndex;

                                if (int.TryParse(indexAsString, out profileIndex) && profileIndex >= 0 && profileIndex < model.Profiles.Count)
                                {
                                    string profileName = model.Profiles[profileIndex];
                                    Reach downstreamReach = reaches[reaches.Count - 1];
                                    List<XSection> xsections = downstreamReach.XSections.Values.ToList();

                                    double normalizationFactor = xsections[xsections.Count - 1].ProfileFlows[profileName];

                                    using (TextWriter writer = new StreamWriter(comidFile))
                                    {
                                        writer.WriteLine("River_Name,Reach_Name,XSection_Station_Name,COMID,MultiplicationFactor");

                                        for (int i = 0; i < rivers.Count; i++)
                                        {
                                            river = rivers[i];

                                            reaches = river.Reaches.Values.ToList();

                                            for (int m = 0; m < reaches.Count; m++)
                                            {
                                                Reach reach = reaches[m];

                                                xsections = reach.XSections.Values.ToList();

                                                for (int j = 0; j < xsections.Count; j++)
                                                {
                                                    XSection xsection = xsections[j];

                                                    writer.WriteLine(river.Name + "," + reach.Name + "," + xsection.StationName + ", [COMID]," + (xsection.ProfileFlows[profileName] / normalizationFactor));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        Console.WriteLine("Finished exporting COMID mapping file using " + ratingsCurveXMLLib + "\n");
                    }
                }
                else
                {
                    Console.WriteLine("\nPlease specify valid ratings curve library path\n");
                }
            }

            # endregion

            # region Export forecast file

            else if (exportForeCast)
            {
                if (ratingsCurveXMLLib != null && File.Exists(ratingsCurveXMLLib))
                {
                    if (comidFile != null && File.Exists(comidFile))
                    {
                        if (forecastXML != null)
                        {
                            Console.WriteLine("Exporting forecast file ...\n");

                            ForeCastConfiguration forecast = new ForeCastConfiguration(new FileInfo(ratingsCurveXMLLib));

                            using (TextReader reader = new StreamReader(comidFile))
                            {
                                string line = "";
                                string[] delim = new string[] { "," };

                                while ((line = reader.ReadLine()) != null)
                                {
                                    string[] cols = line.Split(delim, StringSplitOptions.RemoveEmptyEntries);

                                    double outVal;

                                    if (cols.Length == 5 && double.TryParse(cols[4], out outVal))
                                    {
                                        forecast.SetCOMIDAndFlowFactor(cols[0], cols[1], cols[2], int.Parse(cols[3]), outVal);
                                    }
                                }

                                reader.Close();
                            }

                            forecast.SaveAs(new FileInfo(forecastXML));

                            Console.WriteLine("Finished exporting forecast file ...\n");

                        }
                        else
                        {
                            Console.WriteLine("\nPlease specify file to save forecast file\n");
                        }
                    }
                    else
                    {
                        Console.WriteLine("\nPlease specify valid COMID mapping file. Create a new mapping file using the expcomid command \n");
                    }
                }
                else
                {
                    Console.WriteLine("\nPlease specify valid ratings curve library path\n");
                }
            }

            #endregion

            # region Run forecast file

            else if (runForeCast)
            {
                if (forecastXML != null && File.Exists(forecastXML))
                {
                    using (TextReader reader = new StreamReader(forecastXML))
                    {
                        XmlSerializer sr = new XmlSerializer(typeof(ForeCastConfiguration));
                        ForeCastConfiguration forecast = (ForeCastConfiguration)sr.Deserialize(reader);
                        forecast.ForecastFile = forecastXML;
                        reader.Close();
                        reader.Dispose();
                        forecast.Start();
                    }
                }
                else
                {
                    Console.WriteLine("\nPlease specify valid forecast file");
                }
            }

            # endregion

            #region extract location

            else if(getValuesAt)
            {
                if(Directory.Exists(folder) && x.HasValue && y.HasValue)
                {
                    FileInfo[] files = (new DirectoryInfo(folder)).GetFiles("*.tif");

                    using (TextWriter writer = new StreamWriter(getValuesAtOutputFile,false))
                    {
                        writer.WriteLine("File,Value");

                        for (int i = 0; i < files.Length; i++)
                        {
                            double[] geoTransformation = new double[6];

                            Dataset rasterElevationGeotiff = Gdal.Open(files[i].FullName, Access.GA_ReadOnly);
                            int xSize = rasterElevationGeotiff.RasterXSize;
                            int ySize = rasterElevationGeotiff.RasterYSize;

                            rasterElevationGeotiff.GetGeoTransform(geoTransformation);

                            Band band = rasterElevationGeotiff.GetRasterBand(1);

                            Point p = ForeCastConfiguration.getCoordIndexes(x.Value, y.Value, geoTransformation);

                            float[] v = new float[1];

                            int oi = p.X < 0 ? 0 : (int)p.X;
                            oi = oi >= xSize ? xSize -1 : oi;

                            int oj = p.Y < 0 ? 0 : (int)p.Y;
                            oj = oj >= ySize ? ySize - 1 : oj;

                            band.ReadRaster(oi, oj, 1, 1, v, 1, 1, 0,0);

                            writer.WriteLine(files[i].Name + "," + v[0]);
                            band.Dispose();
                            band = null;

                            rasterElevationGeotiff.Dispose();
                            rasterElevationGeotiff = null;
                        }
                    }
                }
            }

            # endregion

            else if (args == null || (args.Length > 0 && args[0] != "-help" && !help))
            {
                Console.WriteLine("\nCommand was not recognized. Type -help for proper usage of commands\n");
            }
        #if !DEBUG

            //}
            //catch (Exception ex)
            //{
            //    Console.ForegroundColor = ConsoleColor.Red;

            //    Console.WriteLine("Exceptions");
            //    Console.WriteLine("==================================");

            //    Console.WriteLine("\n" + ex.Message);

            //    Console.WriteLine("Inner Exceptions");
            //    Console.WriteLine("\t==================================");
            //    Exception tex = ex.InnerException;

            //    while (tex != null)
            //    {
            //        Console.WriteLine("\t" + tex.Message);
            //        tex = tex.InnerException;
            //    }

            //    Console.WriteLine("\tStackTrace");
            //    Console.WriteLine("\t==================================");
            //    Console.WriteLine("\t" + ex.StackTrace);

            //    Console.ResetColor();
            //}
        #endif
        }
    }