//Si un élément de la liste déroulante est changé. protected void DropDownListVilles_SelectedIndexChanged(object sender, EventArgs e) { string select = DropDownListVilles.SelectedItem.Value; if (Session["modeleClient"] != null) { //On le récupère et on demande les enregistrements des clients selon la requête passée en paramètre Modele modele = (Modele)Session["modeleClient"]; OleDbDataReader readerSelect = modele.ReadClient("SELECT IdPointDistribution, Adresse, Ville, Pays FROM PointDistribution"); string iD = readerSelect.GetName(0); // Le GetName prend le champ selon sa position dans la sélection. //On envoie notre table en construction while (readerSelect.Read()) { if (select == readerSelect[iD].ToString()) { LabelAdresse.Text = "Adresse :" + readerSelect["Adresse"].ToString(); LabelVille.Text = "Ville :" + readerSelect["Ville"].ToString(); LabelPays.Text = "Pays :" + readerSelect["Pays"].ToString(); LiteralMap.Text = @"<iframe src=http://maps.google.com/" + readerSelect["Ville"].ToString() + "\" width=\"600\" height=\"450\" style=\"border:0\" ></iframe>"; } } readerSelect.Close(); } }
public detailPieceView(Modele _input) { InitializeComponent(); SelectedModele = _input; nbVendus.Content = SelectedModele.Nbvendus; pourcentageVendu.Content = $"{100 * SelectedModele.Nbvendus / Commande.NbModelesVendus()} %"; }
public override void ExecuteShowDetailsCommand(object selectedItem) { if (selectedItem is Modele) { this.SelectedModele = selectedItem as Modele; } }
private void btnSaveCustomer_Click(object sender, RoutedEventArgs e) { if (!string.IsNullOrEmpty(tbFirstName.Text) && !string.IsNullOrEmpty(tbLastName.Text)) { if (Modele.IsCustomerPresent(Convert.ToInt32(tbID.Text))) { // Mise à jour du client Customer client = Modele.GetCustomerById(Convert.ToInt32(tbID.Text)); if (client != null) { Modele.UpdateCustomer(client, (Customer)objectBinding); DisplayMessage("Modification réussi!"); } } else { //Ajout d'un client Modele.AddCustomer((Customer)objectBinding); objectBinding = new Customer(); panelClient.DataContext = objectBinding; DisplayMessage("Enregistrement réussi!"); } Frame.Navigate(typeof(Client_Fournisseur), "Clients"); } else { DisplayMessage("Il est nécessaire de remplir au moins les champs Nom et Prénom pour enregistrer."); } }
private void brandComboBox_Changed(object sender, RoutedEventArgs e) { modelTextblock.Visibility = Visibility.Visible; modelComboBox.Visibility = Visibility.Visible; Modele.Clear(); Years.Clear(); List <string> modele = new List <string>(); try { modele = (from m in _db.import where m.make == MyItem select m.model).Distinct().ToList(); foreach (var i in modele) { Modele.Add(i); //Console.WriteLine(i); } NotifyPropertyChanged("Modele"); } catch { Console.WriteLine("ex1"); return; } //Console.WriteLine(item.Content.ToString()); //modelComboBox.ItemsSource = modele; }
public static Boolean kupWoz(string id) { int kasa = Modele.getGold(); int x; if (kasa >= 200) { foreach (TableCaravan kar in Modele.tableCaravan) { if (kar.GetId() == id) { x = kar.GetWagons(); x++; kar.SetWagons(x); } } x = Modele.getGold(); x = x - 200; Modele.setGold(x); return(true); } else { return(false); } }
public void tura() { int czas = Modele.getTime(); czas++; Modele.setTime(czas); foreach (TableCaravan kar in Modele.tableCaravan) //odejmujemy jedna ture od karawan { kar.ChangeDuration(); // tu juz jest kontrola czy jest zero tur if (kar.GetDuration() != 0) { Random rng = new Random(); int random = rng.Next(100); if (random == 1) { napad(kar.GetId()); } } } dzien(); wyplata(); if (czas % 7 == 0) { tydzien(); } }
private void btnSaveSupplier_Click(object sender, RoutedEventArgs e) { if (!string.IsNullOrEmpty(tbCompanyNameSupplier.Text)) { if (Modele.IsSupplierPresent(Convert.ToInt32(tbIDSupplier.Text))) { // Modification dd fournisseur sélectionné Supplier fournisseur = Modele.GetSupplierById(Convert.ToInt32(tbIDSupplier.Text)); if (fournisseur != null) { Modele.UpdateSupplier(fournisseur, (Supplier)objectBinding); DisplayMessage("Modification réussi!"); } } else { //Ajout d'un fournisseur Modele.AddSupplier((Supplier)objectBinding); objectBinding = new Supplier(); panelClient.DataContext = objectBinding; DisplayMessage("Enregistrement réussi!"); } Frame.Navigate(typeof(Client_Fournisseur), "Fournisseurs"); } else { DisplayMessage("Il est nécessaire de remplir au moins le champ Nom de l'entreprise pour enregistrer."); } }
/// <summary> /// Initialisation, première étape du cycle de vie donc on en profite pour créer notre modèle seulement s'il n'existe pas dans la session /// Après quoi, on ne le referra pas inutilement /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Init(object sender, EventArgs e) { //On ouvre pas une connexion si le modèle est déjà construit ! //Il y a une nuance avec le postback ici car si on a frappé un problème dans le code, on aura mis le modèle à null dans la session //Ceci nous laisse donc une chance de le reconstruire ! if (Session["modeleClient"] == null) { //Gestion des exception essentielle, on gère du code "dangereux" try { //On effectue la connexion et on l'obtient en retour bd = new ConnexionBD(); OleDbConnection connection = bd.ConnectToDB(sqlDataSource1.ConnectionString); //On Instancie notre modèle client en lui passant la connection reçue modeleClient = new Modele(connection); //Si tout a fonctionné, on stocke notre modèle dans la session. C'est la meilleure façon car un PostBack va tout effacer ce qu'on vient de faire ! Session["modeleClient"] = modeleClient; } catch (Exception exc) { //message d'erreur comme quoi la BD ne sera pas disponible modeleClient.RollbackTransaction(); System.Diagnostics.Debug.Write(exc); } } }
public EditModeleView(Modele _input) { InitializeComponent(); SelectedModele = _input; Grandeurs = new ObservableCollection <Grandeur>(Grandeur.Ensemble); LignesProduits = new ObservableCollection <LigneProduit>(LigneProduit.Ensemble); }
void testChainOfResposibility() { ObjetBase vehicule1 = new ProjetSI73.ChainOfResponsibility.Vehicule( "Auto++ KT500 Véhicule d’occasion en bon état "); Console.WriteLine(vehicule1.donneDescription()); ObjetBase modele1 = new Modele("KT400", "Le véhicule spacieux et confortable"); ObjetBase vehicule2 = new ProjetSI73.ChainOfResponsibility.Vehicule(null); vehicule2.suivant = modele1; Console.WriteLine(vehicule2.donneDescription()); ObjetBase marque1 = new Marque("Auto++", "La marque des autos", "de grande qualité"); ObjetBase modele2 = new Modele("KT700", null); modele2.suivant = marque1; ObjetBase vehicule3 = new ProjetSI73.ChainOfResponsibility.Vehicule(null); vehicule3.suivant = modele2; Console.WriteLine(vehicule3.donneDescription()); ObjetBase vehicule4 = new ProjetSI73.ChainOfResponsibility.Vehicule(null); Console.WriteLine(vehicule4.donneDescription()); }
//Si le bouton "Se connecter" est cliqué. protected void ButtonConnect_Click(object sender, EventArgs e) { string lastName = TextBoxLastName.Text; string firstName = TextBoxFirstName.Text; if (Session["modeleClient"] != null) { //On le récupère et on demande les enregistrements des clients selon la requête passée en paramètre Modele modele = (Modele)Session["modeleClient"]; OleDbDataReader readerSelect = modele.ReadClient("SELECT * FROM CLIENT WHERE iDTypeClient = 4"); string iD = readerSelect.GetName(1); string iD2 = readerSelect.GetName(2); while (readerSelect.Read()) { if (lastName == readerSelect[iD].ToString() && firstName == readerSelect[iD2].ToString()) { //<JCOTE> PanelAdmin.Visible = false; ImageButtonPasserUneCommande.Enabled = true; ImageButtonPasserUneCommande.Visible = true; ImageButtonDeconnection.Enabled = true; ImageButtonDeconnection.Visible = true; Session["adminConnected"] = true; //</JCOTE> } } readerSelect.Close(); } }
public towar(string idt, string idm) { IDmiasto = idm; IDtowar = idt; TableArticle towar = Modele.ZnajdzTowar(idt); cenaDef = towar.GetPrice(); produkcjaDef = towar.GetProduction(); zapotrzebowanieDef = towar.GetRequisition(); TableArtInTown towarW = Modele.ZnajdzTowarWMiescie(idt, idm); ilosc = towarW.GetNumber(); produkcjaMod = towarW.GetProduction(); zapotrzebowanieMod = towarW.GetRequisition(); TableTown miasto = Modele.ZnajdzMiasto(idm); populacja = miasto.GetPopulation(); cenaKup = 0; cenaSp = 0; prodAkt = 0; zapoAkt = 0; }
public static string kup(string IDkarawana, string IDmiasto, string IDtowar, int ile, int cena) { int pojemnosc = przekaznik.PoliczPojemnosc(IDkarawana); int obciazenie = przekaznik.PoliczObciozenie(IDkarawana); TableArtInTown towarMiasto = Modele.ZnajdzTowarWMiescie(IDtowar, IDmiasto); TableArtInCaravan towarKarawana = Modele.ZnajdzTowarWKarawanie(IDtowar, IDkarawana); if (cena == -1) { return("Ten towar nie jest na sprzedarz"); } if (towarMiasto.GetNumber() < ile) { return("Chcesz kupić więcej towaru niż jest w mieście"); } int dostepnaMasa = pojemnosc - obciazenie; if (dostepnaMasa < ile) { return("Tyle towaru nie zmieści się w naszej karawanie"); } int kwota = ile * cena; if (kwota > Modele.getGold()) { return("Nie masz dość złota!"); } towarMiasto.SetNumber(towarMiasto.GetNumber() - ile); towarKarawana.SetNumber(towarKarawana.GetNumber() + ile); Modele.setGold(Modele.getGold() - kwota); return("done"); }
public JsonResult GetEquipmentsByPost() { using (db_inventaireContext context = new db_inventaireContext()) { List <TempInvent> equipments = context.TempInvent.ToList(); List <EquipmentConnected> equipmentsConnected = new List <EquipmentConnected>(); foreach (TempInvent e in equipments) { Modele modele = context.Modele.SingleOrDefault(e2 => e2.Description.Equals(e.ModelName)); EquipmentConnected equipment = new EquipmentConnected(); if (modele == null) { equipment.exist = false; } else { equipment.SNDetected = modele.SnDetectable; } equipment.ModelDetected = e.ModelDetected; equipment.vendorDetected = e.VendorDetected; equipment.SN = e.Sn; equipment.NomPost = e.NomPost; equipment.ModelName = e.ModelName; equipment.VendorName = e.VendorName; equipment.Type = e.Type; equipmentsConnected.Add(equipment); } return(Json(equipmentsConnected)); } }
public static string DajCzasS() { int x = Modele.getTime(); string y = x.ToString(); return(y); }
public static string DajKaseS() { int x = Modele.getGold(); string y = x.ToString(); return(y); }
public ActionResult createModele(Modele modele, FormCollection collection) { if (ModelState.IsValid) { try { if (etat) { BissInventaireEntities.Instance.Modele.Add(modele); BissInventaireEntities.Instance.SaveChanges(); return(RedirectToAction("getModele")); } else { return(RedirectToAction("Index", "Error")); } } catch (Exception ex) { LogThread.WriteLine(ex.Message); return(RedirectToAction("Index", "Error")); } } else { return(View()); } }
public void UpdateCategorie_ModeleDetached(Modele e) { Modele existing = FindCategorie_ModeleById(e.IdModele); ((IObjectContextAdapter)DataContext).ObjectContext.Detach(existing); this.DataContext.Entry(e).State = EntityState.Modified; }
private async void RecupDonnees() { await Modele.LoadData(); Modele.Resultat(); MyFrame.Navigate(typeof(Views.Dashboard)); NavigationCortana.Navigation(MyFrame); }
/// <summary> /// Constructeur de l'objet Controler /// </summary> public Controler() { //Création d'un objet modele à la création du controleur Modele modele = new Modele(); //Join le modèle créé dans le constructeur avec celui qui local this.modele = modele; }
public ActionResult DeleteConfirmed(int id) { Modele modele = db.Modeles.Find(id); db.Modeles.Remove(modele); db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// Cette méthode liste tous les Commandes de la base de données et envoie les données en construction dans la table /// </summary> public void ListerCommandes() { //Gestion des exception essentielle, on gère du code "dangereux" try { //On s'assure que le modèle client est disponible if (Session["modeleClient"] != null) { //On le récupère et on demande les enregistrements des clients selon la requête passée en paramètre Modele modele = (Modele)Session["modeleClient"]; //Récupère les informations de la commande à modifier. OleDbDataReader readerSelectTabSelected = modele.ReadClient("SELECT Jeu.Titre, Jeu.Prix, CommandeJeu.CodeJeu, CommandeJeu.Quantité, CommandeJeu.DateCommande,CommandeJeu.IdCommande, Entrepot.Ville, Entrepot.Pays" + " FROM Jeu INNER JOIN (CommandeJeu INNER JOIN Entrepot ON CommandeJeu.IdEntrepot=Entrepot.IdEntrepot) ON Jeu.CodeJeu=CommandeJeu.CodeJeu " + "WHERE IdCommande=" + Request.QueryString["IdCommande"] + " ORDER BY CommandeJeu.DateCommande"); //On envoie notre table en construction ConstruireLabelTabSelected(readerSelectTabSelected); //!!!!!!!!!!!!!!!!!!!!!!!! //CECI EST ESSENTIEL AVANT DE FAIRE UNE AUTRE REQUETE, CECI PERMETTRA UNE AUTRE //REQUÊTE SUR LA COMMANDE QUI A ÉTÉ OUVERTE DANS LE MODÈLE. MÊME SI C'ÉTAIT LA DERNIÈRE REQUÊTE DU LOT IL FAUT LE FAIRE !!! //!!!!!!!!!!!!!!!!!!!!!!!! readerSelectTabSelected.Close(); //Récupère le titre et le code de touts les jeux pour les ajouter dans la liste déroulante de jeu. OleDbDataReader readerSelectJeu = modele.ReadClient("SELECT Titre, CodeJeu FROM Jeu"); //On envoie notre table en construction ConstruireDropDownList(DropDownListJeu, readerSelectJeu, false); //!!!!!!!!!!!!!!!!!!!!!!!! //CECI EST ESSENTIEL AVANT DE FAIRE UNE AUTRE REQUETE, CECI PERMETTRA UNE AUTRE //REQUÊTE SUR LA COMMANDE QUI A ÉTÉ OUVERTE DANS LE MODÈLE. MÊME SI C'ÉTAIT LA DERNIÈRE REQUÊTE DU LOT IL FAUT LE FAIRE !!! //!!!!!!!!!!!!!!!!!!!!!!!! readerSelectJeu.Close(); //Récupère la ville, le pays et Id des entrepot de touts les entrepot pour les ajouter dans la liste déroulante de jeu. OleDbDataReader readerSelectEntrepot = modele.ReadClient("SELECT Ville, Pays, IdEntrepot FROM Entrepot"); //On envoie notre table en construction ConstruireDropDownList(DropDownListEntrepot, readerSelectEntrepot, true); //!!!!!!!!!!!!!!!!!!!!!!!! //CECI EST ESSENTIEL AVANT DE FAIRE UNE AUTRE REQUETE, CECI PERMETTRA UNE AUTRE //REQUÊTE SUR LA COMMANDE QUI A ÉTÉ OUVERTE DANS LE MODÈLE. MÊME SI C'ÉTAIT LA DERNIÈRE REQUÊTE DU LOT IL FAUT LE FAIRE !!! //!!!!!!!!!!!!!!!!!!!!!!!! readerSelectEntrepot.Close(); } } catch (Exception exc) { //Si le probleme provenait de la transaction du modele, on la Rollback Modele modele = (Modele)Session["modeleClient"]; modele.RollbackTransaction(); //et on invalide le modele, il pourra être reconstruit en PostBack Session["modeleClient"] = null; System.Diagnostics.Debug.Write(exc); } }
public void zmianaIlosci() { policzZapotrzebowanie(); policzProdukcje(); int wynik = 0; int niedobor = 0; ilosc -= zapoAkt; if (ilosc < 0) { wynik--; niedobor = ilosc * -1; ilosc = 0; } if (niedobor == 0) { ilosc += prodAkt; } else { ilosc += prodAkt; niedobor /= 2; ilosc -= niedobor; if (ilosc < 0) { ilosc = 0; wynik--; } } double roznica; if (zapoAkt == 0) { roznica = 0; } else { roznica = ilosc / zapoAkt; } if (roznica >= 5) { wynik++; } TableArtInTown towar = Modele.ZnajdzTowarWMiescie(IDtowar, IDmiasto); towar.SetNumber(ilosc); TableTown miasto = Modele.ZnajdzMiasto(IDmiasto); int prosp = miasto.GetProsperity(); prosp = prosp + wynik; miasto.SetProsperity(prosp); }
//Fonction qui liste le jeu sélectionné dans la page précédente. public void ListerJeuSelectionné() { //<sspeichert> //On récupère en get la clé du site web. string codeJeu = Request.QueryString["codeJeu"]; //</sspeichert> //Gestion des exceptions essentielle, on gère du code "dangereux" try { //On s'assure que le modèle client est disponible if (Session["modeleClient"] != null) { //On le récupère et on demande les enregistrements des clients selon la requête passée en paramètre Modele modele = (Modele)Session["modeleClient"]; //<sspeichert> OleDbDataReader readerSelect = modele.ReadClient("SELECT Jeu.CodeJeu, Jeu.Titre, Jeu.Prix, Jeu.Plateforme, TypeJeu.Genre, Jeu.CodeCompagnie, Jeu.Description, Jeu.Image FROM Jeu INNER JOIN TypeJeu ON Jeu.IdGenre = TypeJeu.IdGenre WHERE Jeu.CodeJeu ='" + codeJeu + "'"); //Pendant que le reader est en train d'être lu, on entre while (readerSelect.Read()) { if (codeJeu == readerSelect[0].ToString()) { //ImageJeu.ImageUrl = "~/img/miniatures/" + readerSelect["Image"].ToString(); LabelTitreDuJeu.Text = "Titre du jeu :" + readerSelect["Titre"].ToString(); LabelGenre.Text = "Genre :" + readerSelect["Genre"].ToString(); LabelPlateforme.Text = "Plateforme :" + readerSelect["Plateforme"].ToString(); LabelPrix.Text = "Prix :" + readerSelect["Prix"].ToString(); LabelDeveloppeur.Text = "Developpeur :" + readerSelect["CodeCompagnie"].ToString(); LabelSynopsis.Text = "Synopsis :" + readerSelect["Description"].ToString(); } } //!!!!!!!!!!!!!!!!!!!!!!!! //CECI EST ESSENTIEL AVANT DE FAIRE UNE AUTRE REQUETE, CECI PERMETTRA UNE AUTRE //REQUÊTE SUR LA COMMANDE QUI A ÉTÉ OUVERTE DANS LE MODÈLE. MÊME SI C'ÉTAIT LA DERNIÈRE REQUÊTE DU LOT IL FAUT LE FAIRE !!! //!!!!!!!!!!!!!!!!!!!!!!!! readerSelect.Close(); //<sspeichert> } } catch (Exception exc) { //Si le probleme provenait de la transaction du modele, on la Rollback Modele modele = (Modele)Session["modeleClient"]; modele.RollbackTransaction(); //et on invalide le modele, il pourra être reconstruit en PostBack Session["modeleClient"] = null; System.Diagnostics.Debug.Write(exc); } }
/// <summary> /// Execution de la procedure stocké /// Recupere la liste de tous les equipements par centre /// </summary> /// <param name="num"></param> /// <returns></returns> public List <Equipement> GetEquipementByCentre(int num) { using (DbConnection db = DAOConnection.GetConnexion()) { using (DbCommand cde = db.CreateCommand()) { cde.CommandText = "GetEquipementsByIdCentre"; cde.CommandType = CommandType.StoredProcedure; DbParameter odbP1 = cde.CreateParameter(); odbP1.DbType = System.Data.DbType.String; odbP1.Direction = System.Data.ParameterDirection.Input; odbP1.ParameterName = "@num"; odbP1.Value = num; cde.Parameters.Add(odbP1); List <Equipement> lstEqui = new List <Equipement>(); try { using (DbDataReader reader = cde.ExecuteReader()) { while (reader.Read()) { string numSerie = reader.GetString(0); string nomModele = reader.GetString(1); int numModele = reader.GetInt32(2); decimal tarif = reader.GetDecimal(3); int codetarif = reader.GetInt32(4); string typeE = reader.GetString(5); int idtype = reader.GetInt32(6); DateTime?dt = reader.GetDateTime(7); TypeEquipement te = new TypeEquipement(0, typeE); Tarif Letarif = new Tarif(Convert.ToDouble(tarif), dt); Modele m = new Modele(numModele, nomModele, Letarif, te); Equipement e = new Equipement(m, numSerie); lstEqui.Add(e); } reader.Close(); } } catch (DbException se) { throw new DAOExceptionClient("[DAO] GetClientByName :\n" + se.Message, se); } return(lstEqui); } //End using command } //End using connection }
private int dobrobyt; //uj wie public miasto(string ID) { TableTown tmp = Modele.ZnajdzMiasto(ID); id = ID; populacja = tmp.GetPopulation(); gotowosc = tmp.GetMilitary(); zywnosc = tmp.GetFood(); dobrobyt = tmp.GetProsperity(); }
public JsonResult UpdateModel([FromBody] Modele modele) { using (db_inventaireContext context = new db_inventaireContext()) { context.Modele.Update(modele); context.SaveChanges(); } return(Json(modele)); }
public static ModeleDto ToDto(this Modele input) { return(new ModeleDto { Id = input.Id, CategorieNom = input.CategorieNom, Marque = input.Marque, Nom = input.Nom, NbrSieges = input.NbrSieges.ToString() }); }
public ActionResult Edit([Bind(Include = "IdModelu,NazwaModelu,MarkiRefId")] Modele modele) { if (ModelState.IsValid) { db.Entry(modele).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.MarkiRefId = new SelectList(db.Markis, "IdMarki", "NazwaMarki", modele.MarkiRefId); return(View(modele)); }
/// <summary> /// Dla zadanych szerokości i wysokości geograficznej wyszukuje w bazie i zwraca lokacje, które znajdują się w pobliżu. /// (Może dla testów na razie niech zwraca po prostu wszystkie lokacje?) /// </summary> /// <param name="lat"></param> /// <param name="lng"></param> /// <returns></returns> /// <summary> /// Dodaje lokację do bazy. /// /// </summary> /// <param name="lokacja">model lokacji do dodania</param> /// <param name="id">jesli się powiodło - tutaj zostanie zwrócony ID dodanej lokacji</param> /// <param name="wiadomosc">W razie niepowodzenia - tutaj zostanie zwrócona informacja o tym, co poszło nie tak</param> /// <returns>true jeśli się powiodło, false jeśli nie</returns> public static bool DodajLubEdytuj(Modele.Lokacja lokacja, out int id, out string wiadomosc) { id = -1; wiadomosc = "Ta metoda nie jest jeszcze zaimplementowana."; if (lokacja == null) { wiadomosc = "Obiekt lokacja nie jest zdefiniowany"; return false; } else { //edycja if (lokacja.Id != null) { if (DAL.DatabaseUtils.ExistsElement("SELECT FIRST 1 1 FROM LOCATION L WHERE L.ID = '" + lokacja.Id + "';")) /* && !DAL.DatabaseUtils.ExistsElement("SELECT FIRST 1 1 FROM LOCATION L WHERE L.NAZWA = '" + lokacja.Nazwa + "';"))*/ { //edycja DAL.DatabaseUtils.DatabaseCommand( string.Format( "UPDATE LOCATION SET NAZWA = '{0}', LONGITUDE = {1}, LATITUDE = {2}, STREET = '{3}', ZIP_CODE = '{4}', CITY = '{5}' WHERE(ID = {6})", lokacja.Nazwa, lokacja.Lng.ToString(System.Globalization.CultureInfo.InvariantCulture), lokacja.Lat.ToString(System.Globalization.CultureInfo.InvariantCulture), lokacja.Ulica ?? "", lokacja.KodPocztowy ?? "", lokacja.Miasto ?? "", lokacja.Id )); return true; } } else//insert { WroBL.DAL.DatabaseUtils.DatabaseCommand( "INSERT INTO LOCATION (NAZWA, LONGITUDE, LATITUDE, STREET, ZIP_CODE, CITY) VALUES ('" +lokacja.Nazwa+"', " +lokacja.Lng.ToString(System.Globalization.CultureInfo.InvariantCulture)+", " + lokacja.Lat.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", '" +lokacja.Ulica+"', '" +lokacja.KodPocztowy+"', '" +lokacja.Miasto+"');"); Int32.TryParse( WroBL.DAL.DatabaseUtils.GetOneElement("SELECT l.id from location l where l.nazwa = '" + lokacja.Nazwa + "';"), out id); return true; } if (!DAL.DatabaseUtils.ExistsElement("SELECT FIRST 1 1 FROM LOCATION L WHERE L.NAZWA = '" + lokacja.Nazwa + "';")) { DAL.DatabaseUtils.DatabaseCommand("INSERT INTO LOCATION(NAZWA, LONGITUDE, LATITUDE, STREET, ZIP_CODE, CITY)"+ " VALUES('" + lokacja.Nazwa + "', " + lokacja.Lng.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", " + lokacja.Lat.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", '" + lokacja.Ulica + "', '" + lokacja.KodPocztowy + "', '" + lokacja.Miasto + "'); "); var success = Int32.TryParse(DAL.DatabaseUtils.GetOneElement("SELECT L.ID FROM LOCATION L WHERE L.NAZWA = '" + lokacja.Nazwa + "'"), out id); wiadomosc = "OK"; return true; } else { wiadomosc = "Lokacja z taką nazwą już istnieje"; return false; } } }
public static bool UsunWydarzenie(Modele.Wydarzenie wydarzenie, out int id) { id = 0; if (DAL.DatabaseUtils.ExistsElement("SELECT FIRST 1 1 FROM EVENT E WHERE E.ID="+wydarzenie.Id)) { DAL.DatabaseUtils.DatabaseCommand("DELETE FROM EVENT WHERE ID=" + wydarzenie.Id + ";"); Int32.TryParse(wydarzenie.Id.ToString(), out id); return true; } return false; }
/// <summary> /// Dodaje wydarzenie do bazy /// </summary> /// <param name="wydarzenie">model wydarzenia, które ma zostać dodane</param> /// <param name="id">jesli się powiodło - tutaj zostanie zwrócony ID dodanego wydarzenia</param> /// <param name="wiadomosc">W razie niepowodzenia - tutaj zostanie zwrócona informacja o tym, co poszło nie tak</param> /// <returns>true jeśli się powiodło, false jeśli nie</returns> public static bool DodajLubEdytuj(Modele.Wydarzenie wydarzenie, out int id, out string wiadomosc) { id = -1; if ( wydarzenie == null) { wiadomosc = "Obiekt wydarzenia jest pusty."; return false; } //dodawanie lokacji int idLokacji; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Maciusiu, ttutaj został ten if wyrzucony, bo edytujemyt wydarzenie, a nie edytujemy lokacji, to ten if sie wysypuje i rzuca falsem i kończy działanie metody //if (DodajLubEdytuj(wydarzenie.Lokalizacja, out idLokacji, out wiadomosc) == false) // return false; DodajLubEdytuj(wydarzenie.Lokalizacja, out idLokacji, out wiadomosc); if ( wydarzenie.Id == null) { var dataDodania = DateTime.Now; //dodawanie wydarzenia DAL.DatabaseUtils.DatabaseCommand("INSERT INTO EVENT(NAME, \"DATE\", PRICE, LOCATION, DESCRIPTION, OPERATOR, ADD_DATE, LINK)" + " VALUES('" + wydarzenie.Nazwa + "',' " + wydarzenie.Data + "', " + wydarzenie.Cena.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", '" + idLokacji + "', '" + wydarzenie.Opis + "', '" + wydarzenie.IdOperatora + "', '" + dataDodania + "', '" + wydarzenie.Link + "'); "); if ( !Int32.TryParse( DAL.DatabaseUtils.GetOneElement("SELECT L.ID FROM EVENT L WHERE L.NAME = '" + wydarzenie.Nazwa + "' AND L.ADD_DATE = '" + dataDodania + "'"), out id)) { wiadomosc = "Problem z dodaniem wydarzenia."; return false; } else { DAL.DatabaseUtils.DatabaseCommand("INSERT INTO CAT2EVENT(EVENT,CATEGORIES) VALUES (" + id + "," + wydarzenie.IdKategorii + ");"); } wiadomosc = "OK"; } else { //Ten update tak dziwnie wygląda, bo nie może być tak, że: LOCATION=,DESCRIPTION....[PUSTE PO LOCATION], //ale update działa poprawnie, ewentualnie można ejszcze bardzoej potestować. //Add date bedzie działało, że to jets data ostatniej edycji, bo inaczej jest ciężko tego update napisać, DAL.DatabaseUtils.DatabaseCommand(string.Format("UPDATE \"EVENT\" SET {0} {1}" +"{2} {3} {4}" +"{5} {6} ADD_DATE='"+DateTime.Now+"' WHERE (ID = {7});", !String.IsNullOrEmpty(wydarzenie.Nazwa)? "NAME = '"+wydarzenie.Nazwa+"',":"", wydarzenie.Data.ToString()!= "01.01.0001 00:00:00" ? "\"DATE\" = '"+wydarzenie.Data+"',":"", wydarzenie.Cena!=0?"PRICE = "+wydarzenie.Cena+",":"", wydarzenie.IdLokacji!=null?"LOCATION = "+wydarzenie.IdLokacji+",":"", !String.IsNullOrEmpty(wydarzenie.Opis)? "DESCRIPTION = '"+wydarzenie.Opis+"',":"", wydarzenie.IdOperatora!=0? "OPERATOR ="+wydarzenie.IdOperatora+" ,":"", !String.IsNullOrEmpty(wydarzenie.Link)? "LINK = '"+wydarzenie.Link+"',":"", wydarzenie.Id)); Int32.TryParse(wydarzenie.Id.ToString(), out id); DAL.DatabaseUtils.DatabaseCommand("UPDATE CAT2EVENT C SET C.CATEGORIES = " + wydarzenie.IdKategorii + " WHERE C.EVENT=" + id); } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //delikatnie poprawiłem funkcję dodawania obrazków tak, że może byc pusta lista, //można sprawdzić //dodawanie obrazkow if (id != -1) { if (! Dodaj(wydarzenie.LinkiDoObrazkow, id, out wiadomosc)) { wiadomosc = "Wydarzenie zostało dodane, ale wystąpił problem z dodaniem obrazów."; return false; } return true; } return true; }