Cleanup .net warnings

This commit is contained in:
Michał Zieliński
2023-11-29 22:14:37 +01:00
parent 03cf1a5e07
commit e174a02b54
10 changed files with 304 additions and 332 deletions

View File

@@ -4,7 +4,7 @@ using System.Xml.Serialization;
using Google.Apis.Sheets.v4;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using WebAPI.dataParsers;
using WebAPI.Exports;
@@ -37,42 +37,42 @@ namespace WebAPI.Controllers
logsController = new LogsController(googleSheetsHelper, googleDriveHelper, configuration);
}
[HttpGet]
[HttpGet]
[Route("BackupDatabase/{apiKey}")]
[AllowAnonymous]
public IActionResult BackupDatabase(string apiKey)
{
{
if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"])
{
return Unauthorized();
}
try
{
string databaseName = "diunabi-morska";
string localDatabasePath = $"{configuration["dbBackupFile"]}-{DateTime.UtcNow.Day}.bak";
var formatMediaName = $"DatabaseToolkitBackup_{databaseName}";
var formatName = $"Full Backup of {databaseName}";
var connection = new SqlConnection(configuration.GetConnectionString("SQLDatabase"));
var sql = @"BACKUP DATABASE @databaseName
TO DISK = @localDatabasePath
WITH FORMAT,
MEDIANAME = @formatMediaName,
NAME = @formatName";
connection.Open();
var command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.Parameters.AddWithValue("@databaseName", databaseName);
command.Parameters.AddWithValue("@localDatabasePath", localDatabasePath);
command.Parameters.AddWithValue("@formatMediaName", formatMediaName);
command.Parameters.AddWithValue("@formatName", formatName);
command.ExecuteNonQuery();
{
string databaseName = "diunabi-morska";
string localDatabasePath = $"{configuration["dbBackupFile"]}-{DateTime.UtcNow.Day}.bak";
var formatMediaName = $"DatabaseToolkitBackup_{databaseName}";
var formatName = $"Full Backup of {databaseName}";
var connection = new SqlConnection(configuration.GetConnectionString("SQLDatabase"));
var sql = @"BACKUP DATABASE @databaseName
TO DISK = @localDatabasePath
WITH FORMAT,
MEDIANAME = @formatMediaName,
NAME = @formatName";
connection.Open();
var command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.Parameters.AddWithValue("@databaseName", databaseName);
command.Parameters.AddWithValue("@localDatabasePath", localDatabasePath);
command.Parameters.AddWithValue("@formatMediaName", formatMediaName);
command.Parameters.AddWithValue("@formatName", formatName);
command.ExecuteNonQuery();
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = Path.GetFileName(localDatabasePath);
body.Parents = new List<string?> { configuration["GDriveBackupDirectory"] };
@@ -80,12 +80,16 @@ namespace WebAPI.Controllers
var fsSource = new FileStream(localDatabasePath, FileMode.Open, FileAccess.Read);
if (googleDriveHelper.Service is null)
{
throw new Exception("Google Drive API not initialized");
}
CreateMediaUpload request = googleDriveHelper.Service.Files.Create(body, fsSource, body.MimeType);
request.Fields = "id";
var response = request.Upload();
logsController.AddEntry(new LogEntry
{
Title = "Backup success",
@@ -96,7 +100,7 @@ namespace WebAPI.Controllers
return Ok();
}
catch (Exception e)
{
{
logsController.AddEntry(new LogEntry
{
Title = "Backup error",

View File

@@ -1,121 +1,126 @@
using System.Globalization;
using System.Xml.Serialization;
using DiunaBIWebAPI.dataImporters;
using Google.Apis.Sheets.v4;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.dataParsers;
using WebAPI.dataProcessors;
using WebAPI.Exports;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class LayersController : Controller
{
private readonly AppDbContext db;
private SpreadsheetsResource.ValuesResource googleSheetValues;
private GoogleDriveHelper googleDriveHelper;
private GoogleSheetsHelper googleSheetsHelper;
private readonly IConfiguration configuration;
private readonly LogsController logsController;
public LayersController(
AppDbContext _db,
GoogleSheetsHelper _googleSheetsHelper,
GoogleDriveHelper _googleDriveHelper,
IConfiguration _configuration)
{
db = _db;
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
googleSheetsHelper = _googleSheetsHelper;
googleDriveHelper = _googleDriveHelper;
configuration = _configuration;
logsController = new LogsController(googleSheetsHelper, googleDriveHelper, configuration);
}
[HttpGet]
public IActionResult GetAll(int start, int limit, string? name, LayerType? type)
{
try
{
IQueryable<Layer> response = db.Layers.Where(x => !x.IsDeleted);
if (name != null)
{
response = response.Where(x => x.Name.Contains(name));
}
if (type != null)
{
response = response.Where(x => x.Type == type);
}
return Ok(response
.OrderByDescending(x => x.Number)
.Skip(start).Take(limit).ToList());
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpPost]
public IActionResult Save(Layer input)
{
try
{
//Request.Headers.TryGetValue("userId", out var value);
//Guid currentUserId = new Guid(value!);
return Ok();
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("{id}")]
public IActionResult Get(Guid id)
{
try
{
return Ok(db.Layers
.Include(x => x.CreatedBy)
.Include(x => x.Records)
.Where(x => x.Id == id && !x.IsDeleted).First());
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("exportToGoogleSheet/{id}")]
public IActionResult ExportToGoogleSheet(Guid id)
{
Layer layer = db.Layers
.Include(x => x.Records!.OrderByDescending(x => x.Code))
.Where(x => x.Id == id && !x.IsDeleted).First();
var export = new googleSheetExport(googleDriveHelper, googleSheetValues, configuration);
export.export(layer);
return Ok(true);
}
[HttpGet]
[Route("AutoImport/{apiKey}")]
[AllowAnonymous]
public IActionResult AutoImport(string apiKey)
{
if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"])
{
return Unauthorized();
}
using Google.Apis.Sheets.v4;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.dataProcessors;
using WebAPI.Exports;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class LayersController : Controller
{
private readonly AppDbContext db;
private SpreadsheetsResource.ValuesResource? googleSheetValues;
private GoogleDriveHelper googleDriveHelper;
private GoogleSheetsHelper googleSheetsHelper;
private readonly IConfiguration configuration;
private readonly LogsController logsController;
public LayersController(
AppDbContext _db,
GoogleSheetsHelper _googleSheetsHelper,
GoogleDriveHelper _googleDriveHelper,
IConfiguration _configuration)
{
db = _db;
if (_googleSheetsHelper.Service is not null) {
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
}
googleSheetsHelper = _googleSheetsHelper;
googleDriveHelper = _googleDriveHelper;
configuration = _configuration;
logsController = new LogsController(googleSheetsHelper, googleDriveHelper, configuration);
}
[HttpGet]
public IActionResult GetAll(int start, int limit, string? name, LayerType? type)
{
try
{
IQueryable<Layer> response = db.Layers.Where(x => !x.IsDeleted);
if (name != null)
{
response = response.Where(x => x.Name!=null && x.Name.Contains(name));
}
if (type != null)
{
response = response.Where(x => x.Type == type);
}
return Ok(response
.OrderByDescending(x => x.Number)
.Skip(start).Take(limit).ToList());
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpPost]
public IActionResult Save(Layer input)
{
try
{
//Request.Headers.TryGetValue("userId", out var value);
//Guid currentUserId = new Guid(value!);
return Ok();
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("{id}")]
public IActionResult Get(Guid id)
{
try
{
return Ok(db.Layers
.Include(x => x.CreatedBy)
.Include(x => x.Records)
.Where(x => x.Id == id && !x.IsDeleted).First());
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("exportToGoogleSheet/{id}")]
public IActionResult ExportToGoogleSheet(Guid id)
{
if (googleSheetValues is null) {
throw new Exception("Google Sheets API not initialized");
}
Layer layer = db.Layers
.Include(x => x.Records!.OrderByDescending(x => x.Code))
.Where(x => x.Id == id && !x.IsDeleted).First();
var export = new googleSheetExport(googleDriveHelper, googleSheetValues, configuration);
export.export(layer);
return Ok(true);
}
[HttpGet]
[Route("AutoImport/{apiKey}")]
[AllowAnonymous]
public IActionResult AutoImport(string apiKey)
{
if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"])
{
return Unauthorized();
}
if (googleSheetValues is null) {
throw new Exception("Google Sheets API not initialized");
}
try
{
List<Layer> importWorkerLayers;
@@ -136,7 +141,7 @@ namespace WebAPI.Controllers
Type = LogEntryType.info,
LogType = LogType.import,
CreatedAt = DateTime.UtcNow,
});
});
return Ok();
}
@@ -196,39 +201,42 @@ namespace WebAPI.Controllers
return Ok();
} catch(Exception e)
{
logsController.AddEntry(new LogEntry
{
Title = "Process error",
Type = LogEntryType.error,
LogType = LogType.import,
Message = e.ToString(),
CreatedAt = DateTime.UtcNow
});
logsController.AddEntry(new LogEntry
{
Title = "Process error",
Type = LogEntryType.error,
LogType = LogType.import,
Message = e.ToString(),
CreatedAt = DateTime.UtcNow
});
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("AutoProcess/{apiKey}/{type}")]
[AllowAnonymous]
public IActionResult AutoProcess(string apiKey, string type)
{
if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"])
{
return Unauthorized();
}
try
{
List<Layer> processWorkerLayers = db.Layers
.Include(x => x.Records)
.Where(x =>
x.Records!.Any(x => x.Code == "Type" && x.Desc1 == "ProcessWorker") &&
x.Records!.Any(x => x.Code == "IsEnabled" && x.Desc1 == "True") &&
x.Records!.Any(x => x.Code == "ProcessType" && x.Desc1 == type)
)
.OrderBy(x => x.CreatedAt)
.ToList();
}
}
[HttpGet]
[Route("AutoProcess/{apiKey}/{type}")]
[AllowAnonymous]
public IActionResult AutoProcess(string apiKey, string type)
{
if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"])
{
return Unauthorized();
}
if (googleSheetValues is null) {
throw new Exception("Google Sheets API not initialized");
}
try
{
List<Layer> processWorkerLayers = db.Layers
.Include(x => x.Records)
.Where(x =>
x.Records!.Any(x => x.Code == "Type" && x.Desc1 == "ProcessWorker") &&
x.Records!.Any(x => x.Code == "IsEnabled" && x.Desc1 == "True") &&
x.Records!.Any(x => x.Code == "ProcessType" && x.Desc1 == type)
)
.OrderBy(x => x.CreatedAt)
.ToList();
if (processWorkerLayers.Count() == 0)
{
logsController.AddEntry(new LogEntry
@@ -237,15 +245,15 @@ namespace WebAPI.Controllers
Type = LogEntryType.info,
LogType = LogType.process,
CreatedAt = DateTime.UtcNow,
});
});
return Ok();
}
}
foreach (Layer processWorker in processWorkerLayers)
{
{
try
{
string name = processWorker.Name;
{
string? name = processWorker.Name;
string? year = processWorker?.Records?.SingleOrDefault(x => x.Code == "Year")?.Desc1;
if (year == null)
{
@@ -284,7 +292,7 @@ namespace WebAPI.Controllers
});
continue;
}
T3SourceYearSummaryProcessor processor = new T3SourceYearSummaryProcessor(db, googleSheetValues, this);
T3SourceYearSummaryProcessor processor = new T3SourceYearSummaryProcessor(db, googleSheetValues, this);
processor.process(processWorker!);
logsController.AddEntry(new LogEntry
@@ -311,7 +319,7 @@ namespace WebAPI.Controllers
});
continue;
}
T3MultiSourceYearSummaryProcessor processor = new T3MultiSourceYearSummaryProcessor(db, googleSheetValues, this);
T3MultiSourceYearSummaryProcessor processor = new T3MultiSourceYearSummaryProcessor(db, googleSheetValues, this);
processor.process(processWorker!);
logsController.AddEntry(new LogEntry
@@ -344,13 +352,13 @@ namespace WebAPI.Controllers
{
case "T3-SingleSource":
{
T3SingleSourceProcessor processor = new T3SingleSourceProcessor(db, googleSheetValues, this);
T3SingleSourceProcessor processor = new T3SingleSourceProcessor(db, googleSheetValues, this);
processor.process(processWorker!);
break;
}
case "T3-MultiSourceSummary":
{
T3MultiSourceSummaryProcessor processor = new T3MultiSourceSummaryProcessor(db, googleSheetValues, this);
T3MultiSourceSummaryProcessor processor = new T3MultiSourceSummaryProcessor(db, googleSheetValues, this);
processor.process(processWorker!);
break;
}
@@ -374,45 +382,45 @@ namespace WebAPI.Controllers
CreatedAt = DateTime.UtcNow
});
}
}
return Ok();
}
catch (Exception e)
{
logsController.AddEntry(new LogEntry
{
Title = "Process error",
Type = LogEntryType.error,
LogType = LogType.process,
Message = e.ToString(),
CreatedAt = DateTime.UtcNow
});
return BadRequest(e.ToString());
}
}
internal void SaveRecords(Guid id, ICollection<Record> records, Guid currentUserId)
{
try
{
List<Record> toDelete = db.Records.Where(x => x.LayerId == id).ToList();
if (toDelete.Count > 0)
{
db.Records.RemoveRange(toDelete);
}
foreach (Record record in records)
{
record.CreatedById = currentUserId;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedById = currentUserId;
record.ModifiedAt = DateTime.UtcNow;
record.LayerId = id;
db.Records.Add(record);
}
}
catch (Exception)
{
throw;
}
}
}
}
return Ok();
}
catch (Exception e)
{
logsController.AddEntry(new LogEntry
{
Title = "Process error",
Type = LogEntryType.error,
LogType = LogType.process,
Message = e.ToString(),
CreatedAt = DateTime.UtcNow
});
return BadRequest(e.ToString());
}
}
internal void SaveRecords(Guid id, ICollection<Record> records, Guid currentUserId)
{
try
{
List<Record> toDelete = db.Records.Where(x => x.LayerId == id).ToList();
if (toDelete.Count > 0)
{
db.Records.RemoveRange(toDelete);
}
foreach (Record record in records)
{
record.CreatedById = currentUserId;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedById = currentUserId;
record.ModifiedAt = DateTime.UtcNow;
record.LayerId = id;
db.Records.Add(record);
}
}
catch (Exception)
{
throw;
}
}
}
}

View File

@@ -9,7 +9,7 @@ namespace WebAPI.Controllers
{
public class LogsController : Controller
{
private SpreadsheetsResource.ValuesResource googleSheetValues;
private SpreadsheetsResource.ValuesResource? googleSheetValues;
private GoogleDriveHelper googleDriveHelper;
private readonly IConfiguration configuration;
public LogsController(
@@ -17,13 +17,18 @@ namespace WebAPI.Controllers
GoogleDriveHelper _googleDriveHelper,
IConfiguration _configuration)
{
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
if (_googleSheetsHelper.Service is not null) {
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
}
googleDriveHelper = _googleDriveHelper;
configuration = _configuration;
}
public void AddEntry(LogEntry entry)
{
if (googleSheetValues is null) {
throw new Exception("Google Sheets API not initialized");
}
String type;
switch (entry.LogType) {
case LogType.import:
@@ -42,8 +47,8 @@ namespace WebAPI.Controllers
var response = googleSheetValues.Get(configuration["appLogsFile"], $"{type}!A:A").Execute();
var data = response.Values;
int row = 1;
if (data != null) {
row = data.Count + 1;
if (data != null) {
row = data.Count + 1;
}
var range = $"{type}!A{row}:D{row}";