Lösungsvariante hinzugefügt
This commit is contained in:
parent
b5daf727d0
commit
6a05c7b75b
Binary file not shown.
Binary file not shown.
@ -24,7 +24,7 @@
|
||||
"RelativeDocumentMoniker": "Projekt_Calcan_Conze\\Program.cs",
|
||||
"ToolTip": "C:\\Jan_bib_Module\\PMC\\Projekt\\Projekt_Calcan_Conze\\Projekt_Calcan_Conze\\Program.cs",
|
||||
"RelativeToolTip": "Projekt_Calcan_Conze\\Program.cs",
|
||||
"ViewState": "AQIAACkAAAAAAAAAAAAAwDcAAAAgAAAA",
|
||||
"ViewState": "AQIAAFIAAAAAAAAAAAAqwGAAAABAAAAA",
|
||||
"Icon": "ae27a6b0-e345-4288-96df-5eaf394ee369.000738|",
|
||||
"WhenOpened": "2024-05-24T09:06:25.212Z",
|
||||
"EditorCaption": ""
|
||||
|
@ -47,7 +47,7 @@ class Program
|
||||
MySql.Data.MySqlClient.MySqlConnection myConnection;
|
||||
string myConnectionString;
|
||||
//set the correct values for your server, user, password and database name
|
||||
myConnectionString = "server=localhost;uid=root;pwd=root;database=import_export"; //ID eventuell von phpMyAdmin ziehen?
|
||||
myConnectionString = "server=localhost;uid=root;pwd=root;database=import_export"; //Hier greife ich auf import_export zu
|
||||
|
||||
try
|
||||
{
|
||||
@ -59,15 +59,16 @@ class Program
|
||||
MySqlCommand myCommand = new MySqlCommand();
|
||||
myCommand.Connection = myConnection;
|
||||
// myCommand.CommandText = @"SELECT * FROM workshop WHERE maxParticipants = @code;";
|
||||
|
||||
//Selber eingefügt ab hier
|
||||
myCommand.CommandText = @"SELECT * FROM user";
|
||||
myCommand.CommandText = @"SELECT * FROM user"; //Hier tragen wir unsere SELECT ein
|
||||
//Hier ende
|
||||
|
||||
// myCommand.Parameters.AddWithValue("@code", "12");
|
||||
|
||||
// execute the command and read the results
|
||||
using MySqlDataReader myReader = myCommand.ExecuteReader();
|
||||
|
||||
|
||||
//Hier dann den CSV Reader benutzen?
|
||||
while (myReader.Read())
|
||||
{
|
||||
@ -83,7 +84,7 @@ class Program
|
||||
|
||||
}
|
||||
|
||||
//Consolen-Ausgabe und Abfrage
|
||||
//Consolen-Ausgabe und Abfrage Eventuell hoch in das While schieben
|
||||
|
||||
Console.WriteLine("Willkommen");
|
||||
Console.Write("Bitte geben Sie nun die Kundenummer ein: ");
|
||||
@ -93,177 +94,263 @@ class Program
|
||||
|
||||
string filePath = "path/to/your/" + dateiBezeichnung; //Wo wird die CSV vor dem einlesen abgelegt? Extra Ordner dafür erstellen
|
||||
|
||||
//Überprüfung einbauen, ob die Datei exisitiert mit if()
|
||||
//Überprüfung, ob die Datei exisitiert mit File.Exists()
|
||||
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
Console.WriteLine("Die Datei-Parameter konnten nicht gefunden werden. Bitte versuche es erneut");
|
||||
}
|
||||
|
||||
|
||||
//Schwierigkeit: Bei User beginnen und dann alle anderen Tabellen durch Foreign Keys verbinden/verweisen
|
||||
//Procedure INSERT anschauen - Elegante Lösung
|
||||
//Auto Increment beachten
|
||||
|
||||
//Umsetzung mit Arrays: Beginnend mit durchzählen für Länge Array, Dann unterteilung in Blöcken
|
||||
//(CSV Datei einteilen vor Herr/Frau) , Dann erstellung Tabelle User, dann Andere Tabellen mit Foreign Keys verbinden
|
||||
//Umsetzung mit Arrays: Beginnend mit durchzählen für Länge Array, darauffolgende Unterteilung in Blöcken
|
||||
//(CSV Datei einteilen: (Beginnend immer mit Herr/Frau) , dann Erstellung Tabelle User, dann andere Tabellen mit Foreign Keys verknüpfen
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
*
|
||||
* Die wunderbare Lösung von unserem Kollegen. Nicht getestet aber an den Ansätzen können wir uns orientieren
|
||||
*
|
||||
/* Das hier wäre eine Lösungsvariante. Diese beruht auf den vorhandenen Daten
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
if (args.Length != 2)
|
||||
{
|
||||
Console.WriteLine("Usage: ImportUsers <csv-file> <customer-id>");
|
||||
return;
|
||||
}
|
||||
// Connection zum Server
|
||||
string myConnectionString = "server=localhost;uid=root;pwd=root;database=import_export";
|
||||
|
||||
string filePath = args[0];
|
||||
string customerId = args[1];
|
||||
Console.WriteLine("Willkommen");
|
||||
Console.Write("Bitte geben Sie nun die Kundennummer ein: ");
|
||||
string kundennummer = Console.ReadLine();
|
||||
Console.Write("Bitte geben Sie die Datei-Parameter ein: ");
|
||||
string dateiBezeichnung = Console.ReadLine();
|
||||
|
||||
string filePath = "path/to/your/" + dateiBezeichnung; // Adjust the path to your CSV file
|
||||
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
Console.WriteLine("File does not exist.");
|
||||
Console.WriteLine("Die Datei-Parameter konnten nicht gefunden werden. Bitte versuche es erneut");
|
||||
return;
|
||||
}
|
||||
|
||||
var users = ReadCsvFile(filePath);
|
||||
var invalidUsers = new List<string>();
|
||||
var validUsers = new List<User>();
|
||||
List<string> invalidEntries = new List<string>();
|
||||
List<string> existingEntries = new List<string>();
|
||||
|
||||
foreach (var user in users)
|
||||
// Einlesen der CSV-Datei und Verarbeitung der Daten
|
||||
string[] lines = File.ReadAllLines(filePath);
|
||||
List<User> users = ParseCsv(lines, invalidEntries);
|
||||
|
||||
using (MySqlConnection myConnection = new MySqlConnection(myConnectionString))
|
||||
{
|
||||
if (ValidateUser(user, out string validationError))
|
||||
myConnection.Open();
|
||||
|
||||
foreach (User user in users)
|
||||
{
|
||||
if (!IsUserAlreadyExists(user, customerId))
|
||||
// Überprüfen, ob der Nutzer bereits existiert
|
||||
if (UserExists(myConnection, user, kundennummer))
|
||||
{
|
||||
validUsers.Add(user);
|
||||
existingEntries.Add($"{user.Firstname} {user.Lastname}, {user.Email}");
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
invalidUsers.Add($"User already exists: {user.FirstName} {user.LastName}, Email: {user.Email}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
invalidUsers.Add(validationError);
|
||||
|
||||
// Nutzer einfügen
|
||||
InsertUser(myConnection, user, kundennummer);
|
||||
}
|
||||
}
|
||||
|
||||
ImportValidUsers(validUsers, customerId);
|
||||
LogInvalidUsers(invalidUsers);
|
||||
// Ungültige und bereits vorhandene Einträge protokollieren
|
||||
LogEntries("invalid_entries.log", invalidEntries);
|
||||
LogEntries("existing_entries.log", existingEntries);
|
||||
|
||||
Console.WriteLine("Import completed.");
|
||||
Console.WriteLine("Import abgeschlossen.");
|
||||
}
|
||||
|
||||
static List<User> ReadCsvFile(string filePath)
|
||||
static List<User> ParseCsv(string[] lines, List<string> invalidEntries)
|
||||
{
|
||||
var users = new List<User>();
|
||||
var lines = File.ReadAllLines(filePath);
|
||||
List<User> users = new List<User>();
|
||||
User currentUser = null;
|
||||
|
||||
foreach (var line in lines)
|
||||
foreach (string line in lines)
|
||||
{
|
||||
var columns = line.Split(',');
|
||||
string[] parts = line.Split(';');
|
||||
|
||||
var user = new User
|
||||
if (parts[0] == "Herr" || parts[0] == "Frau")
|
||||
{
|
||||
Salutation = columns[0],
|
||||
FirstName = columns[1],
|
||||
LastName = columns[2],
|
||||
BirthDate = columns[3],
|
||||
Street = columns[4],
|
||||
PostalCode = columns[5],
|
||||
City = columns[6],
|
||||
Email = columns[7],
|
||||
PhoneNumbers = columns.Skip(8).ToList()
|
||||
if (currentUser != null)
|
||||
{
|
||||
users.Add(currentUser);
|
||||
}
|
||||
currentUser = new User
|
||||
{
|
||||
Gender = parts[0],
|
||||
Firstname = parts[1],
|
||||
Lastname = parts[2],
|
||||
Birthdate = parts[3]
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
users.Add(user);
|
||||
if (parts[0] == "Adresse" && currentUser != null)
|
||||
{
|
||||
currentUser.Address = new Address
|
||||
{
|
||||
Street = parts[1],
|
||||
PostalCode = parts[2],
|
||||
City = parts[3]
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (parts[0] == "E-Mail" && currentUser != null)
|
||||
{
|
||||
currentUser.Email = parts[1];
|
||||
if (!IsValidEmail(currentUser.Email))
|
||||
{
|
||||
invalidEntries.Add($"Ungültige E-Mail: {currentUser.Email}");
|
||||
currentUser = null;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (parts[0] == "Telefon" && currentUser != null)
|
||||
{
|
||||
if (!IsValidPhone(parts[1], parts[2]))
|
||||
{
|
||||
invalidEntries.Add($"Ungültige Telefonnummer: {parts[1]} {parts[2]}");
|
||||
currentUser = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
currentUser.Phones.Add(new Phone
|
||||
{
|
||||
Prefix = parts[1],
|
||||
Number = parts[2]
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentUser != null)
|
||||
{
|
||||
users.Add(currentUser);
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
static bool ValidateUser(User user, out string error)
|
||||
static bool IsValidEmail(string email)
|
||||
{
|
||||
error = string.Empty;
|
||||
DateTime birthDate;
|
||||
|
||||
if (!DateTime.TryParseExact(user.BirthDate, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate))
|
||||
try
|
||||
{
|
||||
error = $"Invalid birth date: {user.BirthDate}";
|
||||
return false;
|
||||
var addr = new System.Net.Mail.MailAddress(email);
|
||||
return addr.Address == email;
|
||||
}
|
||||
|
||||
if (!Regex.IsMatch(user.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
|
||||
catch
|
||||
{
|
||||
error = $"Invalid email: {user.Email}";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!Regex.IsMatch(user.PostalCode, @"^\d{5}$"))
|
||||
{
|
||||
error = $"Invalid postal code: {user.PostalCode}";
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var phone in user.PhoneNumbers)
|
||||
{
|
||||
var parts = phone.Split('-');
|
||||
if (parts.Length != 2 || !Regex.IsMatch(parts[0], @"^\d{3,5}$") || !Regex.IsMatch(parts[1], @"^\d{4,10}$"))
|
||||
{
|
||||
error = $"Invalid phone number: {phone}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
static bool IsValidPhone(string prefix, string number)
|
||||
{
|
||||
return Regex.IsMatch(prefix, @"^\d{3,5}$") && Regex.IsMatch(number, @"^\d{4,10}$");
|
||||
}
|
||||
|
||||
static bool IsUserAlreadyExists(User user, string customerId)
|
||||
static bool UserExists(MySqlConnection connection, User user, string clientId)
|
||||
{
|
||||
// Hier sollte die Logik implementiert werden, um zu prüfen, ob der Nutzer bereits in der Datenbank vorhanden ist.
|
||||
// Dies ist ein Platzhalter für die tatsächliche Überprüfung in der Datenbank.
|
||||
return false;
|
||||
string query = @"SELECT COUNT(*) FROM user WHERE firstname = @firstname AND lastname = @lastname AND clientId = @clientId";
|
||||
MySqlCommand cmd = new MySqlCommand(query, connection);
|
||||
cmd.Parameters.AddWithValue("@firstname", user.Firstname);
|
||||
cmd.Parameters.AddWithValue("@lastname", user.Lastname);
|
||||
cmd.Parameters.AddWithValue("@clientId", clientId);
|
||||
return Convert.ToInt32(cmd.ExecuteScalar()) > 0;
|
||||
}
|
||||
|
||||
static void ImportValidUsers(List<User> users, string customerId)
|
||||
static void InsertUser(MySqlConnection connection, User user, string clientId)
|
||||
{
|
||||
// Hier sollte die Logik implementiert werden, um die gültigen Nutzer in die Datenbank zu importieren.
|
||||
// Dies ist ein Platzhalter für den tatsächlichen Datenbankimport.
|
||||
string query = @"INSERT INTO user (clientId, genderId, firstname, lastname, birthdate) VALUES (@clientId, @genderId, @firstname, @lastname, @birthdate)";
|
||||
MySqlCommand cmd = new MySqlCommand(query, connection);
|
||||
cmd.Parameters.AddWithValue("@clientId", clientId);
|
||||
cmd.Parameters.AddWithValue("@genderId", user.Gender == "Herr" ? 1 : (user.Gender == "Frau" ? 2 : 3));
|
||||
cmd.Parameters.AddWithValue("@firstname", user.Firstname);
|
||||
cmd.Parameters.AddWithValue("@lastname", user.Lastname);
|
||||
cmd.Parameters.AddWithValue("@birthdate", DateTime.ParseExact(user.Birthdate, "dd.MM.yyyy", CultureInfo.InvariantCulture));
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
long userId = cmd.LastInsertedId;
|
||||
|
||||
if (user.Address != null)
|
||||
{
|
||||
query = @"INSERT INTO address (userId, street, postalcode, city) VALUES (@userId, @street, @postalcode, @city)";
|
||||
cmd = new MySqlCommand(query, connection);
|
||||
cmd.Parameters.AddWithValue("@userId", userId);
|
||||
cmd.Parameters.AddWithValue("@street", user.Address.Street);
|
||||
cmd.Parameters.AddWithValue("@postalcode", user.Address.PostalCode);
|
||||
cmd.Parameters.AddWithValue("@city", user.Address.City);
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
static void LogInvalidUsers(List<string> invalidUsers)
|
||||
if (!string.IsNullOrEmpty(user.Email))
|
||||
{
|
||||
using (StreamWriter sw = new StreamWriter("invalid_users.log"))
|
||||
{
|
||||
foreach (var error in invalidUsers)
|
||||
{
|
||||
sw.WriteLine(error);
|
||||
query = @"INSERT INTO email (userId, email) VALUES (@userId, @Email)";
|
||||
cmd = new MySqlCommand(query, connection);
|
||||
cmd.Parameters.AddWithValue("@userId", userId);
|
||||
cmd.Parameters.AddWithValue("@Email", user.Email);
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
foreach (var phone in user.Phones)
|
||||
{
|
||||
query = @"INSERT INTO phone (userId, phoneprefix, phonenumber) VALUES (@userId, @phoneprefix, @phonenumber)";
|
||||
cmd = new MySqlCommand(query, connection);
|
||||
cmd.Parameters.AddWithValue("@userId", userId);
|
||||
cmd.Parameters.AddWithValue("@phoneprefix", phone.Prefix);
|
||||
cmd.Parameters.AddWithValue("@phonenumber", phone.Number);
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
static void LogEntries(string filePath, List<string> entries)
|
||||
{
|
||||
if (entries.Count > 0)
|
||||
{
|
||||
File.AppendAllLines(filePath, entries);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class User
|
||||
{
|
||||
public string Salutation { get; set; }
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
public string BirthDate { get; set; }
|
||||
public string Gender { get; set; }
|
||||
public string Firstname { get; set; }
|
||||
public string Lastname { get; set; }
|
||||
public string Birthdate { get; set; }
|
||||
public Address Address { get; set; }
|
||||
public string Email { get; set; }
|
||||
public List<Phone> Phones { get; set; } = new List<Phone>();
|
||||
}
|
||||
|
||||
class Address
|
||||
{
|
||||
public string Street { get; set; }
|
||||
public string PostalCode { get; set; }
|
||||
public string City { get; set; }
|
||||
public string Email { get; set; }
|
||||
public List<string> PhoneNumbers { get; set; }
|
||||
}
|
||||
*/
|
||||
|
||||
class Phone
|
||||
{
|
||||
public string Prefix { get; set; }
|
||||
public string Number { get; set; }
|
||||
}
|
||||
|
||||
*/
|
@ -14,7 +14,7 @@ using System.Reflection;
|
||||
[assembly: System.Reflection.AssemblyCompanyAttribute("Projekt_Calcan_Conze")]
|
||||
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
|
||||
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+5be00c2e03258059442828eb121b209b9abc8ce5")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+b5daf727d036da56b4f0ec7d625674d7d8d44a73")]
|
||||
[assembly: System.Reflection.AssemblyProductAttribute("Projekt_Calcan_Conze")]
|
||||
[assembly: System.Reflection.AssemblyTitleAttribute("Projekt_Calcan_Conze")]
|
||||
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
|
||||
|
@ -1 +1 @@
|
||||
4b22627745609a314655206a5a1750317c1cb42a093f5d4808d42383331c33bf
|
||||
e39a290590c7cc4b23572b44b843d3323f8e88ed187de9f169fba7cecdea222d
|
||||
|
Loading…
Reference in New Issue
Block a user