Exemplo n.º 1
0
        public static void save(Uczelnia uczelnia, string adresDolcelowy)
        {
            FileStream    writer     = new FileStream(adresDolcelowy + "result.xml", FileMode.Create);
            XmlSerializer serializer = new XmlSerializer(typeof(Uczelnia), new XmlRootAttribute("uczelnia"));

            serializer.Serialize(writer, uczelnia);
        }
Exemplo n.º 2
0
        public static void save(Uczelnia uczelniaTmp, string adresDolcelowy)
        {
            var dodajNaglowek = new
            {
                uczelnia = uczelniaTmp
            };
            var jsonString = JsonSerializer.Serialize(dodajNaglowek);

            File.WriteAllText(String.Concat(adresDolcelowy + "result.json"), jsonString, System.Text.Encoding.UTF8);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            string inputDestination  = @"dane.csv";
            string outputDestination = @"result.xml";
            string dataType          = "xml";

            if (args.Length == 3)
            {
                inputDestination  = args[0];
                outputDestination = args[1];
                dataType          = args[3];
            }

            try
            {
                if (dataType.Equals("xml"))
                {
                    var studentsList = handleData(inputDestination);
                    var uczelnia     = new Uczelnia
                    {
                        createdAt = $"{ DateTime.Now}",
                        author    = "Hubert Janoszka",
                        students  = studentsList
                    };


                    FileStream writer = new FileStream(outputDestination, FileMode.Create);

                    XmlSerializer serializer = new XmlSerializer(typeof(Uczelnia),
                                                                 new XmlRootAttribute("uczelnia"));
                    serializer.Serialize(writer, uczelnia);
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
                string error = "Podana ścieżka jest niepoprawna.";
                errorLog(error);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
                string error = $"Plik {inputDestination} nie istnieje.";
                errorLog(error);
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            var adress       = args.Length > 1 ? args[0] : @"dane.csv";
            var resultAdress = args.Length > 2 ? args[1] : @"result.xml";
            var resultType   = args.Length > 3 ? args[2] : "xml";
            var logAdress    = "log.txt";
            var today        = DateTime.Now.ToString("dd.MM.yyyy");

            try
            {
                var lines    = File.ReadLines(adress);
                var students = new HashSet <Student>(new OwnComparer());
                Dictionary <string, int> activeStdCount = new Dictionary <string, int>();

                using (var log = new StreamWriter(logAdress))
                {
                    foreach (var line in lines)
                    {
                        var  data    = line.Split(",");
                        bool correct = true;
                        foreach (var item in data)
                        {
                            if (string.IsNullOrEmpty(item) || string.IsNullOrWhiteSpace(item))
                            {
                                correct = false;
                            }
                        }
                        if (!correct)
                        {
                            log.WriteLine("Puste dane " + line);
                        }
                        else if (correct && data.Length < 9)
                        {
                            log.WriteLine("Dane za krótkie " + line);
                        }
                        else
                        {
                            if (!activeStdCount.ContainsKey(data[2]))
                            {
                                activeStdCount.Add(data[2], 1);
                            }
                            else
                            {
                                activeStdCount[data[2]]++;
                            }

                            var studies = new Studies {
                                StudiesName = data[2], StudiesMode = data[3]
                            };
                            var student = new Student
                            {
                                FirstName   = data[0],
                                SecondtName = data[1],
                                Studies     = studies,
                                IndexNumber = "s" + data[4],
                                Birthdate   = DateTime.Parse(data[5]),
                                Email       = data[6],
                                MotherName  = data[7],
                                FathersName = data[8],
                            };
                            if (!students.Add(student))
                            {
                                log.WriteLine("Student się powtarza " + line);
                            }
                        }
                    }
                }

                var activeStd = new List <ActiveStudies>();
                foreach (var item in activeStdCount)
                {
                    activeStd.Add(new ActiveStudies {
                        id = item.Key, value = item.Value
                    });
                }

                var uczelnia = new Uczelnia
                {
                    createdAt     = today,
                    studenci      = students,
                    activeStudies = activeStdCount
                };

                if (resultType == "xml")
                {
                    XDocument doc = new XDocument(new XElement("university",
                                                               new XAttribute("createdAt", today),
                                                               new XAttribute("author", "Piotr Dębowski"),
                                                               new XElement("studenci",
                                                                            from student in students
                                                                            select new XElement("student",
                                                                                                new XAttribute("indexNumber", student.IndexNumber),
                                                                                                new XElement("name", student.FirstName),
                                                                                                new XElement("secondName", student.SecondtName),
                                                                                                new XElement("birthdate", student.Birthdate),
                                                                                                new XElement("email", student.Email),
                                                                                                new XElement("mothersName", student.MotherName),
                                                                                                new XElement("fathersName", student.FathersName),
                                                                                                new XElement("studies",
                                                                                                             new XElement("name", student.Studies.StudiesName),
                                                                                                             new XElement("mode", student.Studies.StudiesMode)
                                                                                                             ))),
                                                               new XElement("activeStudies",
                                                                            from asc in activeStdCount
                                                                            select new XElement("studies",
                                                                                                new XAttribute("name", asc.Key),
                                                                                                new XAttribute("numberOfStudents", asc.Value)
                                                                                                )
                                                                            )));
                    doc.Save(resultAdress);

                    //var ns = new XmlSerializerNamespaces();
                    //ns.Add("", "");
                    //FileStream writer = new FileStream(resultAdress, FileMode.Create);
                    //XmlSerializer serializer = new XmlSerializer(typeof(Uczelnia), new XmlRootAttribute("uczelnia"));
                    //serializer.Serialize(writer, uczelnia, ns);
                }
                else if (resultType == "json")
                {
                    var json = JsonConvert.SerializeObject(uczelnia, (Newtonsoft.Json.Formatting)Formatting.Indented);
                    File.WriteAllText(resultAdress + ".json", json);
                }
            } catch (FileNotFoundException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            } catch (ArgumentException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            } catch (IOException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            try
            {
                String adresCSV = Console.ReadLine(); //C:\Users\kfaff\OneDrive\Desktop\APBD\2_csvtoxml\dane.csv
                if (String.IsNullOrEmpty(adresCSV))
                {
                    adresCSV = "data.csv";
                }

                String adresDolcelowy = Console.ReadLine(); //D:\APBD\cw2\
                if (String.IsNullOrEmpty(adresDolcelowy))
                {
                    adresDolcelowy = "";
                }

                String formatDanych = Console.ReadLine(); //xml
                if (String.IsNullOrEmpty(formatDanych))
                {
                    formatDanych = "xml";
                }

                if (File.Exists(adresCSV) && Directory.Exists(adresDolcelowy))
                {
                    string[] source = File.ReadAllLines(adresCSV);
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    for (int i = 0; i < source.Length; i++)
                    {
                        try
                        {
                            if (source[i].Split(",").Length == 9)
                            {
                                string tmp2 = "";
                                string tmp3 = "";
                                bool   czyNiePustaKolumna = true;
                                for (int j = 0; j < 9; j++)
                                {
                                    if (source[i].Split(",")[j].Equals(" ") || source[i].Split(",")[j].Equals(""))
                                    {
                                        czyNiePustaKolumna = false;
                                    }

                                    if (j == 0 || j == 1 || j == 4)
                                    {
                                        tmp2 += source[i].Split(",")[j] + ",";
                                    }
                                    else
                                    {
                                        if (j == 8)
                                        {
                                            tmp3 += source[i].Split(",")[j];
                                        }
                                        else
                                        {
                                            tmp3 += source[i].Split(",")[j] + ",";
                                        }
                                    }
                                }

                                if (czyNiePustaKolumna)
                                {
                                    try
                                    {
                                        dictionary.Add(tmp2, tmp3);
                                    }
                                    catch (ArgumentException e)
                                    {
                                        ErrorLOgging(new Exception("Powtarzający się student!" + source[i]));
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception("Błędne informacje o studencie!" + source[i]);
                            }
                        }
                        catch (Exception ex)
                        {
                            ErrorLOgging(ex);
                        }
                    }
                    int           k   = 0;
                    List <string> tmp = new List <string>();
                    foreach (var keyAndVal in dictionary)
                    {
                        tmp.Add(keyAndVal.Key + keyAndVal.Value);
                        k++;
                    }
                    string[]       filtred  = tmp.ToArray();
                    List <Student> students = new List <Student>();
                    for (int i = 0; i < filtred.Length; i++)
                    {
                        string[] str = filtred[i].Split(",");
                        students.Add(new Student(str[2], str[0], str[1], new DateTime(Int32.Parse(str[5].Split("-")[0]), Int32.Parse(str[5].Split("-")[1]), Int32.Parse(str[5].Split("-")[2])), str[6], str[7], str[8], new Studies(str[3], str[4])));
                    }
                    Uczelnia uczelnia = new Uczelnia(students);
                    switch (formatDanych)
                    {
                    case "xml":
                    {
                        xmlFormatFile.save(uczelnia, adresDolcelowy);
                        // stary sytem zapisu do xml
                        // xmlFormatFile.saveStare(filtred,adresDolcelowy);
                        break;
                    }

                    case "json":
                    {
                        jsonFormatFile.save(uczelnia, adresDolcelowy);
                        break;
                    }

                    default:
                    {
                        Console.WriteLine("Nie obługiwany wyjściowy format plików");
                        break;
                    }
                    }
                }
                else
                {
                    if (!File.Exists(adresCSV))
                    {
                        throw new Exception("File does not exsist");
                    }
                    if (!Directory.Exists(adresDolcelowy))
                    {
                        throw new Exception("Directory does not exsit");
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLOgging(ex);
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            string path            = args[0];
            string destinationPath = args[1];


            try
            {
                StreamWriter logs = File.CreateText("log.txt");

                var liness = File.ReadLines(path);
                var hash   = new HashSet <cw2.Student>(new cw2.OwnComparer());
                int computerScienceStudents = 0;
                int mediaArtStudents        = 0;

                foreach (var line in liness)
                {
                    string[] splitLine = line.Split(",");

                    if (splitLine.Length < 9)
                    {
                        logs.WriteLine(line);
                        break;
                    }

                    cw2.Student student = new cw2.Student
                    {
                        Name    = splitLine[0],
                        Surname = splitLine[1],
                        Id      = "s" + splitLine[4],
                        Date    = splitLine[5],
                        Email   = splitLine[6],
                        Mother  = splitLine[7],
                        Father  = splitLine[8],
                        Studies = new Studia
                        {
                            Name = splitLine[2],
                            Mode = splitLine[3]
                        }
                    };
                    hash.Add(student);
                }


                foreach (var student in hash)
                {
                    if (student.Studies.Name == "Sztuka Nowych Mediów dzienne")
                    {
                        mediaArtStudents++;
                    }
                    else
                    {
                        computerScienceStudents++;
                    }
                }


                Uczelnia uczelnia = new Uczelnia
                {
                    CreatedAt     = DateTime.Today,
                    Author        = "Michał Żabicki",
                    Studenci      = hash,
                    ActiveStudies = new AktywneStudia
                    {
                        ComputerScience = new Informatyka
                        {
                            Name             = "Informatyka dzienne",
                            NumberOfStudents = computerScienceStudents
                        },

                        NewArtMedia = new SztukaNowychMediow
                        {
                            Name             = "Sztuka Nowych Mediów dzienne",
                            NumberOfStudents = mediaArtStudents
                        }
                    }
                };



                XmlSerializer xmls    = new XmlSerializer(typeof(Uczelnia));
                FileStream    fsWrite = new FileStream(destinationPath, FileMode.Create);
                xmls.Serialize(fsWrite, uczelnia);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("{0}: ", e.GetType().Name, e.Message);
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            string file;

            if (args.Length == 0 || args[0].Equals(""))
            {
                file = "data/dane.csv";
            }
            else
            {
                file = args[0];
            }
            string gool;

            if (args.Length < 2 || args[1].Equals(""))
            {
                gool = "żesult.xml";
            }
            else
            {
                gool = args[1];
            }
            if (args.Length == 3 && !args[2].Equals("xml"))
            {
                Console.WriteLine("nieprwaidłowy format pliku");
                return;
            }


            string file2 = "data/łog.txt";

            StreamWriter streamWriter = null;

            streamWriter = new StreamWriter(file2);

            FileInfo                 f    = new FileInfo(file);
            List <Student>           los  = new List <Student>();
            Dictionary <string, int> stud = new Dictionary <string, int>();

            try
            {
                using (StreamReader stream = new StreamReader(f.OpenRead()))
                {
                    string line = "";
                    while ((line = stream.ReadLine()) != null)
                    {
                        string[] studentWiersz = line.Split(",");
                        //Console.WriteLine(line);
                        if (studentWiersz.Length == 9)
                        {
                            bool t = true;

                            foreach (string str in studentWiersz)
                            {
                                if (str.Equals(""))
                                {
                                    t = false;
                                }
                            }

                            if (t)
                            {
                                Studia s = new Studia
                                {
                                    nazwa = studentWiersz[2],
                                    tryb  = studentWiersz[3],
                                };

                                var stu = new Student
                                {
                                    Imie          = studentWiersz[0],
                                    Nazwisko      = studentWiersz[1],
                                    index         = int.Parse(studentWiersz[4]),
                                    stud          = s,
                                    DataUrodzenia = studentWiersz[5],
                                    Email         = studentWiersz[6],
                                    Ojciec        = studentWiersz[8],
                                    Matka         = studentWiersz[7]
                                };
                                los.Add(stu);

                                if (stud.ContainsKey(s.nazwa))
                                {
                                    stud[s.nazwa]++;
                                }
                                else
                                {
                                    stud.Add(s.nazwa, 1);
                                }
                            }
                            else
                            {
                                streamWriter.WriteLine("nieprawidłowa struktura danych:" + line);
                            }
                        }
                        else
                        {
                            streamWriter.WriteLine("nieprawidłowa struktura danych:" + line);
                        }
                    }
                }
            }catch (FileNotFoundException e)
            {
                Console.WriteLine("FileNotFoundException(\"Plik nazwa nie istnieje\")");
                streamWriter.WriteLine("FileNotFoundException(\"Plik nazwa nie istnieje\")");
                return;
            }catch (ArgumentException e1)
            {
                Console.WriteLine("ArgumentException(\"Podana ścieżka jest niepoprawna\")");
                streamWriter.WriteLine("ArgumentException(\"Podana ścieżka jest niepoprawna\")");
                return;
            }catch (Exception e2)
            {
                Console.WriteLine(e2.Message);
                streamWriter.WriteLine(e2.Message);
                return;
            }
            streamWriter.Flush();
            streamWriter.Close();
            ActiveStudies active = new ActiveStudies()
            {
                ACl = new List <AC>()
            };

            foreach (KeyValuePair <string, int> entry in stud)
            {
                AC a = new AC
                {
                    name   = entry.Key,
                    number = entry.Value
                };
                active.ACl.Add(a);
            }
            Students st = new Students
            {
                student = los.Distinct(new EqualityComp()).ToList <Student>()
            };

            Uczelnia uczelnia = new Uczelnia
            {
                data          = DateTime.Now,
                autor         = "Michał Zieliński",
                student       = st,
                activeStudies = active
            };


            FileStream       writer     = new FileStream(@gool, FileMode.Create);
            XmlRootAttribute rotatr     = new XmlRootAttribute("studenci");
            XmlSerializer    serializer = new XmlSerializer(typeof(Uczelnia));



            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("", "");
            serializer.Serialize(writer, uczelnia, ns);
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            var file_path   = "data.csv";
            var target_path = "żesult.xml";
            var log_path    = "łog.txt";
            var data_format = "xml";

            StreamWriter sw = File.CreateText(log_path);

            try
            {
                if (args.Length == 3)
                {
                    file_path   = args[0];
                    target_path = args[1];
                    data_format = args[2];
                }

                if (!File.Exists(file_path))
                {
                    throw new FileNotFoundException("Plik nazwa nie istnieje");
                }

                var    uczelnia      = new Uczelnia();
                var    list          = new List <Student>();
                var    listOfStudies = new List <ActiveStudia>();
                string line          = null;

                using (var stream = new StreamReader(File.OpenRead(file_path)))
                {
                    while ((line = stream.ReadLine()) != null)
                    {
                        try
                        {
                            string[] student = line.Split(',');
                            if (student.Length != 9)
                            {
                                throw new Exception("Wiersz student zawiera błędną liczbę kolumn: " + line);
                            }
                            if (student.Any(x => String.IsNullOrEmpty(x)))
                            {
                                throw new Exception("Wiersz student zawiera pustą kolumnę: " + line);
                            }

                            var st = new Student(student);
                            if (list.Exists(x => x.fname == st.fname && x.lname == st.lname && x.indexNumber == st.indexNumber))
                            {
                                throw new Exception("Wiersz student jest duplikatem: " + line);
                            }

                            list.Add(st);
                        }
                        catch (Exception e)
                        {
                            sw.WriteLine(e);
                        }
                    }

                    var query = list.GroupBy(
                        student => student.studies.name,
                        student => student.indexNumber,
                        (name, id) => new
                    {
                        Key   = name,
                        Count = id.Count()
                    }
                        );

                    foreach (var r in query)
                    {
                        listOfStudies.Add(new ActiveStudia(r.Key, r.Count));
                    }

                    uczelnia.Studenci      = list;
                    uczelnia.ActiveStudies = listOfStudies;


                    if (data_format == "xml")
                    {
                        FileStream              writer     = new FileStream(target_path, FileMode.Create);
                        XmlSerializer           serializer = new XmlSerializer(typeof(Uczelnia));
                        XmlSerializerNamespaces ns         = new XmlSerializerNamespaces();
                        ns.Add("", "");
                        serializer.Serialize(writer, uczelnia, ns);
                    }

                    if (data_format == "json")
                    {
                        var uczelniaRoot = new UczelniaRoot();
                        uczelniaRoot.uczelnia = uczelnia;
                        var jsonString = JsonSerializer.Serialize(uczelniaRoot);
                        File.WriteAllText(target_path, jsonString);
                    }
                }
            }
            catch (Exception e)
            {
                sw.WriteLine(e);
            }
        }