cleanup of using statements

pull/1/head
DJh2o2 2023-01-09 15:37:28 +07:00
parent 06cf67f015
commit 16e309b06a
6 changed files with 606 additions and 699 deletions

@ -59,9 +59,11 @@ namespace Gremlin_BlazorServer.Data.DBClasses
public static void DbBuilder()
{
using GremlinDb gremlinDb = new();
_ = gremlinDb.Database.EnsureDeleted();
_ = gremlinDb.Database.EnsureCreated();
using (GremlinDb gremlinDb = new())
{
gremlinDb.Database.EnsureDeleted();
gremlinDb.Database.EnsureCreated();
}
}
public static void DbInitializer()
@ -100,9 +102,11 @@ namespace Gremlin_BlazorServer.Data.DBClasses
DataModificationByUser = "DbInitializer"
};
using GremlinDb gremlinDb = new();
_ = gremlinDb.ProductLines.Add(plToBeAdded);
_ = gremlinDb.SaveChanges();
using (GremlinDb gremlinDb = new())
{
gremlinDb.ProductLines.Add(plToBeAdded);
gremlinDb.SaveChanges();
}
}
//ACCOUNT TYPES
@ -127,9 +131,11 @@ namespace Gremlin_BlazorServer.Data.DBClasses
_ = MetaDataSetter.ForImport(aTtoBeAdded, "DbInitializer", "DbInitializer");
using GremlinDb db = new();
_ = db.AccountTypes.Add(aTtoBeAdded);
_ = db.SaveChanges();
using (GremlinDb gremlinDb = new())
{
gremlinDb.AccountTypes.Add(aTtoBeAdded);
gremlinDb.SaveChanges();
}
}
//SubMarkets
@ -153,9 +159,11 @@ namespace Gremlin_BlazorServer.Data.DBClasses
_ = MetaDataSetter.ForImport(sMtoBeAdded, "DbInitializer", "DbInitializer");
using GremlinDb db = new();
_ = db.SubMarkets.Add(sMtoBeAdded);
_ = db.SaveChanges();
using (GremlinDb gremlinDb = new())
{
gremlinDb.SubMarkets.Add(sMtoBeAdded);
gremlinDb.SaveChanges();
}
}
List<Account> seedAccounts = new();
@ -360,18 +368,18 @@ namespace Gremlin_BlazorServer.Data.DBClasses
seedAccounts.Add(pike);
using (GremlinDb db = new())
using (GremlinDb gremlinDb = new())
{
foreach (Account account in seedAccounts)
{
// AccountType und SubMarket aus DB laden, damit der Datensatz vom Context verfolgt wird und EF Core nicht versucht, diesen standardmäßig neu anzulegen.
account.AccountType = ResolveAccountType(db, account.AccountType.AccountTypeCode);
account.SubMarket = ResolveSubmarket(db, account.SubMarket.SubMarketCode);
account.AccountType = ResolveAccountType(gremlinDb, account.AccountType.AccountTypeCode);
account.SubMarket = ResolveSubmarket(gremlinDb, account.SubMarket.SubMarketCode);
_ = MetaDataSetter.ForImport(account, "DbInitializer", "Function DbHelper.DbInitializer");
}
db.Accounts.AddRange(seedAccounts);
_ = db.SaveChanges();
gremlinDb.Accounts.AddRange(seedAccounts);
gremlinDb.SaveChanges();
}
//RegisteredUser
@ -391,7 +399,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
};
seedRegisteredUser.Add(userSebastian);
using (GremlinDb db = new())
using (GremlinDb gremlinDb = new())
{
foreach (RegisteredUser userSetting in seedRegisteredUser)
{
@ -399,8 +407,8 @@ namespace Gremlin_BlazorServer.Data.DBClasses
userSetting.DataModificationByUser = "DB Initializer";
userSetting.DataModificationDate = DateTime.Now;
}
db.RegisteredUser.AddRange(seedRegisteredUser);
_ = db.SaveChanges();
gremlinDb.RegisteredUser.AddRange(seedRegisteredUser);
gremlinDb.SaveChanges();
}
//RUSetting
@ -454,7 +462,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
seedRuSettings.Add(saschaTexRand);
}
using (GremlinDb db = new())
using (GremlinDb gremlinDb = new())
{
foreach (RuSettings userSetting in seedRuSettings)
{
@ -462,14 +470,15 @@ namespace Gremlin_BlazorServer.Data.DBClasses
userSetting.DataModificationByUser = "DB Initializer";
userSetting.DataModificationDate = DateTime.Now;
}
db.RuSettings.AddRange(seedRuSettings);
_ = db.SaveChanges();
gremlinDb.RuSettings.AddRange(seedRuSettings);
gremlinDb.SaveChanges();
}
}
public static void InsertTestDataIntoDb()
{
using GremlinDb db = new();
using (GremlinDb gremlinDb = new())
{
Random r = new();
Contact newContact = new()
@ -480,7 +489,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
Gender = (byte)Gender.Male,
Department = RandomString(9),
};
_ = MetaDataSetter.ForImport(newContact, "Tester", "Seeding data for testing.");
MetaDataSetter.ForImport(newContact, "Tester", "Seeding data for testing.");
Account newAccount = new()
@ -493,44 +502,34 @@ namespace Gremlin_BlazorServer.Data.DBClasses
EMail = RandomString(9) + "@" + RandomString(9) + "." + RandomString(3),
PhoneNumber = "+49 " + r.Next().ToString(),
};
_ = MetaDataSetter.ForImport(newAccount, "Tester", "Seeding data for testing.");
MetaDataSetter.ForImport(newAccount, "Tester", "Seeding data for testing.");
AccountType accountType = db.AccountTypes.FirstOrDefault(a => a.AccountTypeCode == "FPC")!;
AccountType accountType = gremlinDb.AccountTypes.FirstOrDefault(a => a.AccountTypeCode == "FPC")!;
newAccount.AccountType = accountType;
SubMarket subMarket = db.SubMarkets
.First(a => a.SubMarketCode == "CEN");
SubMarket subMarket = gremlinDb.SubMarkets.First(a => a.SubMarketCode == "CEN");
newAccount.SubMarket = subMarket;
newContact.Account = newAccount;
try
{
_ = db.Add(newAccount);
_ = db.SaveChanges();
_ = db.Add(newContact);
_ = db.SaveChanges();
gremlinDb.Add(newAccount);
gremlinDb.SaveChanges();
gremlinDb.Add(newContact);
gremlinDb.SaveChanges();
Debug.WriteLine($"Account {newAccount.AccountName} mit Contact {newContact.LastName} wurde angelegt.");
}
catch (Exception ex)
catch (Exception e)
{
Debug.WriteLine(ex);
Debug.WriteLine(e.Message);
}
}
}
private static bool ImportContactsFromCsv(string filepath = "", string separator = ";", bool dataHasHeading = true)
{
//Pfad abfragen über Dtei-Öffnen-Dialog:
if (filepath == "")
{
//filepath = FileIO.GetFilepathFromUser();
}
//Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch:
if (filepath == "")
{
return false;
}
if (filepath == "") return false;
List<Contact> contactsReadFromFile = new(8000);
// ENCODING CHANGED TO UNICODE. TO BE TESTED!
@ -541,12 +540,8 @@ namespace Gremlin_BlazorServer.Data.DBClasses
csvParser.CommentTokens = new[] { "#" };
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names:
if (dataHasHeading)
{
_ = csvParser.ReadLine();
}
if (dataHasHeading) csvParser.ReadLine();
while (!csvParser.EndOfData)
{
@ -615,16 +610,10 @@ namespace Gremlin_BlazorServer.Data.DBClasses
importedContact.SapContactCreationDate = new(year, month, day);
//Convert "No Phone Calls"
if (fields[26] == "1")
{
importedContact.NoPhoneCalls = true;
}
if (fields[26] == "1") importedContact.NoPhoneCalls = true;
//Convert "No Hardcopy Mailing"
if (fields[27] == "1")
{
importedContact.NoHardcopyMailing = true;
}
if (fields[27] == "1") importedContact.NoHardcopyMailing = true;
//SAPAccountID in Contact.Notes speichern, um den entsprechenden Account aus DB heraussuchen zu können:
importedContact.Notes = fields[0];
@ -633,18 +622,18 @@ namespace Gremlin_BlazorServer.Data.DBClasses
}
//Eingelesenen Account in DB schreiben:
using (GremlinDb db = new())
using (GremlinDb gremlinDb = new())
{
foreach (Contact contact in contactsReadFromFile)
{
// AccountID aus DB laden, damit der Datensatz vom Context verfolgt wird und EF Core nicht versucht, diesen standardmäßig neu anzulegen.
contact.Account = ResolveAccountById(db, uint.Parse(contact.Notes));
contact.Account = ResolveAccountById(gremlinDb, uint.Parse(contact.Notes));
contact.Notes = "";
_ = MetaDataSetter.ForImport(contact, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportContactsFromCSV)");
MetaDataSetter.ForImport(contact, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportContactsFromCSV)");
}
db.Contacts.AddRange(contactsReadFromFile);
_ = db.SaveChanges();
gremlinDb.Contacts.AddRange(contactsReadFromFile);
gremlinDb.SaveChanges();
}
}
//Bestätigung senden
@ -654,24 +643,16 @@ namespace Gremlin_BlazorServer.Data.DBClasses
private static bool ImportAccountsFromCsv(string filepath = "", string separator = ";", bool dataHasHeading = true)
{
//Pfad abfragen über Dtei-Öffnen-Dialog:
if (filepath == "")
{
//filepath = FileIO.GetFilepathFromUser();
}
//Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch:
if (filepath == "")
{
return false;
}
if (filepath == "") return false;
List<Account> accountsReadFromFile = new(1000);
List<Account> accountsReadFromFile = new(2000);
//ENCODING CHANGED TO ISO-8859-1 AS EQUIVALENT (?) TO "LATIN1" (unavailable). TO BE TESTED!
//ich würde mir ja UTF8 als universelles Encoding wünschen
using TextFieldParser csvParser = new(filepath, FileService.GetEncoding(filepath));
using (TextFieldParser csvParser = new(filepath, FileService.GetEncoding(filepath)))
{
//Parser configuration:
csvParser.Delimiters = new[] { separator };
csvParser.CommentTokens = new[] { "#" };
@ -680,7 +661,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
// Skip the row with the column names:
if (dataHasHeading)
{
_ = csvParser.ReadLine();
csvParser.ReadLine();
}
while (!csvParser.EndOfData)
@ -780,46 +761,47 @@ namespace Gremlin_BlazorServer.Data.DBClasses
accountsReadFromFile.Add(importedAccount);
}
}
//Eingelesenen Account in DB schreiben:
using GremlinDb db = new();
using (GremlinDb gremlinDb = new())
{
foreach (Account account in accountsReadFromFile)
{
// AccountType aus DB laden, damit der Datensatz vom Context verfolgt wird und EF Core nicht versucht, diesen standardmäßig neu anzulegen.
if (account.AccountType.AccountTypeCode != "")
{
AccountType accountType = db.AccountTypes
.First(a => a.AccountTypeCode == account.AccountType.AccountTypeCode);
AccountType accountType = gremlinDb.AccountTypes.First(a => a.AccountTypeCode == account.AccountType.AccountTypeCode);
account.AccountType = accountType;
account.AccountType = ResolveAccountType(db, account.AccountType.AccountTypeCode);
account.AccountType = ResolveAccountType(gremlinDb, account.AccountType.AccountTypeCode);
}
else
{
//Default
account.AccountType = ResolveAccountType(db, "FPC");
account.AccountType = ResolveAccountType(gremlinDb, "FPC");
}
if (account.SubMarket.SubMarketCode != "")
{
SubMarket subMarket = db.SubMarkets
.First(a => a.SubMarketCode == account.SubMarket.SubMarketCode);
SubMarket subMarket = gremlinDb.SubMarkets.First(a => a.SubMarketCode == account.SubMarket.SubMarketCode);
account.SubMarket = subMarket;
//Warum gelöscht? account.AccountType = ResolveAccountType(db, account.AccountType.AccountTypeCode);
account.SubMarket = ResolveSubmarket(db, account.SubMarket.SubMarketCode);
account.AccountType = ResolveAccountType(gremlinDb, account.AccountType.AccountTypeCode);
account.SubMarket = ResolveSubmarket(gremlinDb, account.SubMarket.SubMarketCode);
}
else
{
//Default
account.SubMarket = ResolveSubmarket(db, "COT");
account.SubMarket = ResolveSubmarket(gremlinDb, "COT");
}
_ = MetaDataSetter.ForImport(account, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportAccountsFromCSV)");
MetaDataSetter.ForImport(account, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportAccountsFromCSV)");
}
db.Accounts.AddRange(accountsReadFromFile);
_ = db.SaveChanges();
gremlinDb.Accounts.AddRange(accountsReadFromFile);
gremlinDb.SaveChanges();
}
//Bestätigung senden
Debug.WriteLine($"Es wurden {accountsReadFromFile.Count} Accounts erfolgreich der Datenbank hinzugefügt.");
@ -830,20 +812,13 @@ namespace Gremlin_BlazorServer.Data.DBClasses
private static bool ImportLsagContactListToolData(string filepath = "", string separator = ";")
{
if (filepath == "")
{
//filepath = FileIO.GetFilepathFromUser(); //Pfad abfragen über Dtei-Öffnen-Dialog:
}
if (filepath == "")
{
return false; //Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch:
}
if (filepath == "") return false; //Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch:
List<Contact> contactsReadFromFile = new(8000);
List<Account> accountsReadFromFile = new(1000);
List<Account> accountsReadFromFile = new(2000);
using TextFieldParser csvParser = new(filepath, FileService.GetEncoding(filepath));
using (TextFieldParser csvParser = new(filepath, FileService.GetEncoding(filepath)))
{
//Parser configuration:
csvParser.Delimiters = new[] { separator };
csvParser.CommentTokens = new[] { "#" };
@ -940,7 +915,8 @@ namespace Gremlin_BlazorServer.Data.DBClasses
importedAccount.AccountCreatedInSapOn = new(year, month, day);
//Convert City von Großschreibung zu Normalschreibung
importedAccount.City = fields[columnNumberOf["City"]].First().ToString() + fields[columnNumberOf["City"]].Substring(1).ToLower();
importedAccount.City = fields[columnNumberOf["City"]].First().ToString() +
fields[columnNumberOf["City"]].Substring(1).ToLower();
// keine Konvertierung nötig:
importedAccount.AccountName = fields[columnNumberOf["AccountName"]];
@ -986,10 +962,13 @@ namespace Gremlin_BlazorServer.Data.DBClasses
//Convert Gender
importedContact.Gender = fields[columnNumberOf["Gender"]] == "M"
? (byte)Gender.Male
: fields[columnNumberOf["Gender"]] == "F" ? (byte)Gender.Female : (byte)Gender.Unknown;
: fields[columnNumberOf["Gender"]] == "F"
? (byte)Gender.Female
: (byte)Gender.Unknown;
//Convert OptIn Status
importedContact.OptInStatus = fields[columnNumberOf["OptInStatus"]] == "Opt In" || (fields[columnNumberOf["OptInStatus"]] == "Opt Out" && false);
importedContact.OptInStatus = fields[columnNumberOf["OptInStatus"]] == "Opt In" ||
(fields[columnNumberOf["OptInStatus"]] == "Opt Out" && false);
//Convert "SAP Contact Number"
try
@ -1045,7 +1024,8 @@ namespace Gremlin_BlazorServer.Data.DBClasses
importedContact.Notes = fields[columnNumberOf["SAPAccountNumber"]];
//Validierungen:
if (importedContact.EmailBounced || importedContact.LastName == "" || importedContact.SapContactNumber == 0)
if (importedContact.EmailBounced || importedContact.LastName == "" ||
importedContact.SapContactNumber == 0)
{
dataHasError = true;
}
@ -1061,28 +1041,27 @@ namespace Gremlin_BlazorServer.Data.DBClasses
contactsReadFromFile.Add(importedContact);
}
}
}
//Eingelesenen Account in DB schreiben:
using (GremlinDb db = new())
using (GremlinDb gremlinDb = new())
{
foreach (Account account in accountsReadFromFile)
{
// AccountType aus DB laden, damit der Datensatz vom Context verfolgt wird und EF Core nicht versucht, diesen standardmäßig neu anzulegen.
AccountType accountType = db.AccountTypes
.First(a => a.AccountTypeCode == account.AccountType.AccountTypeCode);
AccountType accountType = gremlinDb.AccountTypes.First(a => a.AccountTypeCode == account.AccountType.AccountTypeCode);
account.AccountType = accountType;
SubMarket subMarket = db.SubMarkets
.First(a => a.SubMarketCode == account.SubMarket.SubMarketCode);
SubMarket subMarket = gremlinDb.SubMarkets.First(a => a.SubMarketCode == account.SubMarket.SubMarketCode);
account.SubMarket = subMarket;
account.AccountType = ResolveAccountType(db, account.AccountType.AccountTypeCode);
account.SubMarket = ResolveSubmarket(db, account.SubMarket.SubMarketCode);
_ = MetaDataSetter.ForImport(account, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportAccountsFromCSV)");
account.AccountType = ResolveAccountType(gremlinDb, account.AccountType.AccountTypeCode);
account.SubMarket = ResolveSubmarket(gremlinDb, account.SubMarket.SubMarketCode);
MetaDataSetter.ForImport(account, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportAccountsFromCSV)");
}
db.Accounts.AddRange(accountsReadFromFile);
_ = db.SaveChanges();
gremlinDb.Accounts.AddRange(accountsReadFromFile);
gremlinDb.SaveChanges();
}
//Eingelesenen Contacts in DB schreiben:
@ -1092,11 +1071,11 @@ namespace Gremlin_BlazorServer.Data.DBClasses
{
contact.Account = ResolveAccountById(db, uint.Parse(contact.Notes));
contact.Notes = "";
_ = MetaDataSetter.ForImport(contact, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportContactsFromCSV)");
MetaDataSetter.ForImport(contact, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportContactsFromCSV)");
}
db.Contacts.AddRange(contactsReadFromFile);
_ = db.SaveChanges();
db.SaveChanges();
}
return true;
@ -1104,50 +1083,32 @@ namespace Gremlin_BlazorServer.Data.DBClasses
private static bool ImportProductsFromCsv(string filepath = "", string separator = "|", bool dataHasHeading = true)
{
if (filepath == "")
{
//filepath = FileIO.GetFilepathFromUser(); //Pfad abfragen über Dtei-Öffnen-Dialog.
}
if (filepath == "")
{
return false; //Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch.
}
if (filepath == "") return false; //Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch.
List<Product> productsReadFromFile = new(ParseProductFile(filepath, separator, dataHasHeading));
return InsertProducts(productsReadFromFile);
}
private static bool ImportCustomDescriptionsFromCsv(string filepath = "", string separator = "|", bool dataHasHeading = true)
{
if (filepath == "")
{
//filepath = FileIO.GetFilepathFromUser("Delimited Data File|*.csv; *.txt; *.tsv"); //Pfad abfragen über Dtei-Öffnen-Dialog:
}
if (filepath == "")
private static bool ImportCustomDescriptionsFromCsv(string filepath = "", string separator = "|",
bool dataHasHeading = true)
{
return false; //Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch:
}
if (filepath == "") return false; //Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch:
List<CustomDescription> cDsReadFromFile = new(2500);
using TextFieldParser csvParser = new(filepath, Encoding.GetEncoding("UTF-8"));
using (TextFieldParser csvParser = new(filepath, Encoding.GetEncoding("UTF-8")))
{
//Parser configuration:
csvParser.Delimiters = new[] { separator };
csvParser.CommentTokens = new[] { "#" };
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names:
if (dataHasHeading)
{
_ = csvParser.ReadLine();
}
if (dataHasHeading) csvParser.ReadLine();
while (!csvParser.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvParser.ReadFields()!;
//string productNumber = fields[0];
//string? optionNumber = fields[1] == "" ? null : fields[1];
CustomDescription importedCd = new()
@ -1164,10 +1125,11 @@ namespace Gremlin_BlazorServer.Data.DBClasses
AccountName = fields[2] is "" or "RB" ? "Agilent Technologies" : fields[2]
}
};
_ = MetaDataSetter.ForImport(importedCd, "Importer", "Initial Importer by CD-ImporterFomCsv");
MetaDataSetter.ForImport(importedCd, "Importer", "Initial Importer by CD-ImporterFomCsv");
cDsReadFromFile.Add(importedCd);
}
}
//Eingelesenen Custum Desciptions in DB schreiben:
//Check for 3PPs that not yet in the db.
@ -1175,7 +1137,8 @@ namespace Gremlin_BlazorServer.Data.DBClasses
//Step 1b: Add list to db.
//Step 2: Add CDs to products.
using GremlinDb db = new();
using (GremlinDb gremlinDb = new())
{
//Step 1a
List<Product> thirdPartyProductsFromImportedCDs = new();
foreach (CustomDescription cd in cDsReadFromFile)
@ -1196,45 +1159,54 @@ namespace Gremlin_BlazorServer.Data.DBClasses
IntroductionDate = DateTime.Now.Date,
BreakRangeFrom = 0,
BreakRangeTo = 0,
ProductLine = ResolveProductLine(db, "3P")
ProductLine = ResolveProductLine(gremlinDb, "3P")
};
new3PpProduct.CustomDescription.Supplier = ResolveAccountByName(db, new3PpProduct.CustomDescription.Supplier.AccountName);
_ = MetaDataSetter.ForImport(new3PpProduct, "Custom Desciption Importer", "Created at import from Custom Descriptions.");
new3PpProduct.CustomDescription.Supplier = ResolveAccountByName(gremlinDb,
new3PpProduct.CustomDescription.Supplier.AccountName);
_ = MetaDataSetter.ForImport(new3PpProduct, "Custom Desciption Importer",
"Created at import from Custom Descriptions.");
thirdPartyProductsFromImportedCDs.Add(new3PpProduct);
}
}
//Step 1b
db.Products.AddRange(thirdPartyProductsFromImportedCDs); //Imports both the products and the associated custom descriptions!
_ = db.SaveChanges();
gremlinDb.Products.AddRange(
thirdPartyProductsFromImportedCDs); //Imports both the products and the associated custom descriptions!
_ = gremlinDb.SaveChanges();
// Produkt aus DB laden, damit der Datensatz vom Context verfolgt wird und EF Core nicht versucht, diesen standardmäßig neu anzulegen.
//Step 2
List<CustomDescription> importedCDsWithEfReferences = new(100000);
List<CustomDescription> cDsWithoutEfReferences = new(1000); //nur zur Kontrolle, wird nicht verwendet.
List<Product> productsInDb = db.Products.ToList();
Account agilent = db.Accounts.Single(a => a.AccountName == "Agilent Technologies");
foreach (CustomDescription cd in cDsReadFromFile.Where(cd => !thirdPartyProductsFromImportedCDs.Intersect(cd.Products).Any()))
List<Product> productsInDb = gremlinDb.Products.ToList();
Account agilent = gremlinDb.Accounts.Single(a => a.AccountName == "Agilent Technologies");
foreach (CustomDescription cd in cDsReadFromFile.Where(cd =>
!thirdPartyProductsFromImportedCDs.Intersect(cd.Products).Any()))
{
//Establish EF Reference. If no PN/Opt found, then skip this custom description.
//CD.Product = GetProduct(db, CD.ProductNumber, CD.OptionNumber); //ResolveXY-functions return null, if no match is found in db.
cd.Products = productsInDb.Where(product => product.ProductNumber == cd.ProductNumber && product.OptionNumber == cd.OptionNumber).ToList();
cd.Products = productsInDb.Where(product =>
product.ProductNumber == cd.ProductNumber && product.OptionNumber == cd.OptionNumber).ToList();
//Establish EF Reference: If no Supplier-Account found, then skip this custom description (shouldn't happen), else set Supplier to Agilent (3PP-Supplier have been processed before and their products should not be part of this list).
cd.Supplier = agilent;
_ = MetaDataSetter.ForImport(cd, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportCustomDescriptionsFromCsv)");
MetaDataSetter.ForImport(cd, "CSVImporter",
"Initial import by CSV Importer (Function DbHelper.ImportCustomDescriptionsFromCsv)");
//add to final list of CDs, that will go into the db.
importedCDsWithEfReferences.Add(cd);
}
db.CustomDescriptions.AddRange(importedCDsWithEfReferences);
_ = db.SaveChanges();
gremlinDb.CustomDescriptions.AddRange(importedCDsWithEfReferences);
gremlinDb.SaveChanges();
//Bestätigung senden
Debug.WriteLine($"Es wurden {importedCDsWithEfReferences.Count} eigene Beschreibungen erfolgreich der Datenbank hinzugefügt.{Environment.NewLine}Es wurden {thirdPartyProductsFromImportedCDs.Count} 3PP-Produkte neu angelegt.");
return true;
}
}
//public static bool ImportCustomDescriptionsFromDocx(string filepath = "")
/////Importiert Eigene Beschreibungen aus Word-Dokument
@ -1390,24 +1362,15 @@ namespace Gremlin_BlazorServer.Data.DBClasses
private static bool UpdateProductsFromCsv(string filepath = "", string separator = "|", bool dataHasHeading = true)
{
if (filepath == "")
{
//filepath = FileIO.GetFilepathFromUser(); //Pfad abfragen über Dtei-Öffnen-Dialog.
}
string fileName = ExtractFileName(filepath);
if (filepath == "")
{
return false; //Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch.
}
if (filepath == "") return false; //Wenn keine Datei ausgewählt (Cancel geklickt), dann Abbruch.
//Aktiven Produkte aus DB laden
using GremlinDb db = new();
using (GremlinDb gremlinDb = new())
{
//Aktive Produkte aus der DB einlesen
List<Product> activeProductsInDb = db.Products
.Where(p => p.DataStatus == Status.Active.ToString())
.Include(p => p.ProductLine)
.ToList();
List<Product> activeProductsInDb = gremlinDb.Products
.Where(p => p.DataStatus == Status.Active.ToString()).Include(p => p.ProductLine).ToList();
//Neue CPL einlesen...
List<Product> productsReadFromFile = new(ParseProductFile(filepath, separator, dataHasHeading));
@ -1420,6 +1383,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
ProductEqualityComparer proEc = new();
List<Product> obsoleteProducts = new(activeProductsInDb.Except(nonNewProducts, proEc));
DateTime now = DateTime.Now;
//Obsolete Produkte prozessieren
@ -1440,7 +1404,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
//int x = 0;
//Multithreading
_ = Parallel.ForEach(nonNewProducts, parallelOptions, (product) =>
Parallel.ForEach(nonNewProducts, parallelOptions, (product) =>
{
////Debugging-Counter
//x++;
@ -1479,7 +1443,8 @@ namespace Gremlin_BlazorServer.Data.DBClasses
existingProduct.ProductStatus = Status.PriceUpdated.ToString();
}
else if (Normalize(product.SapLongDescription) != Normalize(existingProduct.SapLongDescription)
|| Normalize(product.SapShortDescription) != Normalize(existingProduct.SapShortDescription))
|| Normalize(product.SapShortDescription) !=
Normalize(existingProduct.SapShortDescription))
{
existingProduct.ProductStatus = Status.DescriptionUpdated.ToString();
}
@ -1507,38 +1472,33 @@ namespace Gremlin_BlazorServer.Data.DBClasses
_ = MetaDataSetter.ForImport(updatedProduct, "CPL Updater", "Product Update");
updatedProduct.ProductLine = product.ProductLine.ProductLineCode == existingProduct.ProductLine.ProductLineCode
updatedProduct.ProductLine = product.ProductLine.ProductLineCode ==
existingProduct.ProductLine.ProductLineCode
? product.ProductLine
: ResolveProductLine(db, product.ProductLine.ProductLineCode);
: ResolveProductLine(gremlinDb, product.ProductLine.ProductLineCode);
newProducts.Add(updatedProduct);
}
updatedProducts.Add(existingProduct);
});
_ = InsertProducts(newProducts); //enthält auch ResolvePL()
db.Products.UpdateRange(obsoleteProducts);
db.Products.UpdateRange(updatedProducts);
int changes = db.SaveChanges();
gremlinDb.Products.UpdateRange(obsoleteProducts);
gremlinDb.Products.UpdateRange(updatedProducts);
int changes = gremlinDb.SaveChanges();
Debug.WriteLine($"Es wurden {changes} Änderungen an der Datenbank durchgeführt.\n Davon waren {updatedProducts.Count} UpdatedProducts, {obsoleteProducts.Count} ObsoleteProducts und {newProducts.Count} NewProducts");
return true;
}
}
private static Dictionary<string, int> ColumnMapping(string[] fields)
{
Dictionary<string, int> result = new();
for (int i = 0; i < fields.Length; i++)
{
switch (fields[i]
.ToLower(CultureInfo.CurrentCulture)
.Trim()
.Replace(" ", "")
.Replace("-", "")
.Replace("_", "")
.Replace(".", "")
.Replace(":", "")
)
switch (fields[i].ToLower(CultureInfo.CurrentCulture).Trim().Replace(" ", "").Replace("-", "").Replace("_", "").Replace(".", "").Replace(":", ""))
{
case "accountid" or "fcustomercd" or "sapaccountnumber":
result.Add("SAPAccountNumber", i);
@ -1656,7 +1616,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
return result;
}
private static List<Product> ParseProductFile(string filepath, string separator, bool dataHasHeading)
private static IEnumerable<Product> ParseProductFile(string filepath, string separator, bool dataHasHeading)
{
List<Product> results = new(100000);
//ENCODING CHANGED TO ISO-8859-1 AS EQUIVALENT (?) TO "LATIN1" (unavailable). TO BE TESTED!
@ -1667,10 +1627,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names:
if (dataHasHeading)
{
_ = csvParser.ReadLine();
}
if (dataHasHeading) csvParser.ReadLine();
//decimal oldListPrice;
//bool listpriceHasChanged;
@ -1721,14 +1678,14 @@ namespace Gremlin_BlazorServer.Data.DBClasses
importedProduct.ProductNumber = fields[1];
if (fields[2].Length == 4) //Optionsnummer mit führendem Apostroph
importedProduct.OptionNumber = fields[2].Length switch
{
importedProduct.OptionNumber = fields[2].Substring(1); //schneidet erstes Zeichen/Apostroph weg
}
else if (fields[2].Length == 3) //3-stellige Optionsnummer übernehmen; keine Aktion bei leerem Feld (keine Optionsnummer)
{
importedProduct.OptionNumber = fields[2];
}
//Optionsnummer mit führendem Apostroph
4 => fields[2][1..],
//3-stellige Optionsnummer übernehmen; keine Aktion bei leerem Feld (keine Optionsnummer)
3 => fields[2],
_ => importedProduct.OptionNumber
};
importedProduct.SapShortDescription = fields[3];
@ -1805,27 +1762,30 @@ namespace Gremlin_BlazorServer.Data.DBClasses
private static bool InsertProducts(List<Product> products)
{
using GremlinDb db = new();
List<ProductLine> productLines = db.ProductLines.ToList();
using (GremlinDb gremlinDb = new())
{
List<ProductLine> productLines = gremlinDb.ProductLines.ToList();
foreach (Product product in products)
{
product.ProductLine = productLines.Find(x => x.ProductLineCode == product.ProductLine.ProductLineCode) ?? new ProductLine();
_ = MetaDataSetter.ForImport(product, "CSVImporter", "Initial import by CSV Importer (Function DbHelper.ImportProductsFromCSV)");
product.ProductLine =
productLines.Find(x => x.ProductLineCode == product.ProductLine.ProductLineCode) ??
new ProductLine();
_ = MetaDataSetter.ForImport(product, "CSVImporter",
"Initial import by CSV Importer (Function DbHelper.ImportProductsFromCSV)");
}
db.Products.AddRange(products);
_ = db.SaveChanges();
gremlinDb.Products.AddRange(products);
_ = gremlinDb.SaveChanges();
//Bestätigung senden
// Debug.WriteLine($"Es wurden {products.Count} Produkte erfolgreich der Datenbank hinzugefügt.");
Debug.WriteLine($"Es wurden {products.Count} Produkte erfolgreich der Datenbank hinzugefügt.");
return true;
}
}
public static void DisplayErrorDetails(Exception ex, string errorRaiser)
{
string errorMessage = $"Source: {ex.Source}{Environment.NewLine}" + $"Message: {ex.Message}{Environment.NewLine}{Environment.NewLine}" + $"Contact: {errorRaiser}";
Debug.WriteLine(errorMessage);
// Debug.WriteLine(errorMessage);
Debug.WriteLine($"Source: {ex.Source}{Environment.NewLine}" + $"Message: {ex.Message}{Environment.NewLine}{Environment.NewLine}" + $"Contact: {errorRaiser}");
}
private static string ExtractFileName(string filepath, bool withExtension = false)
@ -1835,17 +1795,9 @@ namespace Gremlin_BlazorServer.Data.DBClasses
return withExtension ? fields[^1] : filename[0];
}
private static string Normalize(string input)
{
return input.ToLower()
.Trim()
.Replace(" ", "")
.Replace("-", "")
.Replace("_", "")
.Replace(".", "");
}
private static string Normalize(string input) => input.ToLower().Trim().Replace(" ", "").Replace("-", "").Replace("_", "").Replace(".", "");
private static List<Product> FilterNewProducts(List<Product> products)
private static IEnumerable<Product> FilterNewProducts(List<Product> products)
{
DateTime now = DateTime.Now;
@ -1906,12 +1858,6 @@ namespace Gremlin_BlazorServer.Data.DBClasses
catch { return new(); }
}
public static Account ResolveAccountById(GremlinDb db, string accountId)
{
try { return db.Accounts.First(account => account.SapAccountNumber == Convert.ToUInt32(accountId)); }
catch { return new(); }
}
public static AccountType ResolveAccountType(GremlinDb db, string accountTypeCode)
{
try { return db.AccountTypes.First(account => account.AccountTypeCode == accountTypeCode); }
@ -1923,17 +1869,6 @@ namespace Gremlin_BlazorServer.Data.DBClasses
try { return db.SubMarkets.First(submarket => submarket.SubMarketCode == subMarketCode); }
catch { return new(); }
}
public static Product GetProduct(GremlinDb db, string productNumber, string optionNumber)
{
try { return db.Products.Include(product => product.ProductLine).Include(product => product.CustomDescription).First(product => product.ProductNumber == productNumber && product.OptionNumber == optionNumber); }
catch { return new(); }
}
public static Product ResolveProduct(GremlinDb db, string productNumber, string option)
{
try { return db.Products.First(product => product.ProductNumber == productNumber && product.OptionNumber == option); }
catch { return new(); }
}
public static ProductLine ResolveProductLine(GremlinDb db, string productLineCode)
{
@ -1946,23 +1881,5 @@ namespace Gremlin_BlazorServer.Data.DBClasses
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return new(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
}
public static Contact GetContact(GremlinDb db, string lastName)
{
try { return db.Contacts.First(contact => contact.LastName == lastName); }
catch { return new(); }
}
public static Contact GetContact(GremlinDb db, uint contactId)
{
try { return db.Contacts.First(contact => contact.ContactId == contactId); }
catch { return new(); }
}
internal static List<Contact> GetAllContacts(GremlinDb db)
{
try { return db.Contacts.Where(contact => contact.LastName != "").ToList(); }
catch { return new(); }
}
}
}

@ -38,11 +38,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
try
{
_ = optionsBuilder
.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString))
//mySqlOptionsAction => mySqlOptionsAction.CharSetBehavior(Pomelo.EntityFrameworkCore.MySql.Infrastructure.CharSetBehavior.NeverAppend)).EnableDetailedErrors()
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)).EnableSensitiveDataLogging().EnableDetailedErrors();
}
catch (Exception ex)
{
@ -62,7 +58,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
////alle Fluent-Konfigurationen aufrufen:
//TO BE TESTED!
_ = modelBuilder.ApplyConfigurationsFromAssembly(typeof(GremlinDb).Assembly);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(GremlinDb).Assembly);
////Fluent-Konfiguration einzeln für eine Entity aufrufen:
//new AccountConfiguration().Configure(modelBuilder.Entity<Account>());

@ -9,21 +9,13 @@ namespace Gremlin_BlazorServer.Data.DBClasses
{
private static readonly DateTime farInTheFuture = DateTime.Parse("2050-12-31t00:00:00.000000z", CultureInfo.CurrentCulture);
public static IMetadata ForImport(
IMetadata entity,
string datamodifiedby = "",
string dataversioncomment = "",
[CallerMemberName] string callername = "")
public static IMetadata ForImport(IMetadata entity, string datamodifiedby = "", string dataversioncomment = "", [CallerMemberName] string callername = "")
{
_ = SetMetaData(entity, datamodifiedby, dataversioncomment, callername);
SetMetaData(entity, datamodifiedby, dataversioncomment, callername);
return entity;
}
private static IMetadata SetMetaData(
IMetadata entity,
string datamodifiedby = "",
string dataversioncomment = "",
[CallerMemberName] string callername = "")
private static IMetadata SetMetaData(IMetadata entity, string datamodifiedby = "", string dataversioncomment = "", [CallerMemberName] string callername = "")
{
entity.DataCreationDate = DateTime.Now;
entity.DataModificationDate = DateTime.Now;

@ -19,7 +19,7 @@ namespace Gremlin_BlazorServer.Data.DBClasses
{
if (product == null) { return 0; }
StringBuilder sb = new();
_ = sb.Append(product.ProductNumber).Append(product.OptionNumber).Append(product.BreakRangeFrom).Append(product.BreakRangeTo);
sb.Append(product.ProductNumber).Append(product.OptionNumber).Append(product.BreakRangeFrom).Append(product.BreakRangeTo);
return sb.ToString().GetHashCode();
}
}

@ -37,7 +37,7 @@ namespace Gremlin_BlazorServer.Services
{
try
{
account = await gremlinDb.Accounts.FirstOrDefaultAsync(a => a.AccountId.Equals(accountId));
account = await gremlinDb.Accounts.FirstAsync(a => a.AccountId.Equals(accountId));
}
catch (Exception e)
{

@ -5,13 +5,15 @@ namespace Gremlin_BlazorServer.Services.GUClasses
internal class DataIdentificator
{
//private readonly string _source; //Qualifier-Liste
private readonly Dictionary<string, int> mappingTable; //Mapping Spaltenzahl <-> Property/(übersetzte) Spaltenüberschrift
private readonly Dictionary<string, int>? mappingTable; //Mapping Spaltenzahl <-> Property/(übersetzte) Spaltenüberschrift
public List<DataIdType> DataTypes { get; set; } = new();
public DataIdentificator(Dictionary<string, int> mappingTable)
{
/*
mappingTable = mappingTable;
*/
//DataTypes populieren. Dazu: einlesen, nach DT qualifier in temp. Liste speichern, damit neuen DIDT erzeugen und zur Liste hinzufügen
Initialize();
}