Exemplo n.º 1
0
 public void Films()
 {
     ConsoleTable
     .From(Movies.GetMovies())
     .Write();
 }
Exemplo n.º 2
0
        public static void LinqVsLambda()
        {
            // LVL simple ordered query
            var title  = "g";
            var rating = "pg-13";
            var years  = new[] { 2016, 2015, 2012 };

            Console.WriteLine($"Films with letter {title} in their title, rated {rating}");
            Console.WriteLine($", filmed in years: {string.Join(", ", years.Select(y => y.ToString()))}");
            Console.WriteLine();
            Console.WriteLine("LINQ");
            var films = (from f in MoviesContext.Instance.Films
                         where f.Title.Contains(title) &&
                         f.RatingCode == rating &&
                         f.ReleaseYear.HasValue &&
                         years.Contains(f.ReleaseYear.Value)
                         orderby f.ReleaseYear descending,
                         f.Title
                         select f.Copy <Film, FilmModel>());

            ConsoleTable.From(films).Write();
            // Results are identical
            Console.WriteLine("Lambda");
            films = MoviesContext.Instance.Films
                    .Where(f => f.Title.Contains(title) &&
                           f.RatingCode == rating &&
                           f.ReleaseYear.HasValue &&
                           years.Contains(f.ReleaseYear.Value))
                    .OrderByDescending(f => f.ReleaseYear)
                    .ThenBy(f => f.Title)
                    .Select(f => f.Copy <Film, FilmModel>());
            ConsoleTable.From(films).Write();

            // LVL Groupings
            string delimiter = "---------------------------------------------";

            Console.WriteLine();
            Console.WriteLine(new String('~', delimiter.Length));
            Console.WriteLine();

            Console.WriteLine("Films grouped by rating");
            Console.WriteLine();

            Console.WriteLine("LINQ");
            var filmGroups = (from f in MoviesContext.Instance.Films
                              group f by f.Rating into g
                              select g);

            foreach (var filmGroup in filmGroups)
            {
                Console.WriteLine(filmGroup.Key);
                foreach (var film in filmGroup.OrderBy(f => f.Title))
                {
                    Console.WriteLine($"\t{film.Title}");
                }
            }

            Console.WriteLine();
            Console.WriteLine(delimiter);
            Console.WriteLine();

            Console.WriteLine("Lambda");
            filmGroups = MoviesContext.Instance.Films
                         .GroupBy(f => f.Rating);
            foreach (var filmGroup in filmGroups)
            {
                Console.WriteLine(filmGroup.Key);
                foreach (var film in filmGroup.OrderBy(f => f.Title))
                {
                    Console.WriteLine($"\t{film.Title}");
                }
            }

            Console.WriteLine();
            Console.WriteLine(new String('~', delimiter.Length));
            Console.WriteLine();

            // LVL Joins
            var ratings = new[] {
                new { Code = "G", Name = "General Audiences" },
                new { Code = "PG", Name = "Parental Guidance Suggested" },
                new { Code = "PG-13", Name = "Parents Strongly Cautioned" },
                new { Code = "R", Name = "Restricted" },
            };

            Console.WriteLine($"Films joined with rating names:");
            Console.WriteLine($"{string.Join(", ", ratings.Select(r => r.Code + "=" + r.Name))}");
            Console.WriteLine();

            Console.WriteLine("LINQ");
            var joinedFilms = (from f in MoviesContext.Instance.Films
                               join r in ratings on f.RatingCode equals r.Code
                               select new { f.Title, r.Code, r.Name });

            ConsoleTable.From(joinedFilms).Write();

            Console.WriteLine("Lambda");
            joinedFilms = MoviesContext.Instance.Films.Join(ratings,
                                                            f => f.RatingCode,
                                                            r => r.Code,
                                                            (f, r) => new { f.Title, r.Code, r.Name });
            ConsoleTable.From(joinedFilms).Write();
        }
 public string CreateTable <T>(IEnumerable <T> collection)
 {
     return(ConsoleTable.From <T>(collection).ToString());
 }
Exemplo n.º 4
0
        internal static void UpdateItem()
        {
            // update an actor
            Console.WriteLine("Update an Actor");
            Console.WriteLine("Enter an Actor ID");
            var actorId = Console.ReadLine().ToInt();

            var actor = MoviesContext.Instance.Actors.SingleOrDefault(actor => actor.ActorId == actorId);

            if (actor == null)
            {
                Console.WriteLine($"Actor with id {actorId} not found");
            }
            else
            {
                ConsoleTable.From(new[] { actor.Copy <Actor, ActorModel>() }).Write();


                Console.WriteLine("Enter the First Name");
                var firstName = Console.ReadLine().Trim();

                Console.WriteLine("Enter the Last Name");
                var lastName = Console.ReadLine().Trim();

                actor.FirstName = firstName;
                actor.LastName  = lastName;


                MoviesContext.Instance.SaveChanges();

                var actors = MoviesContext.Instance.Actors.Where(actor => actor.ActorId == actorId).Select(actor => actor.Copy <Actor, ActorModel>());

                ConsoleTable.From(actors).Write();
            }

            // update a film

            Console.WriteLine("Update a Film");

            Console.WriteLine("Enter a Film ID");
            var filmId = Console.ReadLine().ToInt();

            var film = MoviesContext.Instance.Films
                       .SingleOrDefault(a => a.FilmId == filmId);

            if (film == null)
            {
                Console.WriteLine($"Film with id {filmId} not found");
            }
            else
            {
                ConsoleTable.From(new[] { film.Copy <Film, FilmModel>() })
                .Write();

                Console.WriteLine("Enter the Title");
                var title = Console.ReadLine().Trim();

                Console.WriteLine("Enter the Release Year");
                var releaseYear = Console.ReadLine().ToInt();

                Console.WriteLine("Enter the Rating");
                var rating = Console.ReadLine().Trim();

                if (!string.IsNullOrWhiteSpace(title) && film.Title != title)
                {
                    film.Title = title;
                }

                if (releaseYear > 0 && film.ReleaseYear != releaseYear)
                {
                    film.ReleaseYear = releaseYear;
                }

                if (!string.IsNullOrWhiteSpace(rating) && film.Rating != rating)
                {
                    film.Rating = rating;
                }

                MoviesContext.Instance.SaveChanges();

                var films = MoviesContext.Instance.Films
                            .Where(a => a.FilmId == filmId)
                            .Select(a => a.Copy <Film, FilmModel>());
                ConsoleTable.From(films).Write();
            }
        }
Exemplo n.º 5
0
        private static void WriteActors()
        {
            var actors = MoviesContext.Instance.Actors.Select(actors => actors.Copy <Actor, ActorModel>());

            ConsoleTable.From(actors).Write();
        }
Exemplo n.º 6
0
 private void AfficherListeClient()
 {
     _listeClient = AppGrandHotel.Instance.Contexte.GetListClient();
     ConsoleTable.From(_listeClient, "Client").Display("Client");
 }
Exemplo n.º 7
0
        public void Run(TimeSpan timeLimit)
        {
            MyEngine = MyBuilder.Build(timeLimit);

            watch = System.Diagnostics.Stopwatch.StartNew();

            Console.WriteLine("Optimizing...");

            Thread thread = new Thread(() => Optimize());

            thread.Start();
            ThreadInProgress = true;
            counter          = 1;
            MyEngine.watch   = System.Diagnostics.Stopwatch.StartNew();
            while (ThreadInProgress)
            {
                if (MyEngine.MyPriority != Priority.FirstAvailable)
                {
                    var status = MyEngine.GetStatus(counter++.ToString(), watch.Elapsed);
                    Console.WriteLine(status);
                    System.Threading.Thread.Sleep(4000);
                }
            }
            thread.Join();

            // Add the results to the table
            foreach (var result in MyResults.Results)
            {
                result.CreationTimestamp    = DateTime.Today;
                context.Entry(result).State = result.ID == 0 ? EntityState.Added : EntityState.Modified;
            }
            foreach (var input in MyResults.Inputs)
            {
                context.Entry(input).State = input.Id == 0 ? EntityState.Added : EntityState.Modified;
            }
            //context.SaveChanges();

            if (ShowDebugMessages)
            {
                watch.Stop();
                Console.WriteLine("\nOptimization Complete.\n");
                if (MyEngine.MyPriority != Priority.FirstAvailable)
                {
                    Console.WriteLine(MyEngine.GetStatus("Final", watch.Elapsed) + "\n");
                }

                Console.WriteLine("\nOriginal Optimizer Inputs");
                ConsoleTable.From <OptimizerInputPrintable>(MyEngine.Inputs.Select(x => new OptimizerInputPrintable(x))).Write(Format.MarkDown);
                Console.WriteLine("");
                Console.WriteLine("Preexisting Schedule");
                try
                {
                    ConsoleTable.From <ScheduledClassPrintable>(MyEngine.CurrentSchedule.Select(c => new ScheduledClassPrintable(c))).Write(Format.MarkDown);
                }
                catch
                {
                }
                switch (MyEngine.MyPriority)
                {
                case Priority.Default:
                    Console.WriteLine($"Total classes scheduled: {MyResults.Results.Count} out of {MyBuilder.OriginalInputCount}.\n");
                    break;

                case Priority.FirstAvailable:
                    break;

                case Priority.MaximizeInstructorLongestToTeach:
                    Console.WriteLine($"The total time between all instructor assignments and the last time they taught the course is {MyEngine.CurrentBestAnswer.OptimizationScore} days.\n");
                    break;

                case Priority.MaximizeSpecializedInstructors:
                    Console.WriteLine($"Between all assigned instructors for this answer, they have a total of {MyResults.OptimizationScore} qualifications.\n");
                    break;

                case Priority.MinimizeForeignInstructorCount:
                    Console.WriteLine($"{MyResults.OptimizationScore} instructors will have to travel to fulfill these assignments.\n");
                    break;

                case Priority.MinimizeInstructorTravelDistance:
                    Console.WriteLine($"Instructors will have to travel a total of {MyResults.OptimizationScore} miles to fulfill these assignments.\n");
                    break;
                }
                MyResults.Print();
            }
        }
Exemplo n.º 8
0
        public static void EditConfig()
        {
            string c = "";

            while (c != "exit")
            {
                var accounts = new List <AccountRecord>();
                for (int i = 0; i < config.Accounts.Length; i++)
                {
                    var acc = new AccountRecord {
                        Name     = config.Accounts[i].Name,
                        Password = config.Hide ? new string('*', config.Accounts[i].Password.Length) : config.Accounts[i].Password
                    };
                    accounts.Add(acc);
                }
                if (c != "help")
                {
                    ConsoleTable.From(accounts).Write((Format)config.TableFormat);
                }

                Console.Write("terminal-pass> ");
                string   raw    = Console.ReadLine();
                string[] tokens = raw.Split(' ').ToArray();
                try
                {
                    c = tokens[0];
                    switch (c)
                    {
                    case "help":
                        Colors.WriteLine("\treload".Yellow(), " -> ", "Updates the file and reloads the table");
                        Colors.WriteLine("\tdelete ".Yellow(), "name".Green(), " -> ", "Deletes row with name specified.");
                        Colors.WriteLine("\tadd ".Yellow(), "name".Green(), " password".Green(), " -> ", "Adds a new row.");
                        Colors.WriteLine("\tset ".Yellow(), "key".Green(), " value".Green(), " -> ", "Used to change the config settings.");
                        Colors.WriteLine("\t\t\t hide ".Yellow(), "true/false".Green(), ": ", "Show/Hide passwords when displaying the table.");
                        break;

                    case "reload":
                        WriteConfig(config, masterPassword);
                        Console.Clear();
                        break;

                    // delete name
                    case "delete":
                        string nameToDelete = tokens[1];
                        config.Accounts = config.Accounts.Where(acc => acc.Name != nameToDelete).ToArray();
                        WriteConfig(config, masterPassword);
                        Console.Clear();
                        break;

                    // add name password
                    case "add":
                        string name     = tokens[1];
                        string password = tokens[2];
                        config.Accounts = config.Accounts
                                          .Concat(new AccountRecord[] { new AccountRecord {
                                                                            Name = name, Password = password
                                                                        } })
                                          .ToArray();
                        WriteConfig(config, masterPassword);
                        Console.Clear();
                        break;

                    case "set":
                        switch (tokens[1])
                        {
                        case "hide":
                            if (bool.TryParse(tokens[2], out bool hide))
                            {
                                config.Hide = hide;
                            }
                            break;
                        }
                        WriteConfig(config, masterPassword);
                        Console.Clear();
                        break;

                    default:
                        Console.WriteLine($"Invalid name {tokens[1]}.");
                        break;
                    }
                } catch (Exception e)
                {
                    Console.WriteLine("Invalid command");
                    Console.WriteLine(e.Message);
                }
            }
        }
Exemplo n.º 9
0
 protected override void DisplayResult(ChatOverview[] result)
 {
     ConsoleTable
     .From(result)
     .Write(Format.Minimal);
 }
Exemplo n.º 10
0
        private void AfficherPays()
        {
            List <string> Pays = Contexte.GetPaysFournisseurs();

            ConsoleTable.From(Pays, "Pays").Display("pays");
        }
Exemplo n.º 11
0
 public void PrintReport()
 {
     ConsoleTable.From(_debugList).Write();
 }
Exemplo n.º 12
0
        private void AfficherClientsCommandes()
        {
            List <CommandeClient> Comm = Contexte.GetClientsCommandes();

            ConsoleTable.From(Comm, "Comm").Display("Comm");
        }
Exemplo n.º 13
0
        private static async System.Threading.Tasks.Task Main(string[] args)
        {
            IServiceCollection services = new ServiceCollection();

            services.AddDataTransferServices();
            using var serviceProvider = services.BuildServiceProvider();
            var dataTransfer = serviceProvider.GetService <ReportGeneratorService>();

            Console.OutputEncoding = System.Text.Encoding.Unicode; // allow printing of unicode character i.e € symbol

            Console.WriteLine("Hello Welcome to....... ");
            Console.WriteLine("Please copy the file path to where the CSV is stored or copy the http link where the data can be requested");

            string         userInput = Console.ReadLine();
            List <BetData> betData   = new List <BetData>();

            if (userInput.Length >= 3 && userInput.EndsWith(".csv")) // check is csv
            {
                // TODO: Add exception handling
                Console.WriteLine("Trying to read data from the csv file..");
                betData = CsvParser.ParseCsv <BetData>(userInput);
                //Success message here
            }
            if (userInput.Contains("http"))
            {
                try
                {
                    Console.WriteLine($"Data will be requested from {userInput}");
                    // validate that you can make request
                    betData = (List <BetData>) await dataTransfer.GetBetDataApi(userInput);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"An exception occured when trying to obtain data from {userInput}\n{ex}");
                    throw;
                }
            }

            // Type of Report to be Generated
            Console.WriteLine("\nHow would you like the data outputed?" +
                              "\nPress 1 for it to be outputed to the console or 2 for it to written to a CSV file");

            string input = Console.ReadLine();

            if (input.Equals("1"))
            {
                ReportType reportType = TypeOfReport();
                if (reportType == ReportType.Report1)
                {
                    var report1 = dataTransfer.GenerateReport1(betData);
                    // make method here for generating console report
                    ConsoleTable

                    .From(report1.Select(x => new Report1
                    {
                        Currency       = x.Currency.ToString(),
                        SelectionName  = x.SelectionName,
                        TotalStakes    = $"{CurrencyHelper.GetCurrencySymbol(x.Currency.ToString())}{x.TotalStakes:F}",
                        TotalLiability = $"{CurrencyHelper.GetCurrencySymbol(x.Currency.ToString())}{x.TotalLiability:F}",
                        NumberOfBets   = x.NumberOfBets
                    }))

                    .Configure(o => o.NumberAlignment = Alignment.Right)
                    .Write(Format.Alternative);
                }
                if (reportType == ReportType.Report2)
                {
                    var report2 = dataTransfer.GenerateReport2(betData);
                    ConsoleTable
                    .From(report2.Select(x => new Report2
                    {
                        Currency       = x.Currency,
                        NumOfBets      = x.NumberOfBets,
                        TotalStakes    = $"{CurrencyHelper.GetCurrencySymbol(x.Currency.ToString())}{x.TotalStakes:F}",
                        TotalLiability = $"{CurrencyHelper.GetCurrencySymbol(x.Currency.ToString())}{x.TotalLiability:F}",
                    }))
                    .Configure(o => o.NumberAlignment = Alignment.Right)
                    .Write(Format.Alternative);
                }
                Console.WriteLine("Table outputted to console");
                Console.WriteLine("Press any key to exit..");
                Console.ReadLine();
                Environment.Exit(0); // exit app
            }
            else if (input.Equals("2"))
            {
                ReportType reportType = TypeOfReport();
                // TODO: Confirm you want to overwrite
                string fileName = $"{reportType}bet_data_ouput.csv";

                if (reportType == ReportType.Report1)
                {
                    var report1 = dataTransfer.GenerateReport1(betData);
                    CsvParser.CreateCsv(report1.ToList(), fileName);
                }
                if (reportType == ReportType.Report2)
                {
                    var report2 = dataTransfer.GenerateReport2(betData);
                    CsvParser.CreateCsv(report2.ToList(), fileName);
                }


                Console.WriteLine($"The file will be generated in {Directory.GetCurrentDirectory()}/{reportType}bet_data_output.csv");
            }

            else
            {
                Console.WriteLine("You didn't select a valid option\nExiting...");
            }
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
            Environment.Exit(0); // exit app
        }
Exemplo n.º 14
0
 private void PrintTable(IReadOnlyList <LasFileRecord> records)
 {
     ConsoleTable.From <LasFileRecord>(records)
     .Configure(o => o.NumberAlignment = Alignment.Right)
     .Write(Format.Alternative);
 }
Exemplo n.º 15
0
 private static void PrintOrderMarket(OrderMarketSnap market)
 {
     Console.WriteLine("Orders (marketid={0}):", market.MarketId);
     ConsoleTable.From(market.OrderMarketRunners.SelectMany(r => r.UnmatchedOrders.Values))
     .Write();
 }
        public void EmptyClassTest()
        {
            var collection = new[] { new EmptyClass() };

            var table = ConsoleTable.From(collection);
        }
Exemplo n.º 17
0
        private void AfficherPays()
        {
            var pays = Contexte.GetPaysFournisseur();

            ConsoleTable.From(pays, "Pays").Display("pays");
        }
 public void NullCollectionTest()
 {
     var table = ConsoleTable.From <PropertiesClass>(null);
 }
Exemplo n.º 19
0
        public async Task ImportDomainUsersFromFileAsync()
        {
            var userDataLines = await File.ReadAllLinesAsync(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DomainUsersData.txt"));

            var importUsersResponse = new List <ImportUserResponse>();

            foreach (var userDataLine in userDataLines)
            {
                var userResponse = new ImportUserResponse {
                    Data = userDataLine
                };
                importUsersResponse.Add(userResponse);

                var userData = userDataLine.Split(',');
                if (userData.Length != 6)
                {
                    Log.Error($"Data is not in correct format: {userDataLine}");
                    continue;
                }

                var  email       = userData.ElementAt(0);
                bool emailExists = (await this._userManager.FindByEmailAsync(email)) != null;
                if (emailExists)
                {
                    Log.Error($"User already exits with the email {email}, Data: {userDataLine}");
                    continue;
                }

                if (!Enum.TryParse <UserType>(userData.ElementAt(1), out var userType))
                {
                    Log.Error($"User type is not valid, Data: {userDataLine}");
                    continue;
                }

                var userName = userData.ElementAt(2);

                if (userName.IndexOf("\\") < 0)
                {
                    Log.Error($"User name {userName} is not valid, Data: {userDataLine}");
                    continue;
                }

                if (await this._userManager.FindByLoginAsync(IdentityConstants.WindowsLoginProvider, userName) != null)
                {
                    Log.Error($"Domain user already exits with username {userName}, Data: {userDataLine}");
                    continue;
                }

                var user = new ApplicationUser
                {
                    Email      = email,
                    UserName   = email,
                    UserTypeId = userType,
                    IsActive   = true,
                    Profile    = new UserProfile
                    {
                        FirstName = userData.ElementAt(3),
                        LastName  = userData.ElementAt(4)
                    }
                };

                user.UserLogins.Add(new IdentityUserLogin <string>
                {
                    LoginProvider       = IdentityConstants.WindowsLoginProvider,
                    ProviderDisplayName = IdentityConstants.WindowsLoginProviderDisplayName,
                    ProviderKey         = userName
                });

                var result = await this._userManager.CreateAsync(user);

                if (!result.Succeeded)
                {
                    Log.Error($"User creation failed with data: {userDataLine}");
                    continue;
                }

                userResponse.IsUserAdded = true;

                Log.Information($"User created successfully with data: {userDataLine}");

                var role = userData.ElementAt(4);
                try
                {
                    result = await this._userManager.AddToRoleAsync(user, role);

                    if (!result.Succeeded)
                    {
                        Log.Error($"Adding role {role} to user is failed, Data: {userDataLine}");
                        continue;
                    }

                    userResponse.IsRoleAssigned = true;

                    Log.Information($"Added role {role} to user, Data: {userDataLine}");
                }
                catch (Exception ex)
                {
                    Log.Error($"An error occurred while adding role {role} to the user, Data: {userDataLine}\nException: {JsonConvert.SerializeObject(ex)}");
                    continue;
                }
            }

            if (importUsersResponse.Any())
            {
                ConsoleTable
                .From(importUsersResponse)
                .Configure(o => o.NumberAlignment = Alignment.Right)
                .Write();
            }
            else
            {
                Console.Write("\n************************************************************\n");
                Console.Write("File does not contain any data");
                Console.Write("\n************************************************************\n\n");
            }
        }
        public async void GroupByAccountFromCommand(string companyName)
        {
            try
            {
                ConsoleLogger.LogInformation(
                    string.Concat("Calculation Test: Mapreduce on Sharded Cluster: ",
                                  companyName, " Started."));

                const string reduceCollectionName = "calculationresults";

                var accountMapScript       = Helpers.GetScriptContent(@"SampleMongoScripts\MapReduce\accountMap.mongojs");
                var accountFactorMapScript =
                    Helpers.GetScriptContent(@"SampleMongoScripts\MapReduce\accountFactorMap.mongojs");
                var reduceScript   = Helpers.GetScriptContent(@"SampleMongoScripts\MapReduce\reduce.mongojs");
                var finalizeScript = Helpers.GetScriptContent(@"SampleMongoScripts\MapReduce\finalize.mongojs");

                var mapReduceAggregationScript =
                    File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(),
                                                  @"SampleMongoScripts\MapReduce\aggregation.mongojs"))
                    .Replace("[[TargetCollection]]", reduceCollectionName)
                    .Replace("[[CompanyName]]", companyName);


                var timer = Stopwatch.StartNew();

                Task.Run(async() =>
                {
                    await MongoDataContext.Repository <Account>()
                    .GetCollection()
                    .MapReduceAsync(accountMapScript, reduceScript,
                                    new MapReduceOptions <Account, BsonDocument>
                    {
                        Finalize      = finalizeScript,
                        OutputOptions =
                            MapReduceOutputOptions.Reduce(reduceCollectionName,
                                                          MongoDataContext.Database.DatabaseNamespace.DatabaseName)
                    });

                    await MongoDataContext.Repository <AccountFactor>()
                    .GetCollection()
                    .MapReduceAsync(accountFactorMapScript, reduceScript,
                                    new MapReduceOptions <AccountFactor, BsonDocument>
                    {
                        Finalize      = finalizeScript,
                        OutputOptions =
                            MapReduceOutputOptions.Reduce(reduceCollectionName,
                                                          MongoDataContext.Database.DatabaseNamespace.DatabaseName)
                    });
                    ConsoleLogger.LogWarning(string.Concat("Mapreduce finished. New collection created: ",
                                                           reduceCollectionName));
                }).Wait();

                ConsoleLogger.LogWarning(string.Concat("Document count for ", reduceCollectionName, ": ",
                                                       MongoDataContext.Database.GetCollection <BsonDocument>(reduceCollectionName)
                                                       .AsQueryable()
                                                       .Count()
                                                       .ToString("N0")));

                var result =
                    await
                    MongoDataContext.Database.GetCommandResultAsync <MapReduceCalculationResult>(
                        mapReduceAggregationScript);

                timer.Stop();

                Console.WriteLine(string.Concat(Environment.NewLine, "### MapreduceOnShardedCluster >> ",
                                                companyName, " ###"));
                ConsoleTable.From(result).Write(Format.Alternative);

                var timespan = timer.Elapsed;
                ConsoleLogger.LogInformation(
                    string.Concat("Calculation Test: Mapreduce on Sharded Cluster: ",
                                  companyName, " Finished. Duration: ",
                                  string.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds,
                                                timespan.Milliseconds / 10)));

                _testCounter++;
                ConsoleLogger.LogWarning(string.Concat("Test(s) left: ", _testCounter, "/", _testCount));
            }
            catch (Exception ex)
            {
                ConsoleLogger.LogCritical(ex.GetAllMessages());
            }
        }
Exemplo n.º 21
0
        public static void Main(string[] args)
        {
            FrontendInitializer.RegisterTypes(ServiceLocator.Default);
            FrontendInitializer.Initialize(ServiceLocator.Default);
            var vendorPresetParserService = ServiceLocator.Default.ResolveType <VendorPresetParserService>();
            var logger = new RollingInMemoryLogListener();

            LogManager.AddListener(logger);

            var pluginTestDirectory = @"C:\Program Files\VSTPlugins";
            var testResults         = new List <PluginTestResult>();

            var presetParserDictionary = vendorPresetParserService.GetPresetHandlerListByPlugin();


            var testData       = ReadTestData();
            var ignoredPlugins = ReadIgnoredPlugins();

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

            IgnoredPresetParsers.Add("VoidPresetParser");

            var localLogger = new MiniConsoleLogger();
            var hasIgnored  = false;

            localLogger.SetConsoleLogLevelFilter(new HashSet <LogLevel> {
                LogLevel.Error, LogLevel.Warning
            });

            if (args.Length > 0)
            {
                foreach (var key in presetParserDictionary.Keys.ToList())
                {
                    if (!presetParserDictionary[key].PresetParserType.ToLower().Contains(args[0].ToLower()))
                    {
                        presetParserDictionary.Remove(key);
                        hasIgnored = true;
                    }
                }
            }

            foreach (var presetParserKeyValue in presetParserDictionary)
            {
                var presetParser = presetParserKeyValue.Value;
                var pluginId     = presetParserKeyValue.Key;

                if (IgnoredPresetParsers.Contains(presetParser.PresetParserType))
                {
                    continue;
                }

                if (IsIgnored(ignoredPlugins, presetParser.PresetParserType, pluginId))
                {
                    continue;
                }

                Console.Write(presetParser.PresetParserType + ": ");

                var start = DateTime.Now;

                var pluginLocation = new PluginLocation
                {
                    DllPath = @"C:\Program Files\VstPlugins\Foobar.dll", IsPresent = true
                };

                var plugin = new Plugin
                {
                    VstPluginId = pluginId, PluginLocation = pluginLocation,
                    PluginInfo  = new VstPluginInfoSurrogate
                    {
                        ProgramCount = 1, Flags = VstPluginFlags.ProgramChunks, PluginID = pluginId
                    }
                };

                var stubProcess = new StubVstHostProcess();
                stubProcess.PluginId = pluginId;

                var remoteInstance = new RemotePluginInstance(stubProcess, plugin);

                presetParser.DataPersistence = new NullPresetPersistence();
                presetParser.PluginInstance  = remoteInstance;
                presetParser.RootBank        = plugin.RootBank.First();
                presetParser.Logger.Clear();
                presetParser.Logger.MirrorTo(localLogger);

                var testResult = new PluginTestResult
                {
                    VendorPresetParser = presetParser.PresetParserType,
                    PluginId           = plugin.VstPluginId
                };

                double timeForNumPresets = 0;
                double timeForDoScan     = 0;
                double totalTime         = 0;
                try
                {
                    presetParser.Init();
                    testResult.ReportedPresets = presetParser.GetNumPresets();
                    timeForNumPresets          = (DateTime.Now - start).TotalSeconds;
                    start = DateTime.Now;
                    presetParser.DoScan().GetAwaiter().GetResult();
                    timeForDoScan = (DateTime.Now - start).TotalSeconds;
                    totalTime     = timeForNumPresets + timeForDoScan;
                }
                catch (Exception e)
                {
                    testResult.Error = "Errored";
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                }

                testResult.Presets = plugin.Presets.Count;

                var timePerPreset = (totalTime / testResult.Presets) * 1000;
                // ReSharper disable once LocalizableElement
                Console.WriteLine(
                    $"{testResult.Presets} parsed in {totalTime:F3}s (avg {timePerPreset:F3}ms / Preset, DoScan {timeForDoScan:F3}s, NumPresets {timeForNumPresets:F3}s");

                var testDataEntries    = GetTestDataEntries(testData, presetParser.PresetParserType, pluginId);
                var hasTestDataEntries = testDataEntries.Count > 0;
                var testDataOk         = true;
                foreach (var preset in plugin.Presets)
                {
                    if (preset.Metadata.BankPath == "")
                    {
                        testResult.BankMissing++;
                    }

                    foreach (var testDataEntry in testDataEntries.ToList())
                    {
                        if (preset.Metadata.PresetName == testDataEntry.ProgramName &&
                            preset.Metadata.BankPath == testDataEntry.BankPath)
                        {
                            var testFilename = PathUtils.SanitizeFilename(
                                testDataEntry.PresetParser + "." + preset.OriginalMetadata.PresetName +
                                ".testdata");
                            var myDocumentsTestDataFile = Path.Combine(GetPatchFilesDirectory(), testFilename);
                            var localTestDataFile       = Path.Combine("TestData", testFilename);


                            var presetHash = testDataEntry.Hash.TrimEnd();
                            if (preset.PresetHash != presetHash)
                            {
                                var fileMessage     = "";
                                var wrongPresetData = myDocumentsTestDataFile + ".wrong";
                                testDataOk = false;

                                if (File.Exists(myDocumentsTestDataFile))
                                {
                                    fileMessage = $"Original preset data in {myDocumentsTestDataFile}" +
                                                  Environment.NewLine +
                                                  $"Current (wrong) preset data in {wrongPresetData}";
                                }
                                else
                                {
                                    fileMessage =
                                        $"Original preset data not found (expected in {myDocumentsTestDataFile})" +
                                        Environment.NewLine +
                                        $"Current (wrong) preset data in {wrongPresetData}";
                                }

                                File.WriteAllBytes(wrongPresetData, LZ4Pickler.Unpickle(
                                                       NullPresetPersistence.PresetData[preset.OriginalMetadata.SourceFile]));
                                testResult.DetailedErrors.Add(
                                    $"Found preset {testDataEntry.ProgramName} with bank path " +
                                    $"{testDataEntry.BankPath} but the preset hashes were different. " +
                                    $"Expected hash {presetHash} but found hash {preset.PresetHash}" +
                                    Environment.NewLine + Environment.NewLine + $"{fileMessage}");
                            }
                            else
                            {
                                // Check if the file exists in the output directory
                                if (!File.Exists(myDocumentsTestDataFile))
                                {
                                    if (File.Exists(localTestDataFile))
                                    {
                                        File.Copy(localTestDataFile, myDocumentsTestDataFile);
                                    }
                                    else
                                    {
                                        File.WriteAllBytes(myDocumentsTestDataFile,
                                                           LZ4Pickler.Unpickle(
                                                               NullPresetPersistence.PresetData[preset.OriginalMetadata.SourceFile]));
                                    }
                                }
                                else
                                {
                                    if (!File.Exists(localTestDataFile))
                                    {
                                        testResult.DetailedErrors.Add(
                                            $"Warning: The preset data file {testFilename} exists in the documents " +
                                            "folder but not in the source folder. Copy from documents to git folder. " +
                                            "If already done, remember to clean the presetparsertest project.");
                                    }
                                }

                                var hash = HashUtils.getIxxHash(File.ReadAllBytes(myDocumentsTestDataFile));

                                if (hash != presetHash)
                                {
                                    testResult.DetailedErrors.Add(
                                        $"Warning: The preset data file {myDocumentsTestDataFile} exists but does not match the " +
                                        $"preset hash from the reference presets. Expected: {testDataEntry.Hash} found {hash}");
                                }
                            }

                            testDataEntries.Remove(testDataEntry);
                        }
                    }
                }

                if (testDataEntries.Count > 0)
                {
                    foreach (var missingTestDataEntry in testDataEntries)
                    {
                        var presetHash = missingTestDataEntry.Hash.TrimEnd();
                        testResult.DetailedErrors.Add(
                            $"Did not find preset {missingTestDataEntry.ProgramName} with bank path " +
                            $"{missingTestDataEntry.BankPath} and hash {presetHash}");
                    }

                    testResult.IsOK = false;
                }

                if (plugin.Presets.Count > 0)
                {
                    var randomPreset = plugin.Presets.OrderBy(qu => Guid.NewGuid()).First();
                    testResult.RndHash       = randomPreset.PresetHash;
                    testResult.RndPresetName = randomPreset.Metadata.PresetName;
                    testResult.RndBankPath   = randomPreset.Metadata.BankPath;
                }

                var mockFxp = Path.Combine(Directory.GetCurrentDirectory(), "mock.fxp");
                var fxp     = new FXP();
                fxp.ReadFile(Path.Combine(Directory.GetCurrentDirectory(), "test.fxp"));
                fxp.FxID = VstUtils.PluginIdNumberToIdString(pluginId);
                fxp.WriteFile(mockFxp);
                // Test additional banks
                var bankFile = new BankFile();
                bankFile.Path     = mockFxp;
                bankFile.BankName = "Default";

                plugin.AdditionalBankFiles.Clear();
                plugin.AdditionalBankFiles.Add(bankFile);

                bool additionalBankFileCountOk = false;


                if (presetParser.GetNumPresets() == testResult.ReportedPresets + 1)
                {
                    additionalBankFileCountOk = true;
                }
                else
                {
                    testResult.Error += " additionalBankFileCount failed";
                }

                plugin.Presets.Clear();
                NullPresetPersistence.PresetData.Clear();
                presetParser.DoScan().GetAwaiter().GetResult();

                var additionalBankFileScanOk = false;

                if (plugin.Presets.Count == testResult.Presets + 1)
                {
                    additionalBankFileScanOk = true;
                }
                else
                {
                    testResult.Error += " additionalBankFileScan failed";
                }

                bool bankMissingOk = false;
                if (NumBankMissingsOk.ContainsKey(testResult.PluginId))
                {
                    if (testResult.BankMissing <= NumBankMissingsOk[testResult.PluginId])
                    {
                        bankMissingOk = true;
                    }
                }
                else
                {
                    if (testResult.BankMissing < 2)
                    {
                        bankMissingOk = true;
                    }
                }

                if (hasTestDataEntries && testDataOk && testResult.Presets > 5 && bankMissingOk &&
                    testResult.Presets == testResult.ReportedPresets && additionalBankFileCountOk &&
                    additionalBankFileScanOk)
                {
                    testResult.IsOK = true;
                }

                testResults.Add(testResult);

                NullPresetPersistence.PresetData.Clear();
            }


            var consoleTable = ConsoleTable.From(from testRes in testResults
                                                 where testRes.IsOK == false
                                                 orderby testRes.Presets
                                                 select testRes);

            Console.WriteLine(consoleTable.ToMinimalString());

            foreach (var testRes in (from testRes in testResults
                                     where testRes.DetailedErrors.Count > 0
                                     orderby testRes.Presets
                                     select testRes))
            {
                Console.WriteLine(Environment.NewLine);
                Console.WriteLine($"Detailed Errors for {testRes.VendorPresetParser}");
                Console.WriteLine($"------------------------------------------------------------");

                foreach (var detailedError in testRes.DetailedErrors)
                {
                    Console.WriteLine($"Error #{testRes.DetailedErrors.IndexOf(detailedError)}: {detailedError}");
                }
            }

            Console.WriteLine($"Stuff left: {consoleTable.Rows.Count} / {presetParserDictionary.Count}");

            foreach (var data in GlobalMethodTimeLogger.GetTopMethods())
            {
                Console.WriteLine($"{data.Name}: {data.Duration.TotalSeconds.ToString()}ms");
            }

            if (hasIgnored)
            {
                Console.WriteLine("Warning: Filter active!!");
                Console.WriteLine("Warning: Filter active!!");
                Console.WriteLine("Warning: Filter active!!");
                Console.WriteLine("Warning: Filter active!!");
                Console.WriteLine("Warning: Filter active!!");
                Console.WriteLine("Warning: Filter active!!");
                Console.WriteLine("Warning: Filter active!!");
            }
        }
Exemplo n.º 22
0
        public async Task Move_CriteriaDetails_From_Dev_To_Prod_Test()
        {
            //Find records in development database server.

            Func <string, string, Task <IEnumerable <CriteriaSets> > > FindCriteriaSets = async(criteriaSetTerm, connString) =>
            {
                using (var smartAgentDb = new SqlConnection(ConfigurationManager.ConnectionStrings[connString].ConnectionString))
                {
                    var kernel = new StandardKernel(new RepoTestsModule(smartAgentDb));
                    var repo   = kernel.Get <ISmartAgentRepository>();
                    return(await repo.FindCriteriaSetRecords(criteriaSetTerm));
                }
            };


            Func <string, IEnumerable <CriteriaSets>, Task <IEnumerable <CriteriaDetails> > > FindCriteriaDetails = async(conn, records) =>
            {
                using (var smartAgentDb = new SqlConnection(ConfigurationManager.ConnectionStrings[conn].ConnectionString))
                {
                    var kernel = new StandardKernel(new RepoTestsModule(smartAgentDb));
                    var repo   = kernel.Get <ISmartAgentRepository>();
                    return(await repo.FindWithCriteriaSetKeys(records.Select(element => element.CriteriaSetKey)));
                }
            };

            Func <string, IEnumerable <CriteriaDetails>, Task <IEnumerable <CriteriaDetails> > > AddCriteriaDetails = async(conn, records) =>
            {
                using (var prodDb = new SqlConnection(ConfigurationManager.ConnectionStrings[conn].ConnectionString))
                {
                    var kernel = new StandardKernel(new RepoTestsModule(prodDb));
                    var repo   = kernel.Get <ISmartAgentRepository>();
                    await repo.AddCriteriaDetails(records);

                    return(await repo.FindWithCriteriaSetKeys(records.Select(element => element.CriteriaSetKey)));
                }
            };

            Func <string, IEnumerable <CriteriaSets>, string, Task <IEnumerable <CriteriaSets> > > AddCrtiera = async(conn, records, criteriaSetName) =>
            {
                using (var prodDb = new SqlConnection(ConfigurationManager.ConnectionStrings[conn].ConnectionString))
                {
                    var kernel = new StandardKernel(new RepoTestsModule(prodDb));
                    var repo   = kernel.Get <ISmartAgentRepository>();
                    await repo.AddCriterias(records);

                    return(await repo.FindCriteriaSetRecords(criteriaSetName));
                }
            };

            var criteriaName = "Pomerado Palomar Hospital – Outpatient Pavilion:";

            var devCriteriaSets = await FindCriteriaSets(criteriaName,
                                                         _devAppConfigName);

            if (devCriteriaSets.Any())
            {
                var prodCriteriaRecords = await AddCrtiera(_prodAppConfigName, devCriteriaSets, criteriaName);

                // Find dev criteria detials records
                var criteriaDetialsDev = await FindCriteriaDetails(_devAppConfigName, devCriteriaSets);

                //Move record to production
                //Might want to return the clientkey to prove the successful add.

                var prodClient = await AddCriteriaDetails(_prodAppConfigName, criteriaDetialsDev);

                if (prodClient.Any())
                {
                    ConsoleTable.From <CriteriaDetails>(prodClient).Write();
                }
                else
                {
                    Console.WriteLine("No records added");
                }
            }
        }
Exemplo n.º 23
0
        internal static void DeleteItem()
        {
            // Delete ana actor

            Console.WriteLine("Delete an Actor");

            Console.WriteLine("Enter an Actor ID");
            var actorId = Console.ReadLine().ToInt();

            var actor = MoviesContext.Instance.Actors
                        .SingleOrDefault(a => a.ActorId == actorId);

            if (actor == null)
            {
                Console.WriteLine($"Actor with id {actorId} not found");
            }

            else
            {
                Console.WriteLine("Existing Actors");
                WriteActors();

                MoviesContext.Instance.Actors.Remove(actor);

                MoviesContext.Instance.SaveChanges();

                Console.WriteLine("With actor removed");
                WriteActors();
            }

            // delete a film

            Console.WriteLine("Delete a Film");

            Console.WriteLine("Enter Film Title search");
            var title = Console.ReadLine();

            var film = MoviesContext.Instance.Films
                       .FirstOrDefault(f => f.Title.Contains(title));

            if (film == null)
            {
                Console.WriteLine($"Film with title that contains '{title}' not found");
            }

            else
            {
                ConsoleTable.From(new[] { film.Copy <Film, FilmModel>() }).Write();
                Console.WriteLine("Are you sure you want to delete this film?");
                if (Console.ReadKey().Key == ConsoleKey.Y)
                {
                    MoviesContext.Instance.Films.Remove(film);

                    MoviesContext.Instance.SaveChanges();

                    WriteFilms();
                }
                else
                {
                    Console.WriteLine(" No Films deleted");
                }
            }
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            var                conn = ConfigurationManager.AppSettings["DBConnectionString"].ToString();
            string             sourceDirectory;
            List <returnModel> returnCollection = new List <returnModel>();
            string             fileName         = "";
            int                counterFile      = 1;
            int                counterLine;
            int                counterFileValidate = 1;

            #region Fancy header

            /*
             * Console.Write(FiggleFonts.Ogre.Render("------------"));
             * List<char> chars = new List<char>()
             * {
             *  ' ', 'C', 'r', 'e', 'a', 't', 'e', 'd', ' ',
             *  'b', 'y', ' ',
             *  'P', 'i', 'r', 'i', 'y', 'a', 'V', ' '
             * };
             * Console.Write("---------------", Color.LawnGreen);
             * Console.WriteWithGradient(chars, Color.Blue, Color.Purple, 16);
             * Console.Write("---------------", Color.LawnGreen);
             * Console.WriteLine("\n");
             */
            #endregion

            // Ask the user to type path
            if (args.Length == 0)
            {
                // Display title
                Console.Title = "ExcelToDB 1.0.1";

                // Display header
                Console.WriteWithGradient(FiggleFonts.Banner.Render("excel to db"), Color.LightGreen, Color.ForestGreen, 16);
                Console.ReplaceAllColorsWithDefaults();

                // Display copyright
                Console.WriteLine(" ---------------------- Created by PiriyaV -----------------------\n", Color.LawnGreen);

                Console.Write(@"Enter source path (eg: D:\folder) : ", Color.LightYellow);
                sourceDirectory = Convert.ToString(Console.ReadLine());
                Console.Write("\n");
            }
            else
            {
                sourceDirectory = Convert.ToString(args[0]);
            }

            // Variable for backup
            string folderBackup     = "imported_" + DateTime.Now.ToString("ddMMyyyy_HHmmss");
            string folderBackupPath = Path.Combine(sourceDirectory, folderBackup);

            // Initial values
            int    LineNum;
            int    ColumnNum;
            string sheetName        = "Sheet1";
            string TableName        = "[SAPMM-WM]";
            int    i                = 0;
            int    ColumnNumChecker = 53;
            bool   sheetChecker     = true;

            try
            {
                // Full path for txt
                var FilePath = Directory.EnumerateFiles(sourceDirectory, "*.*", SearchOption.TopDirectoryOnly).Where(s => s.ToLower().EndsWith(".xls") || s.ToLower().EndsWith(".xlsx"));

                // Count txt file
                DirectoryInfo di          = new DirectoryInfo(sourceDirectory);
                int           FileNumXls  = di.GetFiles("*.xls").Length;
                int           FileNumXlsx = di.GetFiles("*.xlsx").Length;
                int           FileNum     = FileNumXls + FileNumXlsx;

                // Throw no txt file
                if (FileNum == 0)
                {
                    throw new ArgumentException("Excel file not found in folder.");
                }

                #region Validate Section
                var pbValidate = new ProgressBar(PbStyle.DoubleLine, FileNum);

                foreach (string currentFile in FilePath)
                {
                    sheetChecker = true;

                    // Update progress bar (Overall)
                    fileName = Path.GetFileName(currentFile);
                    pbValidate.Refresh(counterFileValidate, "Validating, Please wait...");
                    Thread.Sleep(50);

                    System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

                    using (var stream = File.Open(currentFile, FileMode.Open, FileAccess.Read))
                    {
                        // ExcelDataReader Config
                        var conf = new ExcelDataSetConfiguration()
                        {
                            ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                            {
                                UseHeaderRow = true
                            }
                        };

                        using (var reader = ExcelReaderFactory.CreateReader(stream))
                        {
                            // Validation Excel file
                            do
                            {
                                if (reader.Name == sheetName)
                                {
                                    sheetChecker = false;
                                    while (reader.Read())
                                    {
                                        if (i > 0)
                                        {
                                            int rowNO = i + 1;

                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 1, 10, "B", "Material Type");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 2, 255, "C", "Material Type Description");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 3, 10, "D", "Material Group");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 4, 255, "E", "Matl Grp Desc#");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 5, 12, "F", "Material");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 6, 255, "G", "Description");
                                            ValidateDate(reader, pbValidate, rowNO, counterFileValidate, 7, "H", "Posting Date");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 8, 255, "I", "ได้รับมาจาก");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 9, 255, "J", "จ่ายไปให้");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 10, 10, "K", "Movement type");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 11, 255, "L", "Mvt Type Text");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 12, 100, "M", "Batch");
                                            ValidateDate(reader, pbValidate, rowNO, counterFileValidate, 13, "N", "MFG Date");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 14, 100, "O", "Manufacturer Batch");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 15, 100, "P", "Manufacturer");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 16, 255, "Q", "Manufacturer Name");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 17, 100, "R", "Vendor");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 18, 255, "S", "Vendor Name");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 19, 20, "T", "Sold-to");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 20, 255, "U", "Sold-to Name");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 21, 255, "V", "Sold-to Address");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 22, 100, "W", "Sold-to Province");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 23, 20, "X", "Ship-to");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 24, 255, "Y", "Ship-to Name");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 25, 255, "Z", "Ship-to Address");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 26, 100, "AA", "Ship-to Province");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 27, 5, "AB", "Customer Group 1");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 28, 100, "AC", "Customer Group 1 - Desc#");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 29, 5, "AD", "Customer Group 2");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 30, 100, "AE", "Customer Group 2 - Desc#");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 31, 5, "AF", "Customer Group 3");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 32, 100, "AG", "Customer Group 3 - Desc#");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 33, 20, "AH", "FG material");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 34, 255, "AI", "FG Material Description");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 35, 100, "AJ", "FG Batch");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 36, 5, "AK", "Cost Center");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 37, 255, "AL", "Cost Center Description");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 38, 10, "AM", "Plant");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 39, 10, "AN", "Storage Loc#");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 40, 10, "AO", "Dest# Plant");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 41, 10, "AP", "Dest# Sloc");
                                            ValidateFloat(reader, pbValidate, rowNO, counterFileValidate, 42, "AQ", "ยอดยกมา");
                                            ValidateFloat(reader, pbValidate, rowNO, counterFileValidate, 43, "AR", "ปริมาณรับ");
                                            ValidateFloat(reader, pbValidate, rowNO, counterFileValidate, 44, "AS", "ปริมาณจ่าย");
                                            ValidateFloat(reader, pbValidate, rowNO, counterFileValidate, 45, "AT", "ปริมาณคงเหลือ");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 46, 20, "AU", "Unit");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 47, 255, "AV", "หมายเหตุ");
                                            ValidateDate(reader, pbValidate, rowNO, counterFileValidate, 48, "AW", "Entered on");
                                            ValidateDate(reader, pbValidate, rowNO, counterFileValidate, 49, "AX", "Entered at");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 50, 20, "AY", "Material Doc#");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 51, 10, "BZ", "Mat# Doc# Year");
                                            ValidateString(reader, pbValidate, rowNO, counterFileValidate, 52, 5, "BA", "Mat# Doc#Item");
                                        }
                                    }
                                }
                            } while (reader.NextResult());
                        }
                    }

                    // Change wording in progress bar
                    if (counterFileValidate == FileNum)
                    {
                        pbValidate.Refresh(counterFileValidate, "Validate finished.");
                    }

                    // Return error if excel file don't have specific sheet name
                    if (sheetChecker)
                    {
                        pbValidate.Refresh(counterFileValidate, "Validate failed.");
                        throw new ArgumentException($"Excel must have sheet name \" {sheetName} \"");
                    }

                    counterFileValidate++;
                }
                #endregion

                #region Import Section
                // Create progress bar (Overall)
                var pbOverall = new ProgressBar(PbStyle.DoubleLine, FileNum);

                foreach (string currentFile in FilePath)
                {
                    // Initial variable
                    LineNum     = 0;
                    ColumnNum   = 0;
                    counterLine = 1;

                    returnModel Model = new returnModel();

                    fileName = Path.GetFileName(currentFile);

                    // Update progress bar (Overall)
                    pbOverall.Refresh(counterFile, "Importing, Please wait...");
                    Thread.Sleep(50);

                    using (var stream = File.Open(currentFile, FileMode.Open, FileAccess.Read))
                    {
                        // ExcelDataReader Config
                        var conf = new ExcelDataSetConfiguration()
                        {
                            ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                            {
                                UseHeaderRow = true
                            }
                        };

                        using (var reader = ExcelReaderFactory.CreateReader(stream))
                        {
                            // Validation Excel file
                            do
                            {
                                if (reader.Name == sheetName)
                                {
                                    // Read as DataSet
                                    var result = reader.AsDataSet(conf);

                                    // Convert to Datatable
                                    DataTable dt = result.Tables[sheetName];

                                    // Row count
                                    LineNum = dt.Rows.Count;

                                    // Column count
                                    ColumnNum = dt.Columns.Count;

                                    // Validate excel column
                                    if (ColumnNum != ColumnNumChecker)
                                    {
                                        pbOverall.Refresh(counterFile, "Import error occured");
                                        throw new ArgumentException($"Excel file must have {ColumnNumChecker} column!");
                                    }

                                    // Sanitize data
                                    foreach (DataColumn c in dt.Columns)
                                    {
                                        if (c.DataType == typeof(string))
                                        {
                                            foreach (DataRow r in dt.Rows)
                                            {
                                                r[c.ColumnName] = r[c.ColumnName].ToString().Trim();

                                                // Convert empty string into NULL
                                                if (r[c.ColumnName].ToString().Length == 0)
                                                {
                                                    r[c.ColumnName] = DBNull.Value;
                                                }
                                            }
                                        }
                                    }

                                    using (SqlBulkCopy bc = new SqlBulkCopy(conn, SqlBulkCopyOptions.UseInternalTransaction | SqlBulkCopyOptions.TableLock))
                                    {
                                        bc.DestinationTableName = TableName;
                                        bc.BatchSize            = reader.RowCount;
                                        bc.ColumnMappings.Add(1, "[Material Type]");
                                        bc.ColumnMappings.Add(2, "[Material Type Description]");
                                        bc.ColumnMappings.Add(3, "[Material Group]");
                                        bc.ColumnMappings.Add(4, "[Matl Grp Desc#]");
                                        bc.ColumnMappings.Add(5, "[Material]");
                                        bc.ColumnMappings.Add(6, "[Description]");
                                        bc.ColumnMappings.Add(7, "[Posting Date]");
                                        bc.ColumnMappings.Add(8, "[ได้รับมาจาก]");
                                        bc.ColumnMappings.Add(9, "[จ่ายไปให้]");
                                        bc.ColumnMappings.Add(10, "[Movement type]");
                                        bc.ColumnMappings.Add(11, "[Mvt Type Text]");
                                        bc.ColumnMappings.Add(12, "[Batch]");
                                        bc.ColumnMappings.Add(13, "[MFG Date]");
                                        bc.ColumnMappings.Add(14, "[Manufacturer Batch]");
                                        bc.ColumnMappings.Add(15, "[Manufacturer]");
                                        bc.ColumnMappings.Add(16, "[Manufacturer Name]");
                                        bc.ColumnMappings.Add(17, "[Vendor]");
                                        bc.ColumnMappings.Add(18, "[Vendor Name]");
                                        bc.ColumnMappings.Add(19, "[Sold-to]");
                                        bc.ColumnMappings.Add(20, "[Sold-to Name]");
                                        bc.ColumnMappings.Add(21, "[Sold-to Address]");
                                        bc.ColumnMappings.Add(22, "[Sold-to Province]");
                                        bc.ColumnMappings.Add(23, "[Ship-to]");
                                        bc.ColumnMappings.Add(24, "[Ship-to Name]");
                                        bc.ColumnMappings.Add(25, "[Ship-to Address]");
                                        bc.ColumnMappings.Add(26, "[Ship-to Province]");
                                        bc.ColumnMappings.Add(27, "[Customer Group 1]");
                                        bc.ColumnMappings.Add(28, "[Customer Group 1 - Desc#]");
                                        bc.ColumnMappings.Add(29, "[Customer Group 2]");
                                        bc.ColumnMappings.Add(30, "[Customer Group 2 - Desc#]");
                                        bc.ColumnMappings.Add(31, "[Customer Group 3]");
                                        bc.ColumnMappings.Add(32, "[Customer Group 3 - Desc#]");
                                        bc.ColumnMappings.Add(33, "[FG material]");
                                        bc.ColumnMappings.Add(34, "[FG Material Description]");
                                        bc.ColumnMappings.Add(35, "[FG Batch]");
                                        bc.ColumnMappings.Add(36, "[Cost Center]");
                                        bc.ColumnMappings.Add(37, "[Cost Center Description]");
                                        bc.ColumnMappings.Add(38, "[Plant]");
                                        bc.ColumnMappings.Add(39, "[Storage Loc#]");
                                        bc.ColumnMappings.Add(40, "[Dest# Plant]");
                                        bc.ColumnMappings.Add(41, "[Dest# Sloc]");
                                        bc.ColumnMappings.Add(42, "[ยอดยกมา]");
                                        bc.ColumnMappings.Add(43, "[ปริมาณรับ]");
                                        bc.ColumnMappings.Add(44, "[ปริมาณจ่าย]");
                                        bc.ColumnMappings.Add(45, "[ปริมาณคงเหลือ]");
                                        bc.ColumnMappings.Add(46, "[Unit]");
                                        bc.ColumnMappings.Add(47, "[หมายเหตุ]");
                                        bc.ColumnMappings.Add(48, "[Entered on]");
                                        bc.ColumnMappings.Add(49, "[Entered at]");
                                        bc.ColumnMappings.Add(50, "[Material Doc#]");
                                        bc.ColumnMappings.Add(51, "[Mat# Doc# Year]");
                                        bc.ColumnMappings.Add(52, "[Mat# Doc#Item]");
                                        bc.WriteToServer(dt);
                                    }
                                }
                            } while (reader.NextResult());
                            counterLine++;
                        }

                        // Create folder for file import successful
                        if (!Directory.Exists(folderBackupPath))
                        {
                            Directory.CreateDirectory(folderBackupPath);
                        }

                        // Move file to folder backup
                        string destFile = Path.Combine(folderBackupPath, fileName);
                        File.Move(currentFile, destFile);

                        // Add detail to model for showing in table
                        Model.RowNo    = LineNum;
                        Model.FileName = fileName;
                        returnCollection.Add(Model);

                        // Change wording in progress bar
                        if (counterFile == FileNum)
                        {
                            pbOverall.Refresh(counterFile, "Import finished.");
                        }

                        counterFile++;
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                //pbOverall.Refresh(counterFile, "Import failed");

                // Show error message
                Console.Write("\nError occured : ", Color.OrangeRed);
                Console.WriteLine(ex.Message);
                //Console.WriteLine("Error trace : " + ex.StackTrace);

                // Show error on
                if (!String.IsNullOrEmpty(fileName))
                {
                    Console.Write("\nError on : ", Color.OrangeRed);
                    Console.WriteLine("'" + fileName + "'");
                }

                // Show description
                Console.WriteLine("\nPlease check your path or file and try again.\n", Color.Yellow);
            }
            finally
            {
                // Show table
                if (returnCollection.Count > 0)
                {
                    Console.WriteLine("\n--------------- Imported detail ---------------", Color.LightGreen);
                    ConsoleTable.From(returnCollection).Write();
                }
                //Console.WriteLine(JsonSerializer.Serialize(returnCollection));

                // Show backup folder path
                if (Directory.Exists(folderBackupPath))
                {
                    Console.Write("\nImported folder : ", Color.LightGreen);
                    Console.WriteLine($"'{ folderBackupPath }'");
                }
            }

            // Wait key to terminate
            Console.Write("\nPress any key to close this window ");
            Console.ReadKey();
        }
Exemplo n.º 25
0
        private static void WriteFilms()
        {
            var films = MoviesContext.Instance.Films.Select(film => film.Copy <Film, FilmModel>());

            ConsoleTable.From(films).Write();
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            var students = new List <Student>()
            {
                new Student(1, "Student B", new DateTime(1997, 7, 21), 8, 1),
                new Student(2, "Student A", new DateTime(1997, 4, 1), 10, 1),
                new Student(3, "Student C", new DateTime(1996, 7, 1), 1, 1),
                new Student(4, "Student E", new DateTime(1995, 3, 5), 9, 1),
                new Student(5, "Student D", new DateTime(1997, 7, 2), 6, 1),
                new Student(6, "Student H", new DateTime(1997, 11, 21), 7, 2),
                new Student(7, "Student F", new DateTime(1984, 5, 12), 3, 2),
                new Student(8, "Student I", new DateTime(1997, 3, 2), 8, 2),
                new Student(9, "Student J", new DateTime(1997, 2, 3), 3.5, 2),
                new Student(10, "Student L", new DateTime(1997, 6, 21), 7.5, 2),
                new Student(11, "Student K", new DateTime(1997, 2, 14), 9.5, 2),
                new Student(12, "Student N", new DateTime(1997, 9, 6), 10, 3),
                new Student(13, "Student G", new DateTime(1997, 10, 21), 5, 3),
                new Student(14, "Student O", new DateTime(1997, 7, 8), 4, 3),
                new Student(15, "Student M", new DateTime(1997, 8, 9), 10, 3)
            };
            var classes = new List <Class>()
            {
                new Class(1, "Class 1"),
                new Class(2, "Class 2"),
                new Class(3, "Class 3")
            };

            ConsoleTable.From(students.OrderBy(x => x.ClassId).ThenBy(x => x.Name)).Write();

            var classesWithSudentCount = from c in classes
                                         join s in students
                                         on c.Id equals s.ClassId
                                         into selectedClasses
                                         select new
            {
                c.Id,
                c.Name,
                StudentCount = selectedClasses.Count()
            };

            ConsoleTable.From(classesWithSudentCount).Write();

            var classesWithStudentHighestScore = from c in classes
                                                 join s in students
                                                 on c.Id equals s.ClassId
                                                 into selectedClasses
                                                 select new
            {
                c.Id,
                c.Name,
                HighestScore = selectedClasses.Max(student => student.Score)
            };

            ConsoleTable.From(classesWithStudentHighestScore).Write();

            var classesWithAverageScore = from c in classes
                                          join s in students
                                          on c.Id equals s.ClassId
                                          into selectedClasses
                                          select new
            {
                c.Id,
                c.Name,
                AverageScore = selectedClasses.Average(s => s.Score)
            };

            ConsoleTable.From(classesWithAverageScore).Write();

            var tenSudentsHaveHighestScore = (from s in students
                                              orderby s.Score descending
                                              select new
            {
                s.Id,
                s.Name,
                s.Score,
                s.BirthDay,
                s.ClassId
            }).Take(10);

            ConsoleTable.From(tenSudentsHaveHighestScore).Write();

            var topThreeStudentsOfEachClass = (from c in classes
                                               select new
            {
                c.Name,
                Rank = (from s in students
                        orderby s.Score descending
                        join currentClass in classes
                        on s.ClassId equals currentClass.Id
                        where s.Score >= 8
                        where c.Id == currentClass.Id
                        select s).Take(3)
            });

            foreach (var item in topThreeStudentsOfEachClass)
            {
                Console.WriteLine(item.Name);
                ConsoleTable.From(item.Rank).Write();
            }

            var tenStudentsSelectedRandomly = students.OrderBy(x => Guid.NewGuid()).Take(10);

            ConsoleTable.From(tenStudentsSelectedRandomly).Write();

            Console.ReadKey();
        }
Exemplo n.º 27
0
 private void ProduitEnLocal()
 {
     ConsoleTable.From(Northwind2App.DataContexte.GETProduitLocal(), "nbr").Display("Nombre de produit en local");
 }
        private static void AnalyzeData()
        {
            using (IUnitOfWork unitOfWork = new UnitOfWork())
            {
                var teamWithMostGoals = unitOfWork.Teams.GetTeamWithMostGoals();
                PrintResult("Team mit den meisten geschossenen Toren:", $"{teamWithMostGoals.Team.Name}: {teamWithMostGoals.Goals} Tore");

                var teamWithMostAwayGoals = unitOfWork.Teams.GetTeamWithMostAwayGoals();
                PrintResult("Team mit den meisten geschossenen Auswärtstoren:", $"{teamWithMostAwayGoals.Team.Name}: {teamWithMostAwayGoals.Goals} Tore");

                var teamWithMostHomeGoals = unitOfWork.Teams.GetTeamWithMostHomeGoals();
                PrintResult("Team mit den meisten geschossenen Heimtoren:", $"{teamWithMostHomeGoals.Team.Name}: {teamWithMostHomeGoals.Goals} Tore");

                var teamWithBestGoalDifference = unitOfWork.Teams.GetTeamWithBestGoalDifference();
                PrintResult("Team mit dem besten Torverhältnis:", $"{teamWithBestGoalDifference.Team.Name}: {teamWithBestGoalDifference.GoalDifference} Tore");

                var teamStatistics = unitOfWork.Teams.GetTeamStatistics();
                PrintResult("Team Leistung im Durchschnitt (sotiert nach durchsn. geschossene Tore pro Spiel [absteig.]):", ConsoleTable
                            .From(teamStatistics)
                            .Configure(c => c.NumberAlignment = Alignment.Right)
                            .ToStringAlternative());

                var teamStandings = unitOfWork.Teams.GetTeamStandings();
                PrintResult("Team Tabelle (sortiert nach Rang):", ConsoleTable
                            .From(teamStandings)
                            .Configure(c => c.NumberAlignment = Alignment.Right)
                            .ToStringAlternative());
            }
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            // mongod --dbpath d:\KhanhHC2\Programs\Workspace\mongodb
            DataAccess dataAccess = new DataAccess();
            bool       isExit     = false;

            while (!isExit)
            {
                try
                {
                    Console.WriteLine("");
                    Console.WriteLine("1. find");
                    Console.WriteLine("2. insert");
                    Console.WriteLine("3. update");
                    Console.WriteLine("4. delete");
                    Console.WriteLine("5. exit");
                    Console.Write("key: ");
                    string key = Console.ReadLine();
                    switch (key)
                    {
                    case "1":
                        Console.Write("name: ");
                        string findName = Console.ReadLine();
                        var    list     = dataAccess.GetProducts()
                                          .Where(p => p.Name.Contains(findName, StringComparison.CurrentCultureIgnoreCase));
                        ConsoleTable.From <Product>(list).Write();
                        break;

                    case "2":
                        Console.Write("name: ");
                        string insertName = Console.ReadLine();
                        Console.Write("price: ");
                        int insertPrice = int.Parse(Console.ReadLine());
                        Console.Write("description: ");
                        string insertDescription = Console.ReadLine();
                        dataAccess.Create(new Product
                        {
                            Name        = insertName,
                            Price       = insertPrice,
                            Description = insertDescription
                        });
                        ConsoleTable.From <Product>(dataAccess.GetProducts()).Write();
                        break;

                    case "3":
                        Console.Write("id: ");
                        string updateId  = Console.ReadLine();
                        var    updateObj = dataAccess.GetProduct(ObjectId.Parse(updateId));
                        ConsoleTable.From <Product>(new List <Product> {
                            updateObj
                        }).Write();
                        Console.Write("name: ");
                        string updateName = Console.ReadLine();
                        Console.Write("price: ");
                        string updatePrice = Console.ReadLine();
                        Console.Write("description: ");
                        string updateDescription = Console.ReadLine();
                        updateObj.Name        = updateName == "" ? updateObj.Name : updateName;
                        updateObj.Price       = updatePrice == "" ? updateObj.Price : int.Parse(updatePrice);
                        updateObj.Description = updateDescription == "" ? updateObj.Description : updateDescription;
                        dataAccess.Update(updateObj.Id, updateObj);
                        ConsoleTable.From <Product>(dataAccess.GetProducts()).Write();
                        break;

                    case "4":
                        Console.Write("id: ");
                        dataAccess.Remove(ObjectId.Parse(Console.ReadLine()));
                        ConsoleTable.From <Product>(dataAccess.GetProducts()).Write();
                        break;

                    case "5":
                        isExit = true;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            var                conn = ConfigurationManager.AppSettings["DBConnectionString"].ToString();
            string             sourceDirectory;
            string             line;
            int                detailLineNo, headerLineNo;
            List <ReturnModel> returnCollection = new List <ReturnModel>();
            string             FL_Filecode;
            string             FL_TotalRecord;
            string             HD_PoNo;
            string             fileName            = "";
            int                counterFile         = 1;
            int                counterFileValidate = 1;
            int                counterLine;

            #region Fancy header

            /*
             * Console.Write(FiggleFonts.Ogre.Render("------------"));
             * List<char> chars = new List<char>()
             * {
             *  ' ', 'C', 'r', 'e', 'a', 't', 'e', 'd', ' ',
             *  'b', 'y', ' ',
             *  'P', 'i', 'r', 'i', 'y', 'a', 'V', ' '
             * };
             * Console.Write("---------------", Color.LawnGreen);
             * Console.WriteWithGradient(chars, Color.Blue, Color.Purple, 16);
             * Console.Write("---------------", Color.LawnGreen);
             * Console.WriteLine("\n");
             */
            #endregion

            // Ask the user to type path
            if (args.Length == 0)
            {
                // Display title
                Console.Title = "TxtToDB 1.0.6";

                // Display header
                Console.WriteWithGradient(FiggleFonts.Banner.Render("txt to db"), Color.LightGreen, Color.ForestGreen, 16);
                Console.ReplaceAllColorsWithDefaults();

                // Display copyright
                Console.WriteLine(" --------------- Created by PiriyaV ----------------\n", Color.LawnGreen);

                Console.Write(@"Enter source path (eg: D:\folder) : ", Color.LightYellow);
                sourceDirectory = Convert.ToString(Console.ReadLine());
                Console.Write("\n");
            }
            else
            {
                sourceDirectory = Convert.ToString(args[0]);
            }

            // Variable for backup
            string folderBackup     = "imported_" + DateTime.Now.ToString("ddMMyyyy_HHmmss");
            string folderBackupPath = Path.Combine(sourceDirectory, folderBackup);

            try
            {
                // Full path for txt
                var FilePath = Directory.EnumerateFiles(sourceDirectory, "*.*", SearchOption.TopDirectoryOnly).Where(s => s.ToLower().EndsWith(".txt"));

                // Count txt file
                DirectoryInfo di      = new DirectoryInfo(sourceDirectory);
                int           FileNum = di.GetFiles("*.txt").Length;

                // Throw no txt file
                if (FileNum == 0)
                {
                    throw new ArgumentException("Text file not found in folder.");
                }

                #region Validate Section
                var pbValidate = new ProgressBar(PbStyle.DoubleLine, FileNum);

                foreach (string currentFile in FilePath)
                {
                    // Update progress bar (Overall)
                    fileName = Path.GetFileName(currentFile);
                    pbValidate.Refresh(counterFileValidate, "Validating, Please wait...");
                    Thread.Sleep(50);

                    int     Lineno        = 1;
                    string  ErrorMsg      = "";
                    Boolean IsHeaderValid = true;
                    Boolean IsColumnValid = true;

                    using (StreamReader file = new StreamReader(currentFile))
                    {
                        while ((line = file.ReadLine()) != null)
                        {
                            var parser = CreateParser(line, ",");

                            string   firstColumn = "";
                            int      ColumnNo    = 0;
                            string[] cells;
                            while (!parser.EndOfData)
                            {
                                cells       = parser.ReadFields();
                                firstColumn = cells[0];
                                ColumnNo    = cells.Length;

                                #region header
                                if (Lineno == 1 && firstColumn != "FL")
                                {
                                    IsHeaderValid = false;
                                    ErrorMsg      = "First line must contain FL column";
                                }
                                else if (Lineno == 2 && firstColumn != "HD")
                                {
                                    IsHeaderValid = false;
                                    ErrorMsg      = "Second line must contain HD column";
                                }
                                else if (Lineno >= 3 && firstColumn != "LN")
                                {
                                    IsHeaderValid = false;
                                    ErrorMsg      = $"Data must contain LN column (At line: { Lineno })";
                                }

                                if (!IsHeaderValid)
                                {
                                    pbValidate.Refresh(counterFileValidate, "Validate failed.");
                                    throw new ArgumentException(ErrorMsg);
                                }
                                #endregion

                                #region column length
                                switch (firstColumn)
                                {
                                case "FL":
                                    if (ColumnNo != 3)
                                    {
                                        IsColumnValid = false;
                                        ErrorMsg      = $"FL must have 3 columns ({ ColumnNo } columns found)";
                                    }
                                    break;

                                case "HD":
                                    if (ColumnNo != 27)
                                    {
                                        IsColumnValid = false;
                                        ErrorMsg      = $"HD must have 27 columns ({ ColumnNo } columns found)";
                                    }
                                    break;

                                case "LN":
                                    if (ColumnNo != 13)
                                    {
                                        IsColumnValid = false;
                                        ErrorMsg      = $"LN must have 13 columns (At line: { Lineno }, { ColumnNo } columns found)";
                                    }
                                    break;

                                default:
                                    IsColumnValid = false;
                                    ErrorMsg      = $"Incorrect format, File must contain 'FL, HD or LN' in the first column on each row! (At Line: { Lineno})";
                                    break;
                                    //continue;
                                }

                                if (!IsColumnValid)
                                {
                                    pbValidate.Refresh(counterFileValidate, "Validate failed.");
                                    throw new ArgumentException(ErrorMsg);
                                }
                                #endregion

                                #region data type
                                switch (firstColumn)
                                {
                                    #region data type FL
                                case "FL":
                                    ValidateLengthRange(cells[1], 1, 40, pbValidate, counterFileValidate, Lineno, "FILE_CODE", "2");
                                    ValidateInteger(cells[2], pbValidate, counterFileValidate, Lineno, "TOTAL_RECORDS", "3");
                                    break;

                                    #endregion
                                    #region data type HD
                                case "HD":
                                    ValidateLengthRange(cells[1], 1, 40, pbValidate, counterFileValidate, Lineno, "PO_NUMBER", "2");
                                    ValidateBit(cells[2], pbValidate, counterFile, Lineno, "PO_TYPE", "3");
                                    ValidateLengthRange(cells[3], 0, 40, pbValidate, counterFileValidate, Lineno, "CONTRACT_NUMBER", "4");
                                    ValidateDateTime(cells[4], pbValidate, counterFile, Lineno, "ORDERED_DATE", "5");
                                    ValidateDateTime(cells[5], pbValidate, counterFile, Lineno, "DELIVERY_DATE", "6");
                                    ValidateLengthRange(cells[6], 1, 40, pbValidate, counterFileValidate, Lineno, "HOSP_CODE", "7");
                                    ValidateLengthRange(cells[7], 1, 80, pbValidate, counterFileValidate, Lineno, "HOSP_NAME", "8");
                                    ValidateLengthRange(cells[8], 0, 100, pbValidate, counterFileValidate, Lineno, "BUYER_NAME", "9");
                                    ValidateLengthRange(cells[9], 0, 100, pbValidate, counterFileValidate, Lineno, "BUYER_DEPARTMENT", "10");
                                    ValidateLengthRange(cells[10], 1, 40, pbValidate, counterFileValidate, Lineno, "EMAIL", "11");
                                    ValidateLengthRange(cells[11], 1, 40, pbValidate, counterFileValidate, Lineno, "SUPPLIER_CODE", "12");
                                    ValidateLengthRange(cells[12], 1, 40, pbValidate, counterFileValidate, Lineno, "SHIP_TO_CODE", "13");
                                    ValidateLengthRange(cells[13], 1, 40, pbValidate, counterFileValidate, Lineno, "BILL_TO_CODE", "14");
                                    ValidateLengthRange(cells[14], 1, 20, pbValidate, counterFileValidate, Lineno, "Approval Code", "15");
                                    ValidateLengthRange(cells[15], 1, 20, pbValidate, counterFileValidate, Lineno, "Budget Code", "16");
                                    ValidateLengthRange(cells[16], 1, 420, pbValidate, counterFileValidate, Lineno, "CURRENCY_CODE", "17");
                                    ValidateLengthRange(cells[17], 1, 80, pbValidate, counterFileValidate, Lineno, "PAYMENT_TERM", "18");
                                    ValidateFloat(cells[18], pbValidate, counterFile, Lineno, "DISCOUNT_PCT", "19");
                                    ValidateFloat(cells[19], pbValidate, counterFile, Lineno, "TOTAL_AMOUNT", "20");
                                    ValidateLengthRange(cells[20], 0, 500, pbValidate, counterFileValidate, Lineno, "NOTE_TO_SUPPLIER", "21");
                                    ValidateLengthRange(cells[21], 0, 40, pbValidate, counterFileValidate, Lineno, "RESEND_FLAG", "22");
                                    ValidateDateTime(cells[22], pbValidate, counterFile, Lineno, "CREATION_DATE", "23");
                                    ValidateDateTime(cells[23], pbValidate, counterFile, Lineno, "LAST_INTERFACED_DATE", "24");
                                    ValidateLengthRange(cells[24], 1, 20, pbValidate, counterFileValidate, Lineno, "INTERFACE_ID", "25");
                                    ValidateLengthRange(cells[25], 0, 20, pbValidate, counterFileValidate, Lineno, "QUATATION_ID", "26");
                                    ValidateLengthRange(cells[26], 0, 20, pbValidate, counterFileValidate, Lineno, "CUSTOMER_ID", "27");
                                    break;

                                    #endregion
                                    #region data type LN
                                case "LN":
                                    ValidateInteger(cells[1], pbValidate, counterFile, Lineno, "LINE_NUMBER", "2");
                                    ValidateLengthRange(cells[2], 1, 40, pbValidate, counterFileValidate, Lineno, "HOSPITEM_CODE", "3");
                                    ValidateLengthRange(cells[3], 0, 4000, pbValidate, counterFileValidate, Lineno, "HOSPITEM_", "4");
                                    ValidateLengthRange(cells[4], 1, 40, pbValidate, counterFileValidate, Lineno, "DISTITEM_CODE", "5");
                                    ValidateLengthRange(cells[5], 0, 40, pbValidate, counterFileValidate, Lineno, "PACK_SIZE_DESC", "6");
                                    ValidateFloat(cells[6], pbValidate, counterFile, Lineno, "ORDERED_QTY", "7");
                                    ValidateLengthRange(cells[7], 1, 20, pbValidate, counterFileValidate, Lineno, "UOM", "8");
                                    ValidateFloat(cells[8], pbValidate, counterFile, Lineno, "PRICE_PER_UNIT", "9");
                                    ValidateFloat(cells[9], pbValidate, counterFile, Lineno, "LINE_AMOUNT", "10");
                                    ValidateFloat(cells[10], pbValidate, counterFile, Lineno, "DISCOUNT_LINE_ITEM", "11");
                                    ValidateLengthRange(cells[11], 1, 2, pbValidate, counterFileValidate, Lineno, "URGENT_FLAG", "12");
                                    ValidateLengthRange(cells[12], 0, 255, pbValidate, counterFileValidate, Lineno, "COMMENT", "13");
                                    break;
                                    #endregion
                                }
                                #endregion
                            }

                            Lineno++;
                        }
                    }

                    // Change wording in progress bar
                    if (counterFileValidate == FileNum)
                    {
                        pbValidate.Refresh(counterFileValidate, "Validate finished.");
                    }

                    counterFileValidate++;
                }
                #endregion

                #region Import Section
                // Create progress bar (Overall)
                var pbOverall = new ProgressBar(PbStyle.DoubleLine, FileNum);

                foreach (string currentFile in FilePath)
                {
                    // Initial variable
                    headerLineNo   = 0;
                    detailLineNo   = 0;
                    counterLine    = 1;
                    FL_Filecode    = "";
                    FL_TotalRecord = "";
                    HD_PoNo        = "";

                    ReturnModel Model = new ReturnModel();

                    fileName = Path.GetFileName(currentFile);

                    // Create progress bar (Each file)
                    int LineNum  = CountLinesReader(currentFile);
                    var pbDetail = new ProgressBar(PbStyle.SingleLine, LineNum);

                    // Update progress bar (Overall)
                    pbOverall.Refresh(counterFile, "Importing, Please wait...");
                    Thread.Sleep(50);

                    // Convert tis-620 to utf-8
                    byte[]     tis620Bytes = File.ReadAllBytes(currentFile);
                    FileStream fs          = File.OpenWrite(currentFile);
                    byte[]     b           = ThaiEncodingService.ToUTF8(tis620Bytes);
                    fs.Write(b, 0, b.Length);
                    fs.Close();

                    using (StreamReader file = new StreamReader(currentFile))
                    {
                        while ((line = file.ReadLine()) != null)
                        {
                            var parser            = CreateParser(line, ",");
                            var parserFirstcolumn = CreateParser(line, ",");
                            var parserFL          = CreateParser(line, ",");

                            // Store first column
                            string[] cells;
                            string   firstColumn = "";
                            while (!parserFirstcolumn.EndOfData)
                            {
                                cells       = parserFirstcolumn.ReadFields();
                                firstColumn = cells[0];
                            }
                            //string[] cells = line.Split(",");

                            // Update progress bar (Each file)
                            pbDetail.Refresh(counterLine, fileName);
                            Thread.Sleep(20);

                            // Determine what firstColumn is
                            switch (firstColumn)
                            {
                            case "FL":
                                // Store FL key for insert HD
                                while (!parserFL.EndOfData)
                                {
                                    cells          = parserFL.ReadFields();
                                    FL_Filecode    = cells[1];
                                    FL_TotalRecord = cells[2];
                                }
                                //Dump(parser);
                                break;

                            case "HD":
                                /*
                                 * // Throw if FL key not found
                                 * if (string.IsNullOrEmpty(FL_Filecode) || string.IsNullOrEmpty(FL_TotalRecord))
                                 * {
                                 *  throw new ArgumentException("FL key not found!");
                                 * }
                                 */

                                // Insert to DB
                                HD_PoNo = DumpHD(parser, conn, FL_Filecode, FL_TotalRecord, fileName);
                                headerLineNo++;
                                break;

                            case "LN":
                                /*
                                 * // Throw if HD key not found
                                 * if (string.IsNullOrEmpty(HD_PoNo))
                                 * {
                                 *  throw new ArgumentException("HD key not found!");
                                 * }
                                 */

                                // Insert to DB
                                DumpLN(parser, conn, HD_PoNo);
                                detailLineNo++;
                                break;

                            default:
                                //throw new ArgumentException("Incorrect format, File must contain 'FL, HD or LN' in the first column on each row!");
                                break;
                                //continue;
                            }

                            counterLine++;
                        }
                    }

                    // Create folder for file import successful
                    if (!Directory.Exists(folderBackupPath))
                    {
                        Directory.CreateDirectory(folderBackupPath);
                    }

                    // Move file to folder backup
                    string destFile = Path.Combine(folderBackupPath, fileName);
                    File.Move(currentFile, destFile);

                    // Add detail to model for showing in table
                    Model.HeaderNo = headerLineNo;
                    Model.DetailNo = detailLineNo;
                    Model.FileName = fileName;
                    returnCollection.Add(Model);

                    // Change wording in progress bar
                    if (counterFile == FileNum)
                    {
                        pbOverall.Refresh(counterFile, "Import finished.");
                    }

                    counterFile++;
                }
                #endregion
            }
            catch (Exception ex)
            {
                //pbOverall.Refresh(counterFile, "Import failed");

                // Show error message
                Console.Write("\nError occured : ", Color.OrangeRed);
                Console.WriteLine(ex.Message);
                //Console.WriteLine("Error trace : " + ex.StackTrace);

                // Show error on
                if (!String.IsNullOrEmpty(fileName))
                {
                    Console.Write("\nError on : ", Color.OrangeRed);
                    Console.WriteLine("'" + fileName + "'");
                }

                // Show description
                Console.WriteLine("\nPlease check your path or file and try again.\n", Color.Yellow);
            }
            finally
            {
                // Show table
                if (returnCollection.Count > 0)
                {
                    Console.WriteLine("\n--------------- Imported detail ---------------", Color.LightGreen);
                    ConsoleTable.From(returnCollection).Write();
                }
                //Console.WriteLine(JsonSerializer.Serialize(returnCollection));

                // Show backup folder path
                if (Directory.Exists(folderBackupPath))
                {
                    Console.Write("\nImported folder : ", Color.LightGreen);
                    Console.WriteLine($"'{ folderBackupPath }'");
                }
            }

            // Wait key to terminate
            Console.Write("\nPress any key to close this window ");
            Console.ReadKey();
        }