private static async Task SeedItemsAsync(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger)
        {
            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.ItemsCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var itemArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                var item = await CreateItem(itemArgs, dbContext);

                if (item is null)
                {
                    var name = itemArgs[1];

                    logger.LogWarning(string.Format(DatabaseConstants.SeedingConstants.ItemErrorParseMessage, name));
                    logger.LogWarning(line);

                    continue;
                }

                if (await dbContext.Items.AnyAsync(i => i.Id.Equals(item.Id)))
                {
                    continue;
                }

                await dbContext.AddAsync(item);
            }

            await dbContext.SaveChangesWithExplicitIdentityInsertAsync(nameof(EveEchoesPlanetaryProductionApiDbContext.Items));
        }
        public void Process_WhenFilesExistAndNoRecordsFound()
        {
            var fileRecords = new List <LpFile>()
            {
                new LpFile()
                {
                    Value = 1.5M
                },
                new LpFile()
                {
                    Value = 1.6M
                }
            };

            var options = Options.Create(new CsvSettings()
            {
                CsvFilePath = _testFilesPath
            });
            var fileName = CreateRandomFile(_testFilesPath, "LP_");

            _lpFileProcessor.Setup(p => p.GetAllRecords($"{_testFilesPath}\\{fileName}")).Returns(fileRecords);
            _lpFileProcessor.Setup(p => p.CalculateMedian(fileRecords)).Returns(1.55M);

            using (var outFile = new FileUtility($"{_outputPath}\\outFileSingleRecord.txt"))
            {
                var csvFileService = new CsvFileService(_touFileProcessor.Object, _lpFileProcessor.Object, options);
                csvFileService.Process();
            }

            var lines = File.ReadAllLines($"{_outputPath}\\outFileSingleRecord.txt");

            Assert.Empty(lines);
        }
        private static async Task SeedBlueprintsResources(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger)
        {
            var csvValues = new[]
            {
                "Name", "Type", "Tech Level", "Tritanium", "Pyerite", "Mexallon", "Isogen", "Nocxium", "Zydrine",
                "Megacyte", "Morphite", "Lustering Alloy", "Sheen Compound", "Gleaming Alloy", "Condensed Alloy",
                "Precious Alloy", "Motley Compound", "Fiber Composite", "Lucent Compound", "Opulent Compound",
                "Glossy Compound", "Crystal Compound", "Dark Compound", "Base Metals", "Heavy Metals",
                "Reactive Metals", "Noble Metals", "Toxic Metals", "Reactive Gas", "Noble Gas", "Industrial Fibers",
                "Supertensile Plastics", "Polyaramids", "Coolant", "Condensates", "Construction Blocks", "Nanites",
                "Silicate Glass", "Smartfab Units", "Charred Micro Circuit", "Fried Interface Circuit",
                "Tripped Power Circuit", "Smashed Trigger Unit", "Damaged Close-in Weapon System",
                "Scorched Telemetry Processor", "Contaminated Lorentz Fluid", "Conductive Polymer",
                "Contaminated Nanite Polymer", "Defective Current Pump", "Production Cost", "Production Time",
                "Production Count",
            };

            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.BluePrintsCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var lineArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                await SeedCurrentBlueprintResources(dbContext, logger, lineArgs, csvValues);
            }
        }
        private static async Task SeedRegionsAsync(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger)
        {
            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.RegionsCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var lineArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                var success    = long.TryParse(lineArgs[0], out var regionId);
                var regionName = lineArgs[1];

                if (!success)
                {
                    logger.LogWarning(string.Format(DatabaseConstants.SeedingConstants.RegionErrorParseMessage, regionName));
                    logger.LogWarning(line);
                    continue;
                }

                var region = new Region()
                {
                    Id   = regionId,
                    Name = regionName,
                };

                await dbContext.AddAsync(region);
            }

            await dbContext.SaveChangesWithExplicitIdentityInsertAsync(nameof(EveEchoesPlanetaryProductionApiDbContext
                                                                              .Regions));
        }
Example #5
0
        public int Update(string filePath, string encoding, DataTable dt)
        {
            List <string> writeData = new List <string>();
            // header
            string header = string.Empty;

            foreach (DataColumn col in dt.Columns)
            {
                header += col + ",";
            }
            writeData.Add(header.Remove(header.Length - 1));

            // data
            foreach (DataRow row in dt.Rows)
            {
                string data = string.Empty;
                for (int colIdx = 0; colIdx < dt.Columns.Count; colIdx++)
                {
                    data += row[colIdx]?.ToString() + ",";
                }
                writeData.Add(data.Remove(data.Length - 1));
            }

            CsvFileService csv = CsvFileService.GetInstance();

            return(csv.FileWrite(filePath, encoding, false, writeData));
        }
Example #6
0
        public async Task GenerateAsync()
        {
            // Arrange
            var cancellationToken = CancellationToken.None;

            var contextMock = new Mock <IReportServiceContext>();

            contextMock.SetupGet(c => c.Container).Returns(@"C:\Temp");
            contextMock.SetupGet(c => c.CollectionYear).Returns(1920);
            contextMock.SetupGet(c => c.ReturnPeriod).Returns(1);

            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(sm => sm.GetNowUtc()).Returns(DateTime.Now);

            IFileNameService fileNameService = new FileNameService(dateTimeProvider.Object);

            IFileService    fileService = new FileSystemFileService();
            ICsvFileService csvService  = new CsvFileService(fileService);
            var             loggerMock  = new Mock <ILogger>();

            IFcsRepositoryService fcsRepositoryService = new FcsRepositoryService("(local);Database=FCS;User Id=User;Password=Password1;Encrypt=True;");
            ISummarisedActualsRepositoryService summarisedActualsRepositoryService = new SummarisedActualsRepositoryService("data source=(local);initial catalog=SummarisedActuals;User Id=User;Password=Password1;Encrypt=True;");

            IPeriodSummaryDataProvider periodSummaryDataProvider = new PeriodSummaryDataProvider(summarisedActualsRepositoryService, fcsRepositoryService, loggerMock.Object);

            var periodSummaryReport = new PeriodSummaryReport(fileNameService, csvService, null, periodSummaryDataProvider, loggerMock.Object);

            // Act
            var result = await periodSummaryReport.GenerateAsync(contextMock.Object, cancellationToken);

            // Assert
            result.Should().NotBeNull();
        }
Example #7
0
        public async Task DownloadOrderCsv_Success()
        {
            // ARRANGE
            var    requestMock = new Mock <HttpMessageHandler>(MockBehavior.Default);
            string csvString   =
                @"CustomerId,Name,Product,Price,Weight,Country
16,Henry Been,Pepernoten,3.23,0.5,Netherlands
";

            requestMock.SetupGetMethod(HttpStatusCode.OK, "001-experts-inputs.csv", csvString);

            var             httpClient = new HttpClient(requestMock.Object);
            ICsvFileService srv        = new CsvFileService(httpClient);

            // ACT
            var orderList = await srv.DownloadCsv(new Uri("https://henrybeen.nl/wp-content/uploads/2020/10/001-experts-inputs.csv"));

            // ASSESS
            Assert.Single <CsvOrderLine>(orderList);
            var product = orderList.Single();

            Assert.Equal(16, product.CustomerId);
            Assert.Equal("Henry Been", product.Name);
            Assert.Equal("Pepernoten", product.Product);
            Assert.Equal(3.23d, product.Price);
            Assert.Equal(0.5d, product.Weight);
            Assert.Equal("Netherlands", product.Country);
        }
        public void Process_WhenFilesExistAndPositiveRecordsFound()
        {
            var fileRecords = new List <TouFile>()
            {
                new TouFile()
                {
                    Energy = 1.44M
                },
                new TouFile()
                {
                    Energy = 2.46M
                }
            };

            var options = Options.Create(new CsvSettings()
            {
                CsvFilePath = _testFilesPath
            });
            var fileName = CreateRandomFile(_testFilesPath, "TOU_");

            _touFileProcessor.Setup(p => p.GetAllRecords($"{_testFilesPath}\\{fileName}")).Returns(fileRecords);
            _touFileProcessor.Setup(p => p.CalculateMedian(fileRecords)).Returns(1.95M);

            using (var outFile = new FileUtility($"{_outputPath}\\outFile.txt"))
            {
                var csvFileService = new CsvFileService(_touFileProcessor.Object, _lpFileProcessor.Object, options);
                csvFileService.Process();
            }

            var lines = File.ReadAllLines($"{_outputPath}\\outFile.txt");

            Assert.Equal(2, lines.Length);
            Assert.True(lines[0].IndexOf("1.95") > 0);
        }
Example #9
0
        public int GetRireki(ModelKakeibo model)
        {
            try
            {
                // csvファイル読込
                // ToListで読み込み処理を確定させる
                CsvFileService csv = CsvFileService.GetInstance();

                List <string[]> list = csv.CsvFileRead(model.RirekiFile, encoding)?.ToList();

                if (list.First() == null)
                {
                    return(-1);
                }

                (DataTable dtRireki, int shunyu, int shishutsu) = ConvertToRirekiDataTable(list);
                model.SumShunyu    = shunyu;
                model.SumShishutsu = shishutsu;

                // 残金は履歴ファイルの最終行を設定
                int.TryParse(list.Last()[EnumRireki.Zankin.GetInt()], out int zankin);
                model.Zankin = zankin;

                // データテーブルを設定
                model.RirekiTable = dtRireki;
                model.ShukeiTable = GetShukeiTable(dtRireki);
            }
            catch (Exception ex)
            {
                // csvファイルのデータが0件・1件の場合 ArgumentNullException
                Debug.WriteLine(ex.Message);
            }
            return(0);
        }
Example #10
0
        public DataTable GetKakoRirekiTable(string filePath, string shukeiMode)
        {
            CsvFileService  csv  = CsvFileService.GetInstance();
            List <string[]> list = csv.CsvFileRead(filePath, encoding)?.ToList();

            (DataTable dt, _, _) = ConvertToRirekiDataTable(list);
            dt = GetShukeiTable(dt, shukeiMode);
            return(dt);
        }
Example #11
0
        public int CreateNewRirekiFile(string rirekiFilePath)
        {
            CsvFileService csv = CsvFileService.GetInstance();

            // ヘッダを生成して出力
            WriteRirekiHeader(csv, rirekiFilePath);

            // 残金を繰越金として書き込む
            int kurikoshi = GetZankin();

            return(csv.FileAppend(rirekiFilePath, DateTime.Now.ToString("yyyy/MM/01"), "繰り越し", kurikoshi.ToString(), string.Empty, kurikoshi.ToString(), string.Empty));
        }
Example #12
0
        private static async Task SeedSolarSystemsJumpsAsync(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger)
        {
            var solarSystemsJumps = new List <SolarSystemJump>();

            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.SolarSystemsJumpsCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var lineArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                var fromRegionIdSuccess        = long.TryParse(lineArgs[0], out var fromRegionId);
                var fromConstellationIdSuccess = long.TryParse(lineArgs[1], out var fromConstellationId);

                var fromSolarSystemSuccess = long.TryParse(lineArgs[2], out var fromSolarSystemId);
                var toSolarSystemSuccess   = long.TryParse(lineArgs[3], out var toSolarSystemId);

                var toConstellationIdSuccess = long.TryParse(lineArgs[4], out var toConstellationId);
                var toRegionIdSuccess        = long.TryParse(lineArgs[5], out var toRegionId);

                if (!fromRegionIdSuccess ||
                    !toRegionIdSuccess ||
                    !fromConstellationIdSuccess ||
                    !toConstellationIdSuccess ||
                    !fromSolarSystemSuccess ||
                    !toSolarSystemSuccess)
                {
                    logger.LogWarning($"Can't parse solar system jump");
                    logger.LogWarning(line);
                    continue;
                }

                var solarSystemJump = new SolarSystemJump()
                {
                    FromRegionId        = fromRegionId,
                    FromConstellationId = fromConstellationId,
                    FromSolarSystemId   = fromSolarSystemId,
                    ToSolarSystemId     = toSolarSystemId,
                    ToConstellationId   = toConstellationId,
                    ToRegionId          = toRegionId,
                };

                solarSystemsJumps.Add(solarSystemJump);
            }

            await dbContext.AddRangeAsync(solarSystemsJumps);

            await dbContext.SaveChangesAsync();
        }
Example #13
0
        public async Task DownloadOrderCsv_NotFound()
        {
            // ARRANGE
            var    requestMock = new Mock <HttpMessageHandler>(MockBehavior.Default);
            string csvString   = String.Empty;

            requestMock.SetupGetMethod(HttpStatusCode.NotFound, "001-experts-inputs.csv", csvString);

            var             httpClient = new HttpClient(requestMock.Object);
            ICsvFileService srv        = new CsvFileService(httpClient);

            // ACT / ASSERT
            await Assert.ThrowsAsync <InvalidOperationException>(() => srv.DownloadCsv(new Uri("https://wwwdoesnotexist")));
        }
Example #14
0
        private static async Task SeedPlanetsAsync(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger)
        {
            var planets = new List <Planet>();

            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.PlanetsCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var lineArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                var planetIdParseSuccess        = long.TryParse(lineArgs[0], out var planetId);
                var regionIdParseSuccess        = long.TryParse(lineArgs[1], out var regionId);
                var constellationIdParseSuccess = long.TryParse(lineArgs[2], out var constellationId);
                var solarSystemIdParseSuccess   = long.TryParse(lineArgs[3], out var solarSystemId);
                var planetName = lineArgs[4];
                var planetTypeIdParseSuccess = long.TryParse(lineArgs[5], out var planetTypeId);

                if (!planetIdParseSuccess ||
                    !regionIdParseSuccess ||
                    !constellationIdParseSuccess ||
                    !solarSystemIdParseSuccess ||
                    !planetTypeIdParseSuccess)
                {
                    logger.LogWarning($"Can't parse planet");
                    logger.LogWarning(line);
                    continue;
                }

                var planet = new Planet()
                {
                    Id              = planetId,
                    RegionId        = regionId,
                    ConstellationId = constellationId,
                    SolarSystemId   = solarSystemId,
                    Name            = planetName,
                    PlanetTypeId    = planetTypeId,
                };

                planets.Add(planet);
            }

            await dbContext.AddRangeAsync(planets);

            await dbContext.SaveChangesWithExplicitIdentityInsertAsync(nameof(EveEchoesPlanetaryProductionApiDbContext
                                                                              .Planets));
        }
        public void Process_WheninvalidFileThenNoRecordFound()
        {
            var options = Options.Create(new CsvSettings()
            {
                CsvFilePath = _testFilesPath
            });
            var fileName = CreateRandomFile(_testFilesPath, "PDS_");

            using (var outFile = new FileUtility($"{_outputPath}\\outFileNoRecord.txt"))
            {
                var csvFileService = new CsvFileService(_touFileProcessor.Object, _lpFileProcessor.Object, options);
                csvFileService.Process();
            }

            var lines = File.ReadAllLines($"{_outputPath}\\outFileNoRecord.txt");

            Assert.Empty(lines);
        }
Example #16
0
        private static async Task SeedSolarSystemsAsync(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger)
        {
            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.SolarSystemsCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var lineArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                var regionIdParseSuccess      = long.TryParse(lineArgs[0], out var regionId);
                var constellationParseSuccess = long.TryParse(lineArgs[1], out var constellationId);
                var solarSystemSuccess        = long.TryParse(lineArgs[2], out var solarSystemId);
                var solarSystemName           = lineArgs[3];

                var security = double.Parse(lineArgs[21]);

                if (!regionIdParseSuccess ||
                    !constellationParseSuccess ||
                    !solarSystemSuccess)
                {
                    logger.LogWarning(string.Format(
                                          DatabaseConstants.SeedingConstants.SolarSystemErrorParseMessage,
                                          solarSystemName));
                    logger.LogWarning(line);
                    continue;
                }

                var solarSystem = new SolarSystem()
                {
                    RegionId        = regionId,
                    ConstellationId = constellationId,
                    Id       = solarSystemId,
                    Name     = solarSystemName,
                    Security = security,
                };

                await dbContext.AddAsync(solarSystem);
            }

            await dbContext.SaveChangesWithExplicitIdentityInsertAsync(nameof(EveEchoesPlanetaryProductionApiDbContext
                                                                              .SolarSystems));
        }
Example #17
0
        private static async Task SeedPlanetsResourcesAsync(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger)
        {
            var planetsResources = new List <PlanetResource>();

            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths
                                                                                 .PlanetsResourcesCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var lineArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                var planetIdParseSuccess = long.TryParse(lineArgs[0], out var planetId);
                var itemId             = (await dbContext.Items.FirstOrDefaultAsync(i => i.Name.Equals(lineArgs[6])))?.Id ?? 0;
                var richnessId         = (await dbContext.Richnesses.FirstOrDefaultAsync(i => i.Name.Equals(lineArgs[7])))?.Id ?? 0;
                var outputParseSuccess = double.TryParse(lineArgs[8], out var output);

                if (!planetIdParseSuccess ||
                    itemId is 0 ||
                    richnessId is 0 ||
                    !outputParseSuccess)
                {
                    logger.LogWarning($"Can't parse planet resource");
                    logger.LogWarning(line);
                    continue;
                }

                var planetResource = new PlanetResource()
                {
                    PlanetId   = planetId,
                    ItemId     = itemId,
                    RichnessId = richnessId,
                    Output     = output,
                };

                planetsResources.Add(planetResource);
            }

            await dbContext.AddRangeAsync(planetsResources);

            await dbContext.SaveChangesAsync();
        }
Example #18
0
        public async Task DownloadOrderCsv_InvalidCountry()
        {
            // ARRANGE
            var    requestMock = new Mock <HttpMessageHandler>(MockBehavior.Default);
            string csvString   =
                @"CustomerId,Name,Product,Price,Weight,Country
16,Henry Been,Pepernoten,3.23,0,5,Netherlands
";

            requestMock.SetupGetMethod(HttpStatusCode.OK, "001-experts-inputs.csv", csvString);

            var             httpClient = new HttpClient(requestMock.Object);
            ICsvFileService srv        = new CsvFileService(httpClient);

            // ACT / ASSERT
            var orderList = await srv.DownloadCsv(new Uri("https://henrybeen.nl/wp-content/uploads/2020/10/001-experts-inputs.csv"));

            Assert.Empty(orderList);
        }
Example #19
0
        static async Task <int> Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

            var tw = new TextWriterTraceListener(Console.Out);

            tw.TraceOutputOptions |= TraceOptions.None;
            Trace.Listeners.Add(tw);
            Trace.AutoFlush = true;
            Trace.Indent();

            // Setup
            var httpClient = new HttpClient();

            using CsvFileService fileService = new CsvFileService(httpClient);
            var app = new CommandLineApplication
            {
                Name        = "TW ING Coding Challenge",
                Description = "The TeamWildenberg console app for the different assignments in the ING Coding Challenge"
            };

            app.HelpOption("-?|-h|--help");
            var versionOption = app.Option("-v|--version", "Check which version we are running", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                return(0);
            });
            app.Execute(args);

            ICommandAsync cmd = null;

            if (versionOption.HasValue())
            {
                cmd = new AssemblyVersionCommand();
            }
            else
            {
                cmd = new PrintOrdersCommand(fileService);
            }

            return(await cmd.Execute().ConfigureAwait(false));
        }
Example #20
0
        private static ContainerBuilder RegisterNcsService(this ContainerBuilder containerBuilder, INcsServiceConfiguration ncsServiceConfiguration)
        {
            // Tasks
            containerBuilder.RegisterType <FundingTask>().As <INcsDataTask>();
            containerBuilder.RegisterType <ReportingTask>().As <INcsDataTask>();
            containerBuilder.RegisterType <EntryPoint>().As <IEntryPoint>();

            // Services
            containerBuilder.RegisterType <FundingService>().As <IFundingService>();
            containerBuilder.RegisterType <MessageService>().As <IMessageService>();
            containerBuilder.RegisterType <StreamProviderService>().As <IStreamProviderService>();
            containerBuilder.RegisterType <StorageService>().As <IStorageService>().WithAttributeFiltering();
            containerBuilder.RegisterType <ExcelService>().As <IExcelService>().WithAttributeFiltering();
            containerBuilder.RegisterType <FileNameService>().As <IFilenameService>();
            containerBuilder.RegisterType <ZipService>().As <IZipService>().WithAttributeFiltering();
            containerBuilder.RegisterType <OccupancyReportMapperFactory>().As <IClassMapFactory <OccupancyReportModel> >();
            containerBuilder.RegisterType <BulkInsert>().As <IBulkInsert>();
            containerBuilder.Register(c =>
            {
                var csvFileService = new CsvFileService(c.ResolveKeyed <IFileService>(PersistenceStorageKeys.DctAzureStorage));
                return(csvFileService);
            }).As <ICsvFileService>();

            // Ncs database
            containerBuilder.RegisterType <NcsContext>().As <INcsContext>();
            containerBuilder.Register(container => new DbContextOptionsBuilder <NcsContext>()
                                      .UseSqlServer(ncsServiceConfiguration.NcsDbConnectionString)
                                      .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).Options).As <DbContextOptions <NcsContext> >().SingleInstance();

            // Data services
            containerBuilder.RegisterType <PersistenceService>().As <IPersistenceService>();
            containerBuilder.RegisterType <OutcomeRateQueryService>().As <IOutcomeRateQueryService>();
            containerBuilder.RegisterType <NcsSubmissionQueryService>().As <INcsSubmissionQueryService>();
            containerBuilder.RegisterType <FundingValueQueryService>().As <IFundingValueQueryService>();
            containerBuilder.RegisterType <SourceQueryService>().As <ISourceQueryService>();
            containerBuilder.RegisterType <ClearService>().As <IClearService>();

            containerBuilder.Register(c => new DataServiceConfiguration(ncsServiceConfiguration.NcsDbConnectionString)).As <IDataServiceConfiguration>();

            return(containerBuilder);
        }
Example #21
0
        private static async Task SeedItemTypesAsync(EveEchoesPlanetaryProductionApiDbContext dbContext)
        {
            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.ItemTypesCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var lineArgs     = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);
                var itemTypeName = lineArgs[0];

                var itemType = new ItemType()
                {
                    Name = itemTypeName,
                };

                await dbContext.AddAsync(itemType);
            }

            await dbContext.SaveChangesAsync();
        }
Example #22
0
        private void SaveFile(ICollection <YDPostModel> records)
        {
            IFileService   fileService   = new CsvFileService();
            IDialogService dialogService = new DefaultDialogService();

            try
            {
                if (records == null || records.Count < 1)
                {
                    throw new Exception("Нет данных для сохранения");
                }

                if (dialogService.SaveFileDialog() == true)
                {
                    fileService.Save(dialogService.FilePath, PostToCsvConverter.Convert(records));
                    dialogService.ShowMessage("Файл сохранен");
                }
            }
            catch (Exception ex)
            {
                dialogService.ShowMessage(ex.Message);
            }
        }
        private static async Task UpdateItems(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger, bool update)
        {
            if (!update)
            {
                return;
            }

            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.ItemsCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var itemArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                var success = long.TryParse(itemArgs[0], out var itemId);

                if (!success)
                {
                    logger.LogError("Can't parse item");
                    logger.LogError(line);
                    continue;
                }

                if (await dbContext.Items.AnyAsync(i => i.Id.Equals(itemId)))
                {
                    continue;
                }

                var item = await CreateItem(itemArgs, dbContext);

                await dbContext.AddAsync(item);

                await dbContext.SaveChangesWithExplicitIdentityInsertAsync(nameof(EveEchoesPlanetaryProductionApiDbContext.Items));
            }
        }
Example #24
0
        public DataTable GetDataTable(string filePath, string encoding)
        {
            DataTable dt = new DataTable();

            try
            {
                // csvファイル読込
                // ToListで読み込み処理を確定させる
                CsvFileService  csv  = CsvFileService.GetInstance();
                List <string[]> list = csv.CsvFileRead(filePath, encoding).ToList();

                // ヘッダ設定
                foreach (string text in list.First())
                {
                    Debug.WriteLine($"Columns.Add({text})");
                    dt.Columns.Add(text);
                }

                // データ設定
                foreach (string[] texts in list.Skip(1))
                {
                    DataRow row = dt.NewRow();
                    for (int colIdx = 0; colIdx < dt.Columns.Count; colIdx++)
                    {
                        Debug.WriteLine($"Rows[{colIdx}].Add({texts[colIdx]})");
                        row[colIdx] = texts[colIdx];
                    }
                    dt.Rows.Add(row);
                }
            }
            catch (Exception ex)
            {
                // csvファイルのデータが0件・1件の場合 ArgumentNullException
                Debug.WriteLine(ex.Message);
            }
            return(dt);
        }
Example #25
0
        private static async Task SeedBlueprints(EveEchoesPlanetaryProductionApiDbContext dbContext, ILogger logger)
        {
            await foreach (var line in CsvFileService.ReadCsvDataLineByLineAsync(GlobalConstants.FilePaths.BluePrintsCsvFilePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var lineArgs = line.Split(GlobalConstants.CsvDelimiter, StringSplitOptions.RemoveEmptyEntries);

                var name        = lineArgs[0];
                var type        = lineArgs[1];
                var techSuccess = int.TryParse(lineArgs[2], out var tech);

                var productionCostSuccess  = long.TryParse(lineArgs[49], out var productionCost);
                var productionTimeSuccess  = long.TryParse(lineArgs[50], out var productionTime);
                var productionCountSuccess = long.TryParse(lineArgs[51], out var productionCount);

                var product = await dbContext.Items
                              .Where(i => i.Name.Equals(name))
                              .FirstOrDefaultAsync();

                var productType = await dbContext.ItemTypes
                                  .Where(t => t.Name.Equals(type))
                                  .FirstOrDefaultAsync();

                var blueprintName = $"{name} Blueprint";

                var blueprintItem = await dbContext.Items
                                    .Where(i => i.Name.Equals(blueprintName))
                                    .FirstOrDefaultAsync() ?? await CreateBlueprint(dbContext, blueprintName, productType);

                if (product is null ||
                    productType is null ||
                    blueprintItem is null ||
                    !techSuccess ||
                    !productionCostSuccess ||
                    !productionTimeSuccess ||
                    !productionCountSuccess)
                {
                    logger.LogError("Cant parse blueprint");
                    logger.LogError(line);

                    continue;
                }

                var blueprint = new Blueprint()
                {
                    BlueprintItem   = blueprintItem,
                    Product         = product,
                    ProductType     = productType,
                    TechLevel       = tech,
                    ProductionCost  = productionCost,
                    ProductionTime  = productionTime,
                    ProductionCount = productionCount,
                };

                await dbContext.Blueprints.AddAsync(blueprint);

                await dbContext.SaveChangesAsync();
            }
        }