Files
Partsource/PartSource.Automation/Services/WhiSeoService.cs
2021-06-29 19:00:13 -04:00

102 lines
2.8 KiB
C#

#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using PartSource.Automation.Models.Configuration;
using PartSource.Automation.Models.Enums;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace PartSource.Automation.Services
{
public class WhiSeoService
{
private readonly FtpService _ftpService;
private readonly string _connectionString;
private readonly ILogger<WhiSeoService> _logger;
public WhiSeoService(IConfiguration configuration, ILogger<WhiSeoService> logger)
{
FtpConfiguration ftpConfiguration = configuration.GetSection("FtpServers:WhiConfiguration").Get<FtpConfiguration>();
_ftpService = new FtpService(ftpConfiguration);
_connectionString = configuration.GetConnectionString("FitmentDatabase");
_logger = logger;
}
public void GetFiles(SeoDataType seoDataType)
{
string seoDataTypeString = seoDataType.ToString().ToLowerInvariant();
string[] files = _ftpService.ListFiles(seoDataTypeString);
foreach (string file in files)
{
if (file.EndsWith("csv.gz"))
{
try
{
_ftpService.Download($"{seoDataTypeString}/{file}");
_logger.LogInformation($"Finished downloading {file}.");
}
catch (Exception ex)
{
_logger.LogWarning($"Failed to download {file}, quitting", ex);
throw;
}
}
}
}
public void Truncate()
{
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlCommand command = new SqlCommand($"exec DropFitmentTables", connection);
command.ExecuteNonQuery();
}
public void BulkCopy(SeoDataType seoDataType, DataTable dataTable, string tableName)
{
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlCommand command = new SqlCommand($"EXEC CreateFitmentTempTable @tableName = '{tableName}'", connection);
command.ExecuteNonQuery();
using SqlBulkCopy bulk = new SqlBulkCopy(connection)
{
DestinationTableName = $"FitmentTemp.{tableName}",
BulkCopyTimeout = 14400
};
bulk.WriteToServer(dataTable);
}
public void CreateFitmentTable(string tableName)
{
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlCommand command = new SqlCommand($"exec CreateFitmentTable @tableName = '{tableName}'", connection);
command.ExecuteNonQuery();
}
public void CreateFitmentView()
{
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlCommand command = new SqlCommand($"exec CreateFitmentView", connection);
command.ExecuteNonQuery();
}
}
}
#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities