Zapisywanie pól obiektów do listy PROBLEM C#

0

Witam!
Bawie się operacjami na listach i napotkałem na pewien problem.

Napisałem metode na dodwanie nowego usera:


public void AddNewUser()
        {
            Console.WriteLine("Podaj imie: ");
            this.Name = Console.ReadLine();

            Console.WriteLine("Podaj nazwisko: ");
            this.Surname = Console.ReadLine();

            Console.WriteLine("Podaj wiek: ");
            this.Age = uint.Parse(Console.ReadLine());

            Console.WriteLine("Podaj adress: ");
            this.Adress = Console.ReadLine();

            Console.WriteLine("Podaj date urodzenia: ");
            this.BirthDate = DateTime.Parse(Console.ReadLine());

            DATA_BASE.Add(new ClientData(this.UserID, this.Name, this.Surname, this.Age, this.Adress, this.BirthDate));
            this.UserID++;
        }

 

I metode wyswietlajaca wszystkich userów w Liscie


public void ShowAllRegistratedUsers()
        {
            foreach (ClientData person in DATA_BASE)
            {
                Console.WriteLine();
                Console.WriteLine("ID: ["+person.UserID+"] Imie: "+person.Name+" Nazwisko: "+person.Surname+" Wiek: "+person.Age+" Adres: "+person.Adress+" Data urodzenia: "+person.BirthDate+".");
            }
        }

 

Oczywiscie dokonuje zapisu do nstp listy:

  List<ClientData> DATA_BASE = new List<ClientData>(); 

Chce wyswietlic wszystkich zapisanych userów ale tak jakby nikogo nie bylo :P

Ktoś wie gdzie robie błąd?

Pozdrawiam i z góry dzieki.

0

Oczywiscie dokonuje zapisu do nstp listy:
A kiedy powstaje ta lista...?
Bo pewnie tworzysz nową listę już po dodaniu do niej elementów, tracąc tę starą.

0

Tak wyglada całość kodu:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Web;
using System.IO;
using System.Net.Mail;
using System.Net;

namespace BazaDanych
{
    class UserValidation
    {
        private string Login { get; set; }
        private string Password { get; set; }
        public string Email { get; set; }
        public DateTime RegistrationDate { get; set; }

        public UserValidation(string login, string password, string email, DateTime regdate)
        {
            this.Login = login;
            this.Password = password;
            this.Email = email;
            this.RegistrationDate = regdate;
        }

        public UserValidation()
        {

        }

        List<UserValidation> REGISTRATED_USERS_BASE = new List<UserValidation>();

        public void RegistrateNewUser()
        {
            Console.WriteLine("Podaj swoj login: ");
            this.Login = Console.ReadLine();
            Console.WriteLine("Haslo: ");
            this.Password = Console.ReadLine();
            Console.WriteLine("Adres Email: ");
            this.Email = Console.ReadLine();
            this.RegistrationDate = DateTime.Now;
            REGISTRATED_USERS_BASE.Add(new UserValidation(this.Login, this.Password, this.Email,this.RegistrationDate));

            UserValidation newusr = new UserValidation();
            newusr.GetAccesToBase();
        }

        public void GetAccesToBase()
        {
            Console.WriteLine("1 - aby sie zalogowac");
            Console.WriteLine("2 - aby zarejestrowac ");
            Console.WriteLine("3 - aby odzyskac swoje konto");
            Console.WriteLine("ESC aby zakonczyc");
            ConsoleKeyInfo klawisz2 = new ConsoleKeyInfo();
            do
            {
               
                klawisz2 = Console.ReadKey();
                switch (klawisz2.Key)
                {
                    case ConsoleKey.D1:
                        {
                            UserValidation usr1 = new UserValidation();
                            usr1.ValidateAccesToDataBase();
                        } break;
                    case ConsoleKey.D2:
                        {
                            UserValidation usr2 = new UserValidation();
                            usr2.RegistrateNewUser();
                        } break;
                    case ConsoleKey.D3:
                        {
                            UserValidation usr3 = new UserValidation();
                        } break;
                    default:
                        {
                            Console.WriteLine("Brak wybranej opcji!");
                        } break;
                }
            } while (klawisz2.Key != ConsoleKey.Escape);
            
        }

        public void ValidateAccesToDataBase()
        {
            string login, password;
            Console.WriteLine("------------------------------");
            Console.WriteLine("------ PANEL LOGOWANIA -------");
            Console.WriteLine("------------------------------");
            Console.WriteLine("Wpisz login: ");
            login = Console.ReadLine();
            Console.WriteLine("Wpisz haslo: ");
            password = Console.ReadLine();

            if (login == this.Login && password == this.Password)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Zalogowano pomyslnie");
                Console.ResetColor();
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Zly login lub haslo!");
                Console.ResetColor();
            }
        }
    }

    class ClientData
    {
        public int UserID { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public uint Age { get; set; }
        public string Adress { get; set; }
        public DateTime BirthDate { get; set; }


        List<ClientData> DATA_BASE = new List<ClientData>();

        public ClientData()
        {

        }

        public ClientData(int userid, string name, string surname, uint age, string adress, DateTime birthdate)
        {
            this.UserID = userid;
            this.Name = name;
            this.Surname = surname;
            this.Age = age;
            this.Adress = adress;
            this.BirthDate = birthdate;
        }

        

        public void AddNewUser()
        {
            Console.WriteLine("Podaj imie: ");
            this.Name = Console.ReadLine();
            
            Console.WriteLine("Podaj nazwisko: ");
            this.Surname = Console.ReadLine();

            Console.WriteLine("Podaj wiek: ");
            this.Age = uint.Parse(Console.ReadLine());

            Console.WriteLine("Podaj adress: ");
            this.Adress = Console.ReadLine();

            Console.WriteLine("Podaj date urodzenia: ");
            this.BirthDate = DateTime.Parse(Console.ReadLine());

            DATA_BASE.Add(new ClientData(this.UserID, this.Name, this.Surname, this.Age, this.Adress, this.BirthDate));
            //DATA_BASE.Insert(this.UserID, new ClientData(this.UserID, this.Name, this.Surname, this.Age, this.Adress, this.BirthDate));
            this.UserID++;
        }

        public void ShowAllRegistratedUsers()
        {
            foreach (ClientData person in DATA_BASE)
            {
                Console.WriteLine();
               // Console.WriteLine("ID: ["+person.UserID+"] Imie: "+person.Name+" Nazwisko: "+person.Surname+" Wiek: "+person.Age+" Adres: "+person.Adress+" Data urodzenia: "+person.BirthDate+".");
                Console.WriteLine("ID: {0}",person.UserID);
                Console.WriteLine("Imie: {0}",person.Name);
                Console.WriteLine("Nazwisko: {0}",person.Surname);
                Console.WriteLine("Wiek: {0}",person.Age);
                Console.WriteLine("Adres: {0}",person.Adress);
                Console.WriteLine("Data urodzenia: {0}",person.BirthDate);
            }
        }

        public void CalculateAllRegistratedUsers()
        {
            Console.WriteLine();
            Console.WriteLine("W bazie zarejestrowano {0} uzytkownikow",DATA_BASE.Count());
            Console.WriteLine();
        }

        public void FindUser()
        {
            Console.WriteLine("Podaj imie i nazwisko uzytkownika: ");
            string imie = Console.ReadLine();
            string nazwisko = Console.ReadLine();

            foreach (ClientData person in DATA_BASE)
            {
                if (person.Name.Contains(imie) && person.Surname.Contains(nazwisko))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("ID: [" + person.UserID + "] Imie: " + person.Name + " Nazwisko: " + person.Surname + " Wiek: " + person.Age + " Adres: " + person.Adress + " Data urodzenia: " + person.BirthDate + ".");
                    Console.ResetColor();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Nie znaleziono podanego uzytkownika!");
                    Console.ResetColor();
                }
            }
            
        }

        public void ClearAllDataBase()
        {
            DATA_BASE.Clear();
        }

        public void RemoveUser()
        {
            Console.WriteLine("Podaj ID uzytkownika do usuniecia: ");
            int ID = int.Parse(Console.ReadLine());

            DATA_BASE.RemoveAt(ID);
        }

        public void SaveUsersDataToTXTFile()
        {
            string TXTfilePath = @".\UsersData\";
            Directory.CreateDirectory(TXTfilePath);

            using (StreamWriter sw = new StreamWriter(@".\UsersData\userdata.txt", true))
            {
                foreach (var item in DATA_BASE)
                {
                    Console.WriteLine();
                    Console.WriteLine("----------------------------------------------------------");
                    sw.WriteLine("ID: " + item.UserID);
                    sw.WriteLine("Imie: " + item.Name);
                    sw.WriteLine("Nazwiko: " + item.Surname);
                    sw.WriteLine("WIek: " + item.Age);
                    sw.WriteLine("Adres: " + item.Adress);
                    sw.WriteLine("Data urodzenia: " + item.BirthDate);
                    Console.WriteLine("----------------------------------------------------------");
                    Console.WriteLine();
                }
                

                sw.Flush(); //czysci bufor, wszystko co bylo w buferze zostaje zapisane do pliku
                sw.Close(); // zamyka plik
            }
        }

        public void SaveUsersDataToBinaryFile()
        {
            string BinaryFilePath = @".\UsersData\";
            Directory.CreateDirectory(BinaryFilePath);

            using (StreamWriter sw = new StreamWriter(@".\UsersData\userdata.dat", true))
            {
                foreach (var item in DATA_BASE)
                {
                    Console.WriteLine();
                    Console.WriteLine("----------------------------------------------------------");
                    sw.WriteLine("ID: "+item.UserID);
                    sw.WriteLine("Imie: "+item.Name);
                    sw.WriteLine("Nazwiko: " + item.Surname);
                    sw.WriteLine("WIek: " + item.Age);
                    sw.WriteLine("Adres: " + item.Adress);
                    sw.WriteLine("Data urodzenia: " + item.BirthDate);
                    Console.WriteLine("----------------------------------------------------------");
                    sw.Write(sw.NewLine);

                }

                
                sw.Flush(); //czysci bufor, wszystko co bylo w buferze zostaje zapisane do pliku
                sw.Close(); // zamyka plik
            }
        }
    }

    class SendData
    {
        public string YourEmail { get; set; }
        public string TargetEmail { get; set; }
        public string Subject { get; set; }
        public string MessageText { get; set; }
        public string EmailPassword { get; set; }

        public SendData()
        {

        }

       
        public SendData(string youremail, string target, string subject, string message, string emailpassword)
        {
            this.YourEmail = youremail;
            this.TargetEmail = target;
            this.Subject = subject;
            this.MessageText = message;
            this.EmailPassword = emailpassword;
        }

       

        public void SendUserDataUsingEmail()
        {
            Console.WriteLine("Podaj swojego maila: ");
            this.YourEmail = Console.ReadLine();
            Console.WriteLine("Podaj swoje haslo: ");
            this.EmailPassword = Console.ReadLine();
            Console.WriteLine("Podaj maila odbiorcy: ");
            this.TargetEmail = Console.ReadLine();
            Console.WriteLine("Podaj temat wiadomosci: ");
            this.Subject = Console.ReadLine();
            Console.WriteLine("Wpisz tresc wiadomosci: ");
            this.MessageText = Console.ReadLine();

            MailMessage message = new MailMessage();
            message.From = new MailAddress(this.YourEmail);
            message.To.Add(new MailAddress(this.TargetEmail));
            message.Subject = this.Subject;
            message.Body = this.MessageText;

            SmtpClient smtp = new SmtpClient("smtp.gmail.com");
       	    smtp.UseDefaultCredentials = true;
        	smtp.Credentials = new NetworkCredential(this.YourEmail+"[email protected]", this.EmailPassword);
        	smtp.EnableSsl = true;
        	smtp.Port = 587;
        	 
        	smtp.Send(message);
        }

        
    }


    class Products
    {
        public string ProductName { get; set; }
        public string ProductCategory { get; set; }
        public double ProductPrize { get; set; }
        public double TaxVAT = 8.00d; // podatek vat
        public double ProfitPerStack = 4.00d; // marza za sztuke produktu

        List<Products> PRODUCTS_BASE = new List<Products>();

        public Products()
        {

        }

        public Products(string productname, string productcategory, double productprize)
        {
            this.ProductName = productname;
            this.ProductCategory = productcategory;
            this.ProductPrize = productprize;
        }

        public void AddNewProduct()
        {
            Console.WriteLine("Nazwa produktu: ");
            this.ProductName = Console.ReadLine();
            Console.WriteLine("Kategoria produktu: ");
            this.ProductCategory = Console.ReadLine();
            Console.WriteLine("Cena produktu: ");
            this.ProductPrize = Convert.ToDouble(Console.ReadLine());
            PRODUCTS_BASE.Add(new Products(this.ProductName, this.ProductCategory, this.ProductPrize));
        }

        public void ShowAllProducts()
        {
            foreach (Products product in PRODUCTS_BASE)
            {
                Console.WriteLine("Nazwa produktu {0}"+this.ProductName);
                Console.WriteLine("Kategoria produktu: {0}"+this.ProductCategory);
                Console.WriteLine("Cena produktu za sztuke: {0}"+this.ProductPrize);
            }
        }

        public double CalculateShopAmount()
        {
            double cena = 0;

            for (int i = 0; i < PRODUCTS_BASE.Count; i++)
            {
                cena += this.ProductPrize;
            }
            return cena;
        }

        public double CalculatePrizeWithTax()
        {
            double cenazvat = 0;
            for (int i = 0; i < PRODUCTS_BASE.Count; i++)
            {
                cenazvat += (this.ProductPrize + this.TaxVAT);
            }
            return cenazvat;
        }

        public double CalculateShopProfit()
        {
            double shopprofit = 0;
            for (int i = 0; i < PRODUCTS_BASE.Count; i++)
            {
                shopprofit = (this.ProductPrize + this.TaxVAT + this.ProfitPerStack);
            }
            return shopprofit;
        }

        
    }



    class Program
    {
        static void Main(string[] args)
        {
            //UserValidation val = new UserValidation();

            //val.GetAccesToBase();







            ConsoleKeyInfo klawisz = new ConsoleKeyInfo();
            do
            {
                Console.WriteLine();
                Console.WriteLine("==================================");
                Console.WriteLine("======== SUPER SKLEP API =========");
                Console.WriteLine("==================================");
                Console.WriteLine("1 - aby dodac nowego uzytkownika");
                Console.WriteLine("2 - aby wyswietlic wszystkich uzytkowników");
                Console.WriteLine("3 - aby wyszukac uzytkownika");
                Console.WriteLine("4 - aby zliczyc zarejestrowanych userow");
                Console.WriteLine("5 - wyczysc cala liste");
                Console.WriteLine("6 - aby wyslac maila");
                Console.WriteLine("7 - aby dodac nowy produkt do sklepu ");
                Console.WriteLine("8 - aby wyswietlic wszystkie produkty ");
                Console.WriteLine("ESC aby wyjsc");
                Console.WriteLine();

                klawisz = Console.ReadKey();
                Console.WriteLine();

                switch (klawisz.Key)
                {
                    case ConsoleKey.D1:
                        {
                            ClientData usr1 = new ClientData();
                            usr1.AddNewUser();
                            usr1.SaveUsersDataToTXTFile();
                            usr1.SaveUsersDataToBinaryFile();
                        } break;
                    case ConsoleKey.D2:
                        {
                            ClientData users = new ClientData();
                            users.ShowAllRegistratedUsers();
                        } break;
                    case ConsoleKey.D3:
                        {
                            ClientData findusr = new ClientData();
                            findusr.FindUser();

                        }break;
                    case ConsoleKey.D4:
                            {
                                ClientData useramount = new ClientData();
                                useramount.CalculateAllRegistratedUsers();
                            }break;
                    case ConsoleKey.D5:
                        {
                            Console.WriteLine("Czy na pewno chcesz wyczyscic cala baze? [t/n]");
                            string wybor = Console.ReadLine();

                            if (wybor == "t" || wybor == "T")
                            {
                                ClientData remusr = new ClientData();
                                remusr.ClearAllDataBase();
                            }
                            else break;
                           
                        }break;
                    case ConsoleKey.D6:
                        {
                            SendData sd = new SendData();
                            sd.SendUserDataUsingEmail();
                        }break;
                    case ConsoleKey.D7:
                        {
                            Products p = new Products();
                            p.AddNewProduct();
                        }break;
                    case ConsoleKey.D8:
                        {
                            Products p2 = new Products();
                            p2.ShowAllProducts();

                        }break;
                    default:
                        {
                            Console.WriteLine();
                            Console.WriteLine("Brak wybranej opcji!");
                            Console.WriteLine();
                        } break;
                }
            } while (klawisz.Key != ConsoleKey.Escape);




        }
    }
}


Liste implementuje w klasie ClientData na samym początku pod properties

Do pliku mi dobrze wszystko wpisuje ale tak jakby nie wpisywał do 1 listy.

A powinien wpisać 1 usera o ID np 1 a potem dodac 2 usera o ID np 2, po kolei.

Sorry bo troche długi ten post ;d

0

Rozumiem, że próbujesz nas przestraszyć?

Dlaczego u Ciebie każda klasa pobiera dane z klawiatury i wyświetla informacje na ekranie? Powinieneś rozdzielić klasy przechowujące dane od klas pobierających i wyświetlających informacje użytkownikowi.

0

To nie jest w tej chwili ważne, co to tam robi, po prostu pytam się was czemu jak wpisuje coś do listy to tego tam nie ma.

0

Jak wpisujesz coś do listy, to to tam jest.
Nie ma przy wyświetlaniu, bo do wyświetlania tworzysz sobie nowy obiekt ClientData, który ma w sobie nową, pustą listę, a nie tamtą uzupełnioną.

0

Zrobilem tak :

 

 ClientData cd = new ClientData();
                switch (klawisz.Key)
                {
                    case ConsoleKey.D1:
                        {
                            cd.AddNewUser();
                            cd.SaveUsersDataToTXTFile();
                            cd.SaveUsersDataToBinaryFile();
                        } break;
                    case ConsoleKey.D2:
                        {
                            cd.ShowAllRegistratedUsers();
                        } break;

I niby robie wszystko na 1 obiekcie ale i tak nic to nie zmienia ;d

0

Oczywiście, że to nic nie zmienia, bo ClientData cd = new ClientData(); wykonujesz w każdym przebiegu swojej pętli do, która odpowiada za menu.

  1. Używaj debugera.
  2. Porzuć ten dziwny pomysł tworzenia klas, które same są swoimi kolekcjami, a swoje właściwości wykorzystują jako zmienne tymczasowe, które później stają się parametrami własnego konstruktora (WTF?). Zrób dwie klasy:
    a) ClientData, która ma odpowiednie właściwości, przeciążoną metodę ToString, żebyś łatwo mógł wyświetlić dane jako tekst (zamiast miliona Console.WriteLine w metodzie ShowAllRegistratedUsers.
    b) ClientsManager, która będzie posiadała List<ClientData> oraz zestaw metod komunikujących się z użytkownikiem i operujących na tej liście.
  3. Czym się różni SaveUsersDataToTXTFile od SaveUsersDataToBinaryFile? Bo na moje oko, to tylko rozszerzeniem pliku, co jest bez sensu, bo plik binarny, to nie jest plik tekstowy z dziwnym rozszerzeniem.
0
somekind napisał(a)

Porzuć ten dziwny pomysł tworzenia klas, które same są swoimi kolekcjami, a swoje właściwości wykorzystują jako zmienne tymczasowe, które później stają się parametrami własnego konstruktora (WTF?)

Jak to było?

Demonical Monk napisał(a)

Wenus jest Merkurym, Ziemia jest Wenus, Mars jest Ziemią, Pluton jest Neptunem, a planeta jest Plutonem.

:-)

0

Dzięki Panowie za rady :)
Wciąż się uczę.

1 użytkowników online, w tym zalogowanych: 0, gości: 1