private void caricaDatiDiTest()
        {
            UtilsDatabase u = new UtilsDatabase(connStr);

            //u.CreateTableCars();
            //UtilsDatabase.CreateTable("Auto");
            //UtilsDatabase.CreateTable("Moto");
            //UtilsDatabase.CreateTableCars("Moto");
            //UtilsDatabase.CreateTableCars("Auto");
            if (UtilsDatabase.first)
            {
                UtilsDatabase.CreateTableCars("cars");
                UtilsDatabase.AddNewCar("Moto", "Honda", "Dominator", "Nero", 1000, 120, DateTime.Now, false, false, 0, 12000, "Quintino", 0);
                UtilsDatabase.AddNewCar("Auto", "Jeep", "Compass", "Blu", 1000, 32, DateTime.Now, false, false, 0, 32500, "/", 8);
            }
            Moto m = new Moto();

            bindingListVeicoli.Add(m);
            m = new Moto("Honda", "Dominator", "Nero", 1000, 120, DateTime.Now, false, false, 0, "Quintino");
            bindingListVeicoli.Add(m);
            //UtilsDatabase.AddNewItem("Moto", "Honda", "Dominator", "Nero", 1000, 120, DateTime.Now, false, false, 0, 12000, 0, "Quintino");
            Auto a = new Auto("Jeep", "Compass", "Blu", 1000, 32, DateTime.Now, false, false, 0, 8);

            bindingListVeicoli.Add(a);
            //UtilsDatabase.AddNewItem("Auto", "Jeep", "Compass", "Blu", 1000, 32, DateTime.Now, false, false, 0, 32500, /*"",*/ 8, "");
        }
 //Serve per prendere i dati dal database, e caricarli su SerializeBindingList. Lo uso all'inizio di form_load, quando su dgv bisogna caricare i
 // dati presi dal database.
 public static SerializableBindingList <Veicolo> OpenDataBaseToList(SerializableBindingList <Veicolo> listaVeicoli)
 {
     if (connstr != null)
     {
         OleDbConnection connection = new OleDbConnection(connstr);
         using (connection)
         {
             connection.Open();
             OleDbCommand cmd = new OleDbCommand();
             try
             {
                 OleDbDataReader rd = cmd.ExecuteReader();
                 while (rd.Read()) //finchè ci sono le righe
                 {
                     if (rd.GetString(1) == "AUTO")
                     {
                         listaVeicoli.Add(new Auto(rd.GetString(1), rd.GetString(2), rd.GetString(3), rd.GetInt32(4), rd.GetDouble(5),
                                                   rd.GetDateTime(6), rd.GetBoolean(7), rd.GetBoolean(8), rd.GetInt32(9), rd.GetInt32(10), rd.GetInt32(11)));
                     }
                     else if (rd.GetString(1) == "MOTO")
                     {
                         listaVeicoli.Add(new Moto(rd.GetString(1), rd.GetString(2), rd.GetString(3), rd.GetInt32(4), rd.GetDouble(5),
                                                   rd.GetDateTime(6), rd.GetBoolean(7), rd.GetBoolean(8), rd.GetInt32(9), rd.GetString(10), rd.GetInt32(11)));
                     }
                 }
                 rd.Close();
             }
             catch (OleDbException exc) { };
         }
     }
     return(listaVeicoli);
 }
Example #3
0
        /// <summary>
        /// Take the item from the database in a list
        /// </summary>
        /// <param name="list"> Empty vehicles list </param>
        /// <param name="con"> Connection to database </param>
        private void InsertItemInList(SerializableBindingList <Vehicles> list, OleDbConnection con, string tableName)
        {
            OleDbCommand command = new OleDbCommand($"SELECT * FROM {tableName}", con);

            OleDbDataReader rdr = command.ExecuteReader();

            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    bool used = rdr.GetString(7) == "Si" ? true : false;
                    bool km0  = rdr.GetString(8) == "Si" ? true : false;
                    if (tableName == "Auto")
                    {
                        list.Add(new Cars(rdr.GetString(1), rdr.GetString(2), rdr.GetString(3),
                                          rdr.GetInt32(4), rdr.GetInt32(5), rdr.GetDateTime(6), used,
                                          km0, rdr.GetInt32(9), Convert.ToDouble(rdr.GetDecimal(10)), rdr.GetString(12),
                                          rdr.GetInt32(11)));
                    }
                    else
                    {
                        list.Add(new Motorbikes(rdr.GetString(1), rdr.GetString(2), rdr.GetString(3),
                                                rdr.GetInt32(4), rdr.GetInt32(5), rdr.GetDateTime(6), used,
                                                km0, rdr.GetInt32(9), Convert.ToDouble(rdr.GetDecimal(10)), rdr.GetString(12),
                                                rdr.GetString(11)));
                    }
                }
            }
            else
            {
                MessageBox.Show("Non è stato trovato alcun dato", "ATTENZIONE", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            rdr.Close();
        }
Example #4
0
        private SerializableBindingList <Veicolo> openDb(string constr, string sql)
        {
            var       l = new SerializableBindingList <Veicolo>();
            DataTable t = new DataTable();

            using (OleDbConnection connection = new OleDbConnection(constr)) //data reader: oggetto per recuperare dati
            {
                connection.Open();
                OleDbCommand     command = new OleDbCommand(sql, connection);
                OleDbDataAdapter da      = new OleDbDataAdapter(command);
                da.Fill(t);
                foreach (DataRow r in t.Rows)
                {
                    if (r["Carburante"].ToString() == "|")
                    {
                        Moto m = new Moto(r["Targa"].ToString(), r["Marca"].ToString(), r["Modello"].ToString(), r["Versione"].ToString(), Convert.ToInt32(r["Cilindrata"]), r["TipoVeicolo"].ToString(), r["Tipologia"].ToString(), Convert.ToInt32(r["Km"]), Convert.ToDateTime(r["Immatricolazione"]), Convert.ToDouble(r["Prezzo"]));
                        l.Add(m);
                    }
                    else
                    {
                        Auto a = new Auto(r["Targa"].ToString(), r["Marca"].ToString(), r["Modello"].ToString(), r["Versione"].ToString(), Convert.ToInt32(r["Cilindrata"]), r["TipoVeicolo"].ToString(), r["Tipologia"].ToString(), Convert.ToInt32(r["Km"]), Convert.ToDateTime(r["Immatricolazione"]), r["Carburante"].ToString(), Convert.ToDouble(r["Prezzo"]));
                        l.Add(a);
                    }
                }
            }
            return(l);
        }
Example #5
0
        private void CaricaDatiDiTesto()
        {
            moto m = new moto();

            m = new moto("Ducati", "Panigale V4R", 1000, 75, DateTime.Now, 0, "blu", false, false, 11300, "StandarCO");
            listVeicolo.Add(m);
            auto a = new auto("Alfa Romeo", "Stelvio", 2000, 150, DateTime.Now, 0, "rosso", false, false, 10000, 8);

            listVeicolo.Add(a);
            lbVeicoli.DataSource = listVeicolo;
        }
Example #6
0
        public static string datapass(string connectionStr, SerializableBindingList <veicolo> listveicolo, int[] iDs)
        {
            try
            {
                if (connectionStr != null)
                {
                    OleDbConnection connection = new OleDbConnection(connectionStr);
                    using (connection)
                    {
                        connection.Open();
                        OleDbCommand    command = new OleDbCommand("SELECT * FROM veicoli", connection);
                        OleDbDataReader reader  = command.ExecuteReader();

                        listveicolo.Clear();
                        Array.Clear(iDs, 0, iDs.Length);
                        if (reader.HasRows)
                        {
                            int i = 0;
                            while (reader.Read())
                            {
                                if (reader.GetString(1) == "auto")
                                {
                                    iDs[i] = reader.GetInt32(0);
                                    listveicolo.Add(new auto(reader.GetString(2), reader.GetString(3), reader.GetInt32(4), reader.GetDouble(5), reader.GetDateTime(6), reader.GetInt32(7), reader.GetString(8), reader.GetString(9) == "SI" ? true : false, reader.GetString(10) == "SI" ? true : false, reader.GetInt32(12), reader.GetString(11)));
                                }
                                else
                                {
                                    iDs[i] = reader.GetInt32(0);
                                    listveicolo.Add(new moto(reader.GetString(2), reader.GetString(3), reader.GetInt32(4), reader.GetDouble(5), reader.GetDateTime(6), reader.GetInt32(7), reader.GetString(8), reader.GetString(9) == "SI" ? true : false, reader.GetString(10) == "SI" ? true : false, reader.GetInt32(12), reader.GetString(11)));
                                }
                                i++;
                                //    Marca: {reader.GetString(2)};
                                //    Modello: {reader.GetString(3)};
                                //    Cilindrata: {reader.GetInt32(4)};
                                //    Potenza(KW): {reader.GetDouble(5)};
                                //    Data Immatricolazione: {reader.GetDateTime(6).ToShortDateString()};
                                //    Chilometri percorsi: {reader.GetInt32(7)};
                                //    Colore: {reader.GetString(8)};
                                //    Usato: {reader.GetString(9)};
                                //    Km0: {reader.GetString(10)};
                                //    Informazioni: {reader.GetString(11)};
                                //    Prezzo: {reader.GetInt32(12)};
                            }
                        }
                        reader.Close();
                    }
                }
                return("DONE");
            }
            catch (Exception ex)
            {
                return("\n!!ERROR!! " + ex.Message);
            }
        }
Example #7
0
        private void CaricaDatiDiTest()
        {
            Moto m = new Moto();

            bindingListVeicoli.Add(m);
            m = new Moto("Aprilia", "125", "Rosso", 600, 70, DateTime.Now, false, false, 20000, 0, "Harley Davison");
            bindingListVeicoli.Add(m);

            Auto a = new Auto();

            a = new Auto("Audi", "A1", "Blu", 1400, 75, DateTime.Now, false, false, 20000, 0, 7);
            bindingListVeicoli.Add(a);
        }
        public bool listaTabella(string nomeTabella, SerializableBindingList <Veicolo> bindingVeicolo)
        {
            if (conStr != null)
            {
                OleDbConnection con = new OleDbConnection(conStr);
                using (con)
                {
                    con.Open();
                    OleDbCommand cmd;
                    try
                    {
                        cmd = new OleDbCommand($"SELECT * FROM {nomeTabella}", con);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    OleDbDataReader reader = cmd.ExecuteReader();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            if (nomeTabella == "Auto")
                            {
                                Auto a = new Auto(reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetInt32(4), reader.GetInt32(5),
                                                  reader.GetDateTime(6), reader.GetString(7) == "Si" ? true:false, reader.GetString(8) == "Si" ? true:false, reader.GetInt32(9), reader.GetInt32(10), reader.GetInt32(11), reader.GetInt32(0));
                                bindingVeicolo.Add(a);
                            }
                            else
                            {
                                Moto m = new Moto(reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetInt32(4), reader.GetInt32(5),
                                                  reader.GetDateTime(6), reader.GetString(7) == "Si" ? true : false, reader.GetString(8) == "Si" ? true : false, reader.GetInt32(9), reader.GetInt32(10), reader.GetString(11), reader.GetInt32(0));
                                bindingVeicolo.Add(m);
                            }
                        }
                        reader.Close();
                        return(true);
                    }
                    else
                    {
                        reader.Close();
                        return(false);
                    }
                }
            }
            return(false);
        }
        private void Handler_VeicoloAggiunto(Veicolo v, Aggiungi a)
        {
            try
            {
                string pth = a.img.Split('\\')[a.img.Split('\\').Length - 1];//COPIO L'IMMAGINE DAL PATH ORIGINALE ALLA CARTELLA /WWW/IMAGES
                if (!File.Exists(Path.Combine(Properties.Resources.IMAGE_FOLDER_PATH, pth)))
                {
                    File.Copy(a.img, Path.Combine(Properties.Resources.IMAGE_FOLDER_PATH, pth));
                }
                v.ImagePath = Path.Combine(Properties.Resources.IMAGE_FOLDER_PATH, pth);
            }
            catch
            {
                v.ImagePath = "";
            }
            a.img = "";

            listaVeicoliAggiunti.Add(v);
            modifica = true;
            var c = new Card(v);

            this.pnlMain.Controls.Add(c);
            c.CardDeleted += Handler_CardDeleted;
            c.CardShowed  += Handler_CardShowed;
            this.Tb.TabPages.Remove(tAggiungi);
            this.tAggiungi = null;
        }//EVENTO 'AGGIUNTA DI UN VEICOLO'
Example #10
0
        private void caricaDatiDiTest()
        {
            Moto m = new Moto();
            BindingListVeicoli.Add(m);
            //UtilsDatabase.AggiungiVeicolo(m);// problemi di provider 
            m = new Moto("HONDA", "Tsunami", "Rosso", 1000, 120, DateTime.Now, false, false, 0, "Quintino", 15000);
            BindingListVeicoli.Add(m);
            //UtilsDatabase.AggiungiVeicolo(m); Problemi di provider.
            Auto a = new Auto("JEEP", "Compass", "Blue", 2400, 160.10, DateTime.Now, false, false, 0, 8, 30000);
            BindingListVeicoli.Add(a);

            //UtilsDatabase.AggiungiVeicolo(a); Problemi di provider, e per evitare che si interrompesse, l'ho messo come commento.

            dgvVeicoli.DataSource = BindingListVeicoli;

        }
Example #11
0
        public static void CreateList()
        {
            if (connStr != null)
            {
                OleDbConnection con = new OleDbConnection(connStr);
                using (con)
                {
                    con.Open();

                    OleDbCommand cmd = new OleDbCommand();
                    cmd.Connection = con;

                    try
                    {
                        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Veicoli", con);
                        DataTable        table   = new DataTable();
                        adapter.Fill(table);

                        foreach (DataRow item in table.Rows)
                        {
                            if (int.TryParse(item.ItemArray[10].ToString(), out _))
                            {
                                Auto a = new Auto(item.ItemArray[0].ToString(), item.ItemArray[1].ToString(), item.ItemArray[2].ToString(), item.ItemArray[3].ToString(), Convert.ToInt32(item.ItemArray[4]), Convert.ToDouble(item.ItemArray[5]),
                                                  Convert.ToDateTime(item.ItemArray[6]), Convert.ToBoolean(item.ItemArray[7]), Convert.ToBoolean(item.ItemArray[8]), Convert.ToInt32(item.ItemArray[9]),
                                                  Convert.ToInt32(item.ItemArray[10]));
                                bindingListVeicoli.Add(a);
                            }
                            else
                            {
                                Moto m = new Moto(item.ItemArray[0].ToString(), item.ItemArray[1].ToString(), item.ItemArray[2].ToString(), item.ItemArray[3].ToString(), Convert.ToInt32(item.ItemArray[4]), Convert.ToDouble(item.ItemArray[5]),
                                                  Convert.ToDateTime(item.ItemArray[6]), Convert.ToBoolean(item.ItemArray[7]), Convert.ToBoolean(item.ItemArray[8]), Convert.ToInt32(item.ItemArray[9]),
                                                  item.ItemArray[10].ToString());
                                bindingListVeicoli.Add(m);
                            }
                        }
                    }
                    catch (OleDbException exc)
                    {
                        Console.WriteLine("\n " + exc.Message);
                        System.Threading.Thread.Sleep(4000);
                        return;
                    }
                }
            }
        }
        public static void DeserializeJson(SerializableBindingList <Veicolo> lista, string fileName)
        {
            lista.Clear();
            string json = File.ReadAllText(fileName);

            object[] veicoli = JsonConvert.DeserializeObject <object[]>(json);
            for (int i = 0; i < veicoli.Length; i++)
            {
                Moto   moto    = new Moto();
                Auto   auto    = new Auto();
                string veicolo = veicoli[i].ToString();
                if (veicolo.Contains("MarcaSella"))
                {
                    JsonConvert.PopulateObject(veicolo, moto);
                    lista.Add(moto);
                }
                else
                {
                    JsonConvert.PopulateObject(veicolo, auto);
                    lista.Add(auto);
                }
            }
        }
Example #13
0
 private void btnAggiungiVeicolo_Click(object sender, EventArgs e)
 {
     errorProvider1.Clear();
     if (veicolo != null)
     {
         if (controlloCampi())
         {
             if (veicolo == "Auto")
             {
                 Auto a = new Auto(txtMarca.Text, txtModello.Text, color, Convert.ToInt32(nupCilindrata.Value), Convert.ToDouble(nupPotenza.Value), dtpDataImmatricolazione.Value, rdbNo.Checked ? false : true, cmbKm0.SelectedIndex == 0 ? true : false, Convert.ToInt32(nupKm.Value), Convert.ToDouble(numPrezzo.Value), Convert.ToInt32(nupNAirbag.Value), 0);
                 lista.Add(a);
                 pulisciCampi();
                 aggioraCampi(cmbVeicolo.Text);
             }
             else
             {
                 Moto m = new Moto(txtMarca.Text, txtModello.Text, color, Convert.ToInt32(nupCilindrata.Value), Convert.ToDouble(nupPotenza.Value), dtpDataImmatricolazione.Value, rdbNo.Checked ? false : true, cmbKm0.SelectedIndex == 0 ? true : false, Convert.ToInt32(nupKm.Value), Convert.ToDouble(numPrezzo.Value), txtMarcaSella.Text, 0);
                 lista.Add(m);
                 pulisciCampi();
                 aggioraCampi(cmbVeicolo.Text);
             }
             parent.modificato = true;
         }
     }
     else
     {
         if (pnlControlli.Visible == true)
         {
             MessageBox.Show("Compilare prima i campi!!");
         }
         else
         {
             errorProvider1.SetError(cmbVeicolo, "Selezionare un opzione!!!");
         }
     }
 }
        }//ESPORTA I DATI DEI VEICOLI CREANDO UN FOGLIO DI CALCOLO EXCEL

        #endregion

        private void Salva()
        {
            try
            {
                foreach (Veicolo v in listaVeicoliEliminati)
                {
                    vc.Delete(v, connString);
                }
                foreach (Veicolo v in listaVeicoliAggiunti)
                {
                    vc.Insert(v, connString);
                    listaVeicoli.Add(v);
                }
                foreach (Veicolo v in listaVeicoli)
                {
                    vc.Update(v, connString);
                }

                MessageBox.Show("Modifiche salvate!", "Salva", MessageBoxButtons.OK, MessageBoxIcon.Information);
                modifica = false;
                if (deletePaths.Count > 0)
                {
                    foreach (string path in deletePaths)
                    {
                        if (path.Length > 0)
                        {
                            if (!path.Contains("noimg.png"))
                            {
                                File.Delete(path);
                            }
                        }
                    }
                }
                deletePaths.Clear();
                listaVeicoliAggiunti.Clear();
                listaVeicoliEliminati.Clear();
            }
            catch (Exception e)
            {
                MessageBox.Show("Errore durante il Salvataggio dei dati!\n" + e.Message, "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }//METODO CHE SALVA I DATI DI UNA SerializableBindingList<T> IN DB ACCESS
        }//EVENTO 'CHIUSURA TAB DETTAGLI VEICOLO'

        private void Handler_CardDeleted(Veicolo v, Card card, CardDetails c = null)
        {
            modifica = true;
            SerializableBindingList <Veicolo> lista = (listaVeicoli.Contains(v) ? listaVeicoli : listaVeicoliAggiunti);

            lista.Remove(v);
            this.pnlMain.Controls.Remove(this);

            if (c != null)
            {
                this.Tb.TabPages.Remove(c.tabPage);
            }
            this.pnlMain.Controls.Remove(card);

            if (!v.ImagePath.Contains("noimg.png") && v.ImagePath != "")
            {
                deletePaths.Add(v.ImagePath);
            }
            listaVeicoliEliminati.Add(v);
        }//EVENTO 'ELIMINAZIONE DI UN VEICOLO'
        private static void Main()
        {
            bool   created = false;
            string foo     = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Car-shop");
            string accessDbPath;

            if (!Directory.Exists(foo))
            {
                Directory.CreateDirectory(foo);
                File.Create(Path.Combine(foo, Properties.Resources.ACCESS_DB_NAME));
            }
            else
            {
                foo = Path.Combine(foo, Properties.Resources.ACCESS_DB_NAME);
                if (!File.Exists(foo))
                {
                    Catalog c = new Catalog();
                    c.Create($"Provider=Microsoft.Ace.Oledb.12.0;Data Source={foo};");
                    c = null;
                }
            }
            accessDbPath = foo;

            string connString = $"Provider=Microsoft.Ace.Oledb.12.0;Data Source={accessDbPath};";
            SerializableBindingList <Veicolo> listaVeicoli = new SerializableBindingList <Veicolo>();
            VeicoliCommands vc = new VeicoliCommands();

            try
            {
                listaVeicoli = vc.GetVeicoliList(vc.GetRows(connString, "SELECT * FROM Veicoli;"));
                created      = true;
            }
            catch (OleDbException e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("\n\t\t\t=== " + Properties.Resources.PROGRAM_NAME + " ===\n");
            foreach (Veicolo v in listaVeicoli)
            {
                Console.WriteLine($"{v.Targa} - {v.Marca} {v.Modello} - {v.Stato} {v.GetPrezzo()} - {v.Colore}");
            }
            string scelta;

            do
            {
                bool trovato = false;
                Console.Write("# ");
                scelta = Console.ReadLine();
                if (!created && scelta.ToUpper().Split(' ')[0] != "TCREATE")
                {
                    Console.WriteLine("\nIl database non è ancora stato creato!");
                    continue;
                }

                switch (scelta.ToUpper().Split(' ')[0])
                {
                case "EXPORT":
                {
                    string dataType;
                    string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    try
                    {
                        dataType = scelta.Split(' ')[1].Trim().ToUpper();
                    }
                    catch { Console.WriteLine("Sintassi comando errata!"); Console.ReadKey(); break; }
                    FileExport fe = new FileExport();
                    switch (dataType)
                    {
                    case "JSON":
                    {
                        fe.SerializeToJson(listaVeicoli, Path.Combine(desktop, "Veicoli.json"));
                        Console.WriteLine("Esportazione completata!");
                        break;
                    }

                    case "XML":
                    {
                        var f = new FileExport.SerializableBindingList <Veicolo>(listaVeicoli.ToList());
                        fe.SerializeToXml <Veicolo>(f, Path.Combine(desktop, "Veicoli.xml"));
                        Console.WriteLine("Esportazione completata!");
                        break;
                    }

                    case "EXCEL":
                    {
                        List <string[]> l = new List <string[]>();
                        foreach (var v in listaVeicoli)
                        {
                            l.Add(new string[] { v.Targa, v.Marca, v.Modello, v.Immatricolazione.ToShortDateString(), v.Stato, v.GetPrezzo() });
                        }
                        string path = Path.Combine(desktop, "Veicoli.xlsx");
                        Excel  xls  = new Excel("Veicoli", path, l, new string[] { "Targa", "Marca", "Modello", "Immatricolazione", "Stato", "Prezzo" });
                        Console.WriteLine("Il documento è pronto!");
                        break;
                    }

                    default:
                        Console.WriteLine("Formato non supportato!");
                        break;
                    }
                    break;
                }

                case "HELP":
                {
                    Console.WriteLine("\n" + File.ReadAllText(@".\Commands.txt") + "\n");
                    Console.ReadKey();
                    break;
                }

                case "VADD":
                {
                    Console.WriteLine("\t\t\t\t=== NUOVO VEICOLO ===\n");
                    Console.Write("Auto o Moto? (X per uscire)[A/M]: ");
                    string  a = Console.ReadLine().ToUpper();
                    Veicolo v;
                    if (a != "X" && (a == "A" || a == "M"))
                    {
                        if (a == "A")
                        {
                            v = new Auto();
                        }
                        else
                        {
                            v = new Moto();
                        }
                    }
                    else
                    {
                        break;
                    }
                    try
                    {
                        v.Targa            = AskToSet("Inserisci Targa (x per uscire): ");
                        v.Marca            = AskToSet("Inserisci Marca (x per uscire): ");
                        v.Modello          = AskToSet("Inserisci Modello (x per uscire): ");
                        v.Cilindrata       = Convert.ToInt32(AskToSet("Inserisci Cilindrata [cc] (x per uscire): "));
                        v.PotenzaKw        = Convert.ToInt32(AskToSet("Inserisci Potenza [Kw] (x per uscire): "));
                        v.Immatricolazione = Convert.ToDateTime(AskToSet("Inserisci Data Immatricolazione [gg/mm/aaaa] (x per uscire): "));
                        v.IsUsato          = AskToSet("Il veicolo è usato? [S/N] (x per uscire): ").ToUpper() == "S";
                        v.IsKmZero         = AskToSet("Il veicolo è Km Zero? [S/N] (x per uscire): ").ToUpper() == "S";
                        v.KmPercorsi       = v.IsUsato ? Convert.ToInt32(AskToSet("Inserisci chilometraggio [Km] (x per uscire): ")) : 0;
                        v.ImagePath        = AskToSet("Inserisci path immagine [opzionale] (x per uscire): ");
                        v.Colore           = AskToSet("Inserisci colore (x per uscire): ");
                        v.Prezzo           = Convert.ToDouble(AskToSet("Inserisci prezzo [€] (x per uscire): "));

                        if (v is Auto)
                        {
                            (v as Auto).NumeroAirBag = Convert.ToInt32(AskToSet("Inserisci numero di airbag (x per uscire): "));
                        }
                        else
                        {
                            (v as Moto).MarcaSella = AskToSet("Inserisci la marca della sella (x per uscire): ");
                        }
                        listaVeicoli.Add(v);
                        vc.Insert(v, connString);
                        Console.WriteLine("Veicolo Aggiunto!");
                        Console.ReadKey();
                    }

                    catch { }
                    break;
                }

                case "VSHOW":
                {
                    string targa;
                    try
                    {
                        targa = scelta.Split(' ')[1].Trim().ToUpper();
                    }
                    catch { Console.WriteLine("Sintassi comando errata!"); Console.ReadKey(); break; }
                    foreach (Veicolo v in listaVeicoli)
                    {
                        if (v.Targa.ToUpper() == targa)
                        {
                            string s = new string('-', 30);
                            trovato = true;
                            Console.WriteLine($"\n{v.Marca} {v.Modello}\n" + s +
                                              $"\nCilindrata: {v.Cilindrata} cc\n" + s +
                                              $"\nPotenza: {v.PotenzaKw} Kw\n" + s +
                                              $"\nImmatricolazione: {v.Immatricolazione.ToShortDateString()}\n" + s +
                                              $"\nStato: {v.Stato}\n" + s +
                                              $"\nKm Zero: {v.IsKmZero}\n" + s +
                                              $"\nChilometraggio: {v.KmPercorsi } Km\n" + s +
                                              $"\nColore: {v.Colore}\n" + s +
                                              $"\nPrezzo: {v.GetPrezzo()}\n" + s +
                                              ((v is Auto ? $"\nNumero airbag: {(v as Auto).NumeroAirBag}\n" : $"\nMarca sella: {(v as Moto).MarcaSella}\n") + s));
                            break;
                        }
                        if (!trovato)
                        {
                            Console.WriteLine("Veicolo non trovato");
                        }
                        Console.ReadKey();
                    }
                    break;
                }

                case "VEDIT":
                {
                    string targa, proprieta;
                    try
                    {
                        targa     = scelta.Split(' ')[1].Trim().ToUpper();
                        proprieta = scelta.Split(' ')[2].Trim().ToUpper();
                    }
                    catch { Console.WriteLine("Sintassi comando errata!"); Console.ReadKey(); break; }
                    if (proprieta == "TARGA")
                    {
                        Console.WriteLine("Non puoi modificare la targa!");
                        Console.ReadKey(); break;
                    }
                    foreach (Veicolo v in listaVeicoli)
                    {
                        if (v.Targa.ToUpper() == targa)
                        {
                            trovato = true;
                            try
                            {
                                Console.Write("Inserisci nuovo " + proprieta + ": ");
                                v[proprieta.Substring(0, 1) + proprieta.Substring(1).ToLower()] = Console.ReadLine();
                                vc.Update(v, connString);
                            }
                            catch { Console.WriteLine("Formato valore immesso errato!"); }
                        }
                    }
                    if (!trovato)
                    {
                        Console.WriteLine("Veicolo non trovato"); Console.ReadKey();
                    }
                    break;
                }

                case "VFIND":
                {
                    Console.Write("Inserisci: ");
                    SerializableBindingList <Veicolo> results = Veicolo.Search(Console.ReadLine(), listaVeicoli.ToList());
                    if (results.Count > 0)
                    {
                        Console.WriteLine($"\t\t\t=== RISULTATI RICERCA ===\n");
                        foreach (Veicolo v in results)
                        {
                            Console.WriteLine($"{v.Targa} - {v.Marca} {v.Modello} - {v.Stato} {v.GetPrezzo()} - {v.Colore}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Nessun risultato");
                    }
                    Console.ReadKey();
                    break;
                }

                case "VDELETE":
                {
                    string targa;
                    try
                    {
                        targa = scelta.Split(' ')[1].Trim().ToUpper();
                    }
                    catch { Console.WriteLine("Sintassi comando errata!"); Console.ReadKey(); break; }
                    foreach (Veicolo v in listaVeicoli)
                    {
                        if (v.Targa.ToUpper() == targa)
                        {
                            trovato = true;
                            Console.Write($"SEI SICURO DI VOLER ELIMINARE {v.Marca} {v.Modello} - {v.Targa} ? [S/N]: ");
                            if (Console.ReadLine().ToUpper() == "S")
                            {
                                listaVeicoli.Remove(v);
                                vc.Delete(v, connString);
                                Console.WriteLine("Veicolo eliminato");
                            }
                            break;
                        }
                    }
                    if (!trovato)
                    {
                        Console.WriteLine("Veicolo non trovato");
                    }
                    Console.ReadKey();
                    break;
                }

                case "CLEAR":
                {
                    Console.Clear();
                    break;
                }

                case "TDROP":
                {
                    Console.Write($"SEI SICURO DI VOLER ELIMINARE I DATI ? [S/N]: ");
                    if (Console.ReadLine().ToUpper() == "S")
                    {
                        try
                        {
                            vc.DropTable(connString);
                            Console.WriteLine("Database eliminato!");
                            listaVeicoli.Clear();
                            created = false;
                        }
                        catch (OleDbException e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                    break;
                }

                case "TSHOW":
                {
                    foreach (Veicolo v in listaVeicoli)
                    {
                        Console.WriteLine($"{v.Targa} - {v.Marca} {v.Modello} - {v.Stato} {v.GetPrezzo()} - {v.Colore}");
                    }
                    break;
                }

                case "TCREATE":
                {
                    Console.Write($"SEI SICURO DI VOLER CREARE LA TABELLA \"VEICOLI\" ? [S/N]: ");
                    if (Console.ReadLine().ToUpper() == "S")
                    {
                        try
                        {
                            vc.CreateTable(connString);
                            Console.WriteLine("Database creato!");
                            listaVeicoli = vc.GetVeicoliList(vc.GetRows(connString, "SELECT * FROM Veicoli;"));
                            created      = true;
                        }
                        catch (OleDbException e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                    break;
                }

                case "TDEF":
                {
                    string[] d = VeicoliDllProject.Properties.Resources.DATA_DEF.Split(',');
                    int      n = d.Length;
                    Console.WriteLine(string.Join("\n", d));
                    Console.WriteLine("N. campi: " + n);

                    break;
                }

                case "TCOUNT":
                {
                    Console.WriteLine("N. Record: " + listaVeicoli.Count);
                    break;
                }

                case "X": break;

                default:
                    break;
                }
            } while (scelta.ToUpper() != "X");
        }
Example #17
0
        private void salvataggioDatabase()
        {
            int[] idDb = new int[db.contaItem("Auto")];
            db.getIds("Auto", idDb);
            SerializableBindingList <int> idList = new SerializableBindingList <int>();

            foreach (Auto auto in bindingListVeicoli.OfType <Auto>())
            {
                if (auto.Id == 0)
                {
                    db.aggiungiRecord("Auto", auto.Marca, auto.Modello, auto.Colore, auto.Cilindrata, auto.PotenzaKw, auto.Immatricolazione,
                                      auto.IsUsato, auto.IsKmZero, auto.KmPercorsi, auto.Prezzo, auto.NumAirbag, "/");
                }
                else
                {
                    idList.Add(auto.Id);
                }
            }
            if (idList.Count != 0)
            {
                for (int i = 0; i < idDb.Length; i++)
                {
                    bool presente = false;
                    int  j        = 0;
                    do
                    {
                        if (idDb[i] == idList[j])
                        {
                            presente = true;
                        }
                        j++;
                    } while (j != idList.Count && presente == false);
                    if (presente == false)
                    {
                        db.eliminaRecord("Auto", idDb[i]);
                    }
                }
            }
            else
            {
                for (int i = 0; i < idDb.Length; i++)
                {
                    db.eliminaRecord("Auto", idDb[i]);
                }
            }

            idList.Clear();
            idDb = new int[db.contaItem("Moto")];
            db.getIds("Moto", idDb);
            foreach (Moto moto in bindingListVeicoli.OfType <Moto>())
            {
                if (moto.Id == 0)
                {
                    db.aggiungiRecord("Moto", moto.Marca, moto.Modello, moto.Colore, moto.Cilindrata, moto.PotenzaKw, moto.Immatricolazione,
                                      moto.IsUsato, moto.IsKmZero, moto.KmPercorsi, moto.Prezzo, 0, moto.MarcaSella);
                }
                else
                {
                    idList.Add(moto.Id);
                }
            }
            if (idList.Count != 0)
            {
                for (int i = 0; i < idList.Count; i++)
                {
                    bool presente = false;
                    int  j        = 0;
                    do
                    {
                        if (idList[i] == idDb[j])
                        {
                            presente = true;
                        }
                        j++;
                    } while (j != idDb.Length && presente == false);
                    if (presente == false)
                    {
                        db.eliminaRecord("Moto", idList[i]);
                    }
                }
            }
            else
            {
                for (int i = 0; i < idDb.Length; i++)
                {
                    db.eliminaRecord("Moto", idDb[i]);
                }
            }

            modificato = false;
            bindingListVeicoli.Clear();
            CaricaDati();
            MessageBox.Show("Dati salvati correttamente");
        }