public static List <Object> parseToList(string path) { using var sw = new StreamWriter(@"log.txt"); var fi = new FileInfo(path); var listOfStudent = new HashSet <Student>(new CustomComparer()); var listOfStudies = new List <ActiveStudies>(); Int32 count = 0; using (var stream = new StreamReader(fi.OpenRead())) { string line = null; while ((line = stream.ReadLine()) != null) { count++; string[] columns = line.Split(','); if (columns.Length < 9) { reportError($"Student with name{columns[0]} is not described properly"); } else { var name = columns[0]; var study = new Study { Name = columns[2], Mode = columns[3] }; var lastName = columns[1]; var index = columns[4]; var dateOfBirth = columns[5]; var email = columns[6]; var mothersName = columns[7]; var fathersName = columns[8]; var st = new Student { FirstName = name, LastName = lastName, Email = email, StudentIndex = index, Studies = study, DateOfBirth = DateTime.Parse(dateOfBirth), MothersName = mothersName, FathersName = fathersName }; var activeStudy = new ActiveStudies { Name = columns[2], Number = 1 }; if (!listOfStudent.Add(st)) { sw.WriteLine($"Student {name} was not added to the list"); } if (listOfStudies.Contains(activeStudy)) { Console.WriteLine("test"); listOfStudies.Find(x => x.GetName() == activeStudy.GetName()).Number++; sw.WriteLine($"{activeStudy.GetName()} was not added to the list"); } else { listOfStudies.Add(activeStudy); } } } } var list = new List <Object>(); list.Add(listOfStudent); list.Add(listOfStudies); return(list); }
static void Main(string[] args) { string path; string result; string dataFormat; string logPath = "log.txt"; var list = new List <Student>(); if (args.Length != 3) { path = @"Data/data.csv"; result = @"result.xml"; dataFormat = "xml"; } else { path = args[0]; result = args[1]; dataFormat = args[2]; } //If log file doesn't exist the follwing line creates it; if it does the line does nothing using (StreamWriter w = File.AppendText("log.txt")); //Wczytywanie pliku var fi = new FileInfo(path); try { using (var stream = new StreamReader(fi.OpenRead())) { string line = null; while ((line = stream.ReadLine()) != null) { string[] kolumny = line.Split(','); bool whitespace = false; bool duplicate = false; //Check if any column is whitespace for (int i = 0; i < kolumny.Length; i++) { if (String.IsNullOrWhiteSpace(kolumny[i])) { whitespace = true; } } //Check if there already is this student in a list foreach (Student student in list) { string index = "s" + kolumny[4]; if (string.Equals(student.Imie, kolumny[0]) && string.Equals(student.Nazwisko, kolumny[1]) && string.Equals(student.Indeks, index)) { duplicate = true; } } //If any column is missing ignore the line and write it to log file if (kolumny.Length != 9) { StreamWriter streamWriter = File.AppendText(logPath); streamWriter.WriteLine("Brak wszystkich danych: " + line); streamWriter.Close(); } //If any column is whitespace ignore it and write it to log file else if (kolumny.Length == 9 && whitespace == true) { StreamWriter streamWriter = File.AppendText(logPath); streamWriter.WriteLine("Brak wszystkich danych(kolumna zawiera znaki biale): " + line); streamWriter.Close(); } //If this studentInfo is a duplicate then ignore it and write it to log file else if (kolumny.Length == 9 && duplicate == true) { StreamWriter streamWriter = File.AppendText(logPath); streamWriter.WriteLine("Duplikat: " + line); streamWriter.Close(); } //All information is valid -> add it to the list else { Student student = new Student { Imie = kolumny[0], Nazwisko = kolumny[1], studies = new Studies(), Indeks = "s" + kolumny[4], Urodz = kolumny[5], Email = kolumny[6], ImieMatki = kolumny[7], ImieOjca = kolumny[8] }; student.studies.Kierunek = kolumny[2]; student.studies.Tryb = kolumny[3]; list.Add(student); } } } } catch (FileNotFoundException fileNotFoundException) { StreamWriter streamWriter = File.AppendText(logPath); streamWriter.WriteLine("Plik " + path + " nie istnieje"); streamWriter.Close(); Console.WriteLine("Plik " + path + " nie istnieje"); } //getting dictionary with unique activeStudies and their student numbers Dictionary <string, int> studentNumbers = getActiveStudiesDict(list); //putting unique activeStudies into an array Studies[] studies = new Studies[studentNumbers.Count]; int counter = 0; foreach (KeyValuePair <string, int> entry in studentNumbers) { studies[counter] = new Studies { activeStudiesName = entry.Key, numberOfStudents = ((int)entry.Value).ToString() }; counter++; } ActiveStudies activeStudies = new ActiveStudies() { studies = studies }; //combining final Uczelnia object to serialize Uczelnia uczelnia = new Uczelnia { createdAt = "13.03.2020", author = "Kamil Kojs", studenci = list, activeStudies = activeStudies }; //preparing fileStream to save XML to file FileStream writer = null; try { writer = new FileStream(result, FileMode.Create); } catch (ArgumentException argumentException) { StreamWriter streamWriter = File.AppendText(logPath); streamWriter.WriteLine("Podana sciezka jest niepoprawna"); streamWriter.Close(); Console.WriteLine("Podana sciezka jest niepoprawna"); } //preparing XML serializer var xns = new XmlSerializerNamespaces(); xns.Add(string.Empty, string.Empty); //If serializing in XML if (string.Equals("xml", dataFormat)) { XmlSerializer serializer = new XmlSerializer(typeof(Uczelnia)); serializer.Serialize(writer, uczelnia, xns); } }
public static void Main(string[] args) { var path = @"log.txt"; var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); fileStream.Close(); if (File.Exists(path)) { File.WriteAllText(path, string.Empty); } var draft = @"Data\data.csv"; var file = new FileInfo(draft); if (!file.Exists) { File.AppendAllText(path, "File does not exist!"); Console.Error.Write("File does not exist!"); Environment.Exit(1); throw new FileNotFoundException(); } FileStream writer = new FileStream(@"Result.xml", FileMode.Create); University u = new University() { Date = DateTime.Now.ToString("d"), Author = "Viktoriia Skorokhod" }; XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer serializer = new XmlSerializer(typeof(University)); int numberOfStudents0 = 0; int numberOfStudents1 = 0; int others = 0; using (var stream = new StreamReader(file.OpenRead())) { String line = null; while ((line = stream.ReadLine()) != null) { string[] student = line.Split(','); bool switching = true; while (switching) { for (int i = 0; i < student.Length; i++) { if (string.IsNullOrEmpty(student[i])) { string error = "Empty value found: " + line + Environment.NewLine; File.AppendAllText(path, error); break; } } var s0 = new Studies { Faculty = student[2], Mode = student[3] }; var s = new Student { Name = student[0], Surname = student[1], Index = student[4], Birthdate = DateTime.Parse(student[5]).ToString("dd MMMM yyyy hh:mm:ss tt"), Email = student[6], MothersName = student[7], FathersName = student[8], studies = s0 }; if (!u.students.Add(s)) { string error = "Dublicate found: " + line + Environment.NewLine; File.AppendAllText(path, error); } else { u.students.Add(s); if (s0.Faculty.StartsWith("Informatyka")) { numberOfStudents0++; } else if (s0.Faculty.StartsWith("Sztuka")) { numberOfStudents1++; } else { others++; } } break; } } } ActiveStudies a0 = new ActiveStudies { Name = "Computer Science", Count = numberOfStudents0 }; ActiveStudies a1 = new ActiveStudies { Name = "New Media Art", Count = numberOfStudents1 }; ActiveStudies a2 = new ActiveStudies { Name = "Other", Count = others }; u.activeStudies.Add(a0); u.activeStudies.Add(a1); u.activeStudies.Add(a2); Console.WriteLine("Final number od students added: " + u.students.Count + " souls"); serializer.Serialize(writer, u, ns); Console.WriteLine("log.txt -> ...\\bin\\Debug\\netcoreapp3.1\\log.txt" + "\n" + "Result.xml -> ... \\bin\\Debug\\netcoreapp3.1\\Result.xml"); Console.WriteLine("\nPROJECT SPONSOR: https://www.youtube.com/watch?v=8DMChMWAcCk"); }
public static List <Student> czytaj(string plikWejscie) { //LETS GETET STARTET YEE //string file = @"Data/dane.csv"; try { if (!File.Exists(plikWejscie)) { throw new FileNotFoundException("Plik nie istnieje"); } /*var regex = new Regex(@"[A-Z,a-z]\/[A-Z,a-z]\.csv"); * var name = plikWejscie.Substring(0, plikWejscie.LastIndexOf('v')); * if (!regex.IsMatch(name)) * throw * new ArgumentException("Podana ścieżka jest niepoprawna"); * * nwm czemu mi to nie dziala próbowalam to naprawic godzine * ale zakladam ze jak sciezka bedzie zla to wywali FileNotFoE */ //XLM //Wczytywaie pliku FileInfo f = new FileInfo(plikWejscie); using (StreamReader stream = new StreamReader(f.OpenRead())) { string line = ""; while ((line = stream.ReadLine()) != null) { string[] studentWiersz = line.Split(','); for (int i = 0; i < studentWiersz.Length; i += 9) { bool jakTam1 = sprawdzamStudenta(studentWiersz, line); if (jakTam1) { Studies s = new Studies { name = studentWiersz[2], mode = studentWiersz[3], }; var st = new Student { Imie = studentWiersz[i], Nazwisko = studentWiersz[i + 1], numer_indexu = "s" + studentWiersz[i + 4], data_urodzenia = studentWiersz[i + 5], Email = studentWiersz[i + 6], imie_matki = studentWiersz[i + 7], imie_ojca = studentWiersz[i + 8], studies = new Studies { name = studentWiersz[i + 2], mode = studentWiersz[i + 3] }, studKU = s }; list.Add(st); if (studKU.ContainsKey(s.name)) { studKU[s.name]++; } else { studKU.Add(s.name, 1); } } //kierynek 2,3 //index4 //uro5 //mail6 //mama7 //mode3 // stream.Dispose(); //.... IDisposible } // ... } ActiveStudies active = new ActiveStudies() { ACl = new List <AC>() }; foreach (KeyValuePair <string, int> entry in studKU) { AC a = new AC { name = entry.Key, number = entry.Value }; active.ACl.Add(a); } Uczelnia uczelnia = new Uczelnia { studenci = list, autor = "Patrycja Dankowska", czas = System.DateTime.Now.ToString(), activeStudies = active }; FileStream writer = new FileStream(@"data.xml", FileMode.Create); XmlSerializer serializer = new XmlSerializer(typeof(Uczelnia), new XmlRootAttribute("uczelnia")); serializer.Serialize(writer, uczelnia); Console.WriteLine(line + "zakonczenie robienia xml i log ,nacisnij enter i sprawdz bin"); } } catch (FileNotFoundException e) { Console.WriteLine(e); //throw; } catch (ArgumentException e1) { Console.WriteLine(e1); } return(list); }
static void Main(string[] args) { string fileInput = args.Length > 0 ? args[0] : @"C:\Users\Manius83pl\source\repos\Cw_2\Cw_2\Data\dane.csv"; string fileOutputPath = args.Length > 1 ? args[1] : @"C:\Users\Manius83pl\source\repos\Cw_2\Cw_2\Data\"; string dataFormat = args.Length > 2 ? args[2] : "xml"; //domyslny xml string logPath = @"C:\Users\Manius83pl\source\repos\Cw_2\Cw_2\Data\log.txt"; // Console.WriteLine(fileInput + "\n" + fileOutputPath + "\n" + dataFormat); try { if (!File.Exists(fileInput)) { throw new FileNotFoundException("File does not exist"); } if (!Directory.Exists(fileOutputPath)) { throw new ArgumentException("Wrong path"); } var list = new List <Student>(); University uczelnia = new University() { Author = "Mariusz Polak" }; using (var stream = new StreamReader(File.OpenRead(fileInput))) { string line = null; while ((line = stream.ReadLine()) != null) { string[] student = line.Split(','); // Console.WriteLine(line); var st = new Student { Index = student[4], First_Name = student[0], Last_Name = student[1], Birth_Date = student[5], Email = student[6], Mother_Name = student[7], Father_Name = student[8], Studies_Info = new Studies { Studies_Name = student[2], Studies_Mode = student[3] } }; // Console.WriteLine(student.Length.ToString()); if (student.Contains("")) { Console.WriteLine(st.ToString()); File.AppendAllText(logPath, st.ToString() + " : empty space in record\n"); } else if (student.Length > 9) { File.AppendAllText(logPath, st + " : not enough data\n"); } else { uczelnia.Students.Add(st); } if (uczelnia.Active_Studies != null) { foreach (ActiveStudies ac in uczelnia.Active_Studies) { if (ac.Name_of_Studies == student[2]) { Console.WriteLine(ac); } } } else { var activeStudies = new ActiveStudies { Name_of_Studies = student[2], Number_Of_Students = 1 }; //uczelnia.Active_Studies.Add(activeStudies); } } } if (dataFormat.Equals("json")) { var jsonString = JsonSerializer.Serialize(list); File.WriteAllText(fileOutputPath + "dane.json", jsonString); } else { FileStream writer = new FileStream(fileOutputPath + "dane.xml", FileMode.Create); XmlSerializer serializer = new XmlSerializer(typeof(University)); serializer.Serialize(writer, uczelnia); } } catch (ArgumentException ex) { Console.WriteLine("Wrong path"); File.AppendAllText(logPath, fileOutputPath + " : wrong path"); } catch (FileNotFoundException exx) { Console.WriteLine("File does not exist"); File.AppendAllText(logPath, fileInput + " : missing file"); } }
static void Main(string[] args) { //arrlist = list //set = hashset //map = dictionary string fileStart = CheckArgument1(args); string fileResult = CheckArgument2(args); string fileExtension = CheckArgument3(args); string fileLogs = "data/łog.txt"; StreamWriter streamWriter = new StreamWriter(fileLogs); FileInfo file = new FileInfo(fileStart); List <Student> studentList = new List <Student>(); Dictionary <string, int> stundetMap = new Dictionary <string, int>(); try { using (StreamReader stream = new StreamReader(file.OpenRead())) { string line = ""; while ((line = stream.ReadLine()) != null) { Console.WriteLine(line); string[] student = line.Split(","); Console.WriteLine(line); if (checkData(student)) { var kierunek = new Kierunek { nazwa = student[2], tryb = student[3], }; Student student1 = new Student { Imie = student[0], Nazwisko = student[1], Index = int.Parse(student[4]), Kierunek = kierunek, DataUrodzenia = student[5], Email = student[6], Ojciec = student[8], Matka = student[7] }; studentList.Add(student1); if (stundetMap.ContainsKey(kierunek.nazwa)) { stundetMap[kierunek.nazwa]++; } else { stundetMap.Add(kierunek.nazwa, 1); } } else { streamWriter.WriteLine("Zle podane dane : " + line); } } } }catch (FileNotFoundException) { Console.WriteLine("Plik nazwa nie istnieje"); streamWriter.WriteLine("Plik nazwa nie istnieje"); return; }catch (ArgumentException) { Console.WriteLine("Podana ścieżka jest niepoprawna"); streamWriter.WriteLine("Podana ścieżka jest niepoprawna"); return; }catch (Exception e3) { Console.WriteLine(e3.Message); streamWriter.WriteLine(e3.Message); return; } streamWriter.Flush(); streamWriter.Close(); ActiveStudies activeSt = new ActiveStudies() { activeStudies = new List <ActiveStudie>() }; foreach (KeyValuePair <string, int> entry in stundetMap) { activeSt.activeStudies.Add(new ActiveStudie { name = entry.Key, number = entry.Value }); } Students students = new Students { Student = studentList.Distinct(new EqualityComp()).ToList <Student>() }; Uczelnia uczelnia = new Uczelnia { data = "14.03.2020", autor = "Alvan Maksym", student = students, activeStudies = activeSt, }; FileStream writer = new FileStream(fileExtension, FileMode.Create); XmlSerializer serializer = new XmlSerializer(typeof(Uczelnia)); XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add("", ""); serializer.Serialize(writer, uczelnia, namespaces); }
static void Main(string[] args) { var input = args.Length > 0 ? args[0] : @"Files\dane.csv"; //@"Files\dane.csv" var output = args.Length > 1 ? args[1] : @"Files\result.xml"; // var form = args.Length > 2 ? args[2] : "xml"; try { var university = new Uczelnia() { Author = "Gabriel Sek", }; foreach (var line in File.ReadAllLines(input)) { var array = line.Split(","); if (array.Length < 9) { File.AppendAllText("Log.txt", $"{DateTime.UtcNow} Invalid number of students arguments" + "\n"); } if (array[0] == "" || array[1] == "" || array[2] == "" || array[3] == "" || array[4] == "" || array[5] == "" || array[6] == "" || array[7] == "" || array[8] == "") { File.AppendAllText("Log.txt", $"{DateTime.UtcNow} Empty brackets!!!" + "\n"); } var stud = new Student { id = array[4], fname = array[0], lname = array[1], birthdate = array[5], email = array[6], mothersName = array[7], fathersName = array[8], studies = new Studies { name = array[2], mode = array[3] } }; if (!university.Students.Contains(stud)) { university.Students.Add(stud); } var actStudies = new ActiveStudies { name = array[2], count = 1 }; if (!university.activeStudies.Contains(actStudies)) { university.activeStudies.Add(actStudies); } else { foreach (ActiveStudies temp in university.activeStudies) { if (temp.Equals(actStudies)) { temp.count++; } } } } if (form.Equals("xml")) { using var writer = new FileStream($"{output}", FileMode.Create); var serializer = new XmlSerializer(typeof(Uczelnia)); serializer.Serialize(writer, university); } else if (form.Equals("json")) { using var writer = new FileStream($"{output}", FileMode.Create); var options = new JsonSerializerOptions { WriteIndented = true, IgnoreNullValues = true } ; var serializer = JsonSerializer.Serialize(university, options); File.WriteAllText($"{output}", serializer); } else { File.AppendAllText("Log.txt", $"{DateTime.UtcNow} not supported form" + "\n"); } } catch (FileNotFoundException e) { File.AppendAllText("Log.txt", $"{DateTime.UtcNow} {e.Message} {e.FileName}" + "\n"); } catch (ArgumentException e) { File.AppendAllText("Log.txt", $"{DateTime.UtcNow} {e.Message} {e.ParamName}" + "\n"); } }
public static void readFile(string initPath, string finPath, string finalFormat) { var listOfStudents = new HashSet <Student>(new CustomComparer()); var activeStudies = new HashSet <ActiveStudies>(new ActiveStudiesComparer()); var fi = new FileInfo(initPath); try { using (var stream = new StreamReader(fi.OpenRead())) { string line = null; //Check if line exist, because if line == null it means that we have reached the end of the file while ((line = stream.ReadLine()) != null) { var columns = line.Split(','); if (columns.Length < 9) { issueWhileReading(columns); } if (columns.Any(string.IsNullOrWhiteSpace)) { issueWhileReading(columns); continue; } //Creates new objects var newStudent = new Student(columns[4], columns[0], columns[1], columns[5], columns[6], columns[7], columns[8]); var studies = new Studies(columns[2], columns[3]); var possibleActiveStudy = new ActiveStudies(studies); //appends studies to new Student newStudent.appendStudies(studies); //tries to add student to list of student //if exists then appends additional studies to the existing student if (!listOfStudents.Add(newStudent)) { try { throw new DuplicateMemberException(newStudent); } catch (System.Exception) { } var studentToUpdate = listOfStudents.First(stu => stu.IndexNumber == newStudent.IndexNumber); studentToUpdate.appendStudies(studies); } //tries to add active study //if exist then increases the number of students by 1 if (!activeStudies.Add(possibleActiveStudy)) { var studyToUpdate = activeStudies.First(active => active.StudyName == possibleActiveStudy.StudyName); studyToUpdate.increaseNumberOfStudents(); } } } } catch (ArgumentNullException ex) { IReporter reporter = new Reporter(); reporter.Report(ex, $"ERROR: Incorrect path: {initPath}", SecurityLevel.Error); } catch (FileNotFoundException ex) { IReporter reporter = new Reporter(); reporter.Report(ex, $"ERROR: File does not exist: {initPath}", SecurityLevel.Error); } //adding students to the university University university = new University(listOfStudents, activeStudies); if (finalFormat.Equals("xml", StringComparison.OrdinalIgnoreCase)) { new XmlFormatter().Save(university); } else { new JsonFormatter().Serialize(university); } //Exception reporting void issueWhileReading(string[] columns) { try { var str = new StringBuilder(); str.Append(columns); throw new InvalidNumberOfPersonArguments(str.ToString()); } catch (System.Exception e) { } } }