public void crudFormatiCarta() { using (LumenEntities context = new LumenEntities()) { Random r = new Random(); FormatoCarta fc = new FormatoCarta(); fc.id = Guid.NewGuid(); fc.descrizione = "Test-" + r.Next(1000, 9999); fc.prezzo = r.Next(1, 50); fc.attivo = true; fc.ordinamento = (short)r.Next(1, 100); context.FormatiCarta.Add(fc); int test = context.SaveChanges(); Assert.IsTrue(test > 0); var trovato = context.FormatiCarta.Any(c => c.descrizione.StartsWith("Test-")); Assert.IsTrue(trovato); FormatoCarta carta = context.FormatiCarta.First(c => c.descrizione.StartsWith("Test-")); Assert.IsNotNull(carta); } }
public void crudFotografia2() { using (LumenEntities context = new LumenEntities()) { Random r = new Random(); Fotografia f = new Fotografia(); f.id = Guid.NewGuid(); f.didascalia = "Test-" + r.Next(1000, 9999); f.numero = r.Next(1, 1000000); f.nomeFile = "Test"; f.dataOraAcquisizione = DateTime.Now; f.giornata = DateTime.Today; f.fotografo = context.Fotografi.First(); f.evento = context.Eventi.FirstOrDefault(); context.Fotografie.Add(f); int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
public void ricercaTest() { ParamCercaFoto param = new ParamCercaFoto(); param.giornataIniz = new DateTime(2000, 1, 1); param.giornataFine = new DateTime(2299, 12, 31); using (LumenEntities dbContext = new LumenEntities()) { Evento ev = dbContext.Eventi.First(); Fotografo op = dbContext.Fotografi.First(); Fotografia f = dbContext.Fotografie.First(); f.evento = ev; f.fotografo = op; f.faseDelGiorno = (short)FaseDelGiorno.Mattino; f.didascalia = "W IL POLLO ARROSTO"; dbContext.SaveChanges(); param.numeriFotogrammi = "3, 5, 7," + f.numero; param.eventi = new Evento[] { ev }; param.fotografi = new Fotografo [] { op }; param.fasiDelGiorno = new FaseDelGiorno [] { FaseDelGiorno.Mattino, FaseDelGiorno.Sera }; param.didascalia = "%POLLO%"; // Ricerca like IList <Fotografia> ris = _impl.cerca(param); Assert.IsTrue(ris.Count > 0); Console.WriteLine(ris.Count); } }
private void elimina() { bool conferma = false; dialogProvider.ShowConfirmation("Sei sicuro di voler eliminare questa Azione Automatica? \n\n(" + azioneAutomaticaSelezionata.nome + ")", "Elimina", (confermato) => { conferma = confermato; }); if (!conferma) { return; } AzioneAuto azione = azioneAutomaticaSelezionata; OrmUtil.forseAttacca <AzioneAuto>(ref azione); LumenEntities dbContext = UnitOfWorkScope.currentDbContext; dbContext.AzioniAutomatiche.Remove(azione); dbContext.SaveChanges(); rileggereAzioniAutomatiche(); }
public void CarrelloTest3EliminaRiga() { #if COSI_FUNZIONA_BENE Guid guid = new Guid("625a1ed1-6e22-4de7-b8c9-2420de1bcb5e"); using (LumenEntities ctx = new LumenEntities()) { Carrello carrello = ctx.Carrelli .Include("righeCarrello") .Single(r => r.id == guid); int conta = 0; RigaCarrello rigaDacanc = null; foreach (var riga in carrello.righeCarrello) { if (++conta == 2) { rigaDacanc = riga; } } if (rigaDacanc != null) { carrello.righeCarrello.Remove(rigaDacanc); ctx.RigheCarrelli.Remove(rigaDacanc); } ctx.SaveChanges(); } #endif // Cerco un carrello che non sia venduto, con almeno due righe Guid guid = Guid.Empty; using (LumenEntities ctx = new LumenEntities()) { Carrello carrello = ctx.Carrelli .Include("righeCarrello") .Where(c => c.venduto == false && c.righeCarrello.Count > 1) .FirstOrDefault(); if (carrello != null) { guid = carrello.id; } } if (guid != Guid.Empty) { // Carrello carrelloTest = recuperaCarrelloPerTest(); using (GestoreCarrello ges = new GestoreCarrello()) { ges.caricaCarrello(guid); RigaCarrello rigaDacanc = ges.carrello.righeCarrello.AsEnumerable().ElementAt(1); ges.removeRiga(rigaDacanc); ges.salvare(); } } }
public void Init() { LumenApplication app = LumenApplication.Instance; IObservable <ScaricoFotoMsg> observable = app.bus.Observe <ScaricoFotoMsg>(); observable.Subscribe(this); _impl = new ScaricatoreFotoSrvImpl(); _impl.start(); // ------- using (LumenEntities dbContext = new LumenEntities()) { InfoFissa i = dbContext.InfosFisse.Single <InfoFissa>(f => f.id == "K"); _mario = Utilita.ottieniFotografoMario(dbContext); // Se hai fatto bene la configurazione, il fotografo artista deve sempre esistere _artista = dbContext.Fotografi.Single(f => f.id == Configurazione.ID_FOTOGRAFO_DEFAULT); // cerco l'evento con la descrizione _ballo = (from e in dbContext.Eventi where e.descrizione == "BALLO" select e).FirstOrDefault(); if (_ballo == null) { _ballo = new Evento(); _ballo.descrizione = "BALLO"; _ballo.id = Guid.NewGuid(); dbContext.Eventi.Add(_ballo); } _briscola = (from e in dbContext.Eventi where e.descrizione == "BRISCOLA" select e).FirstOrDefault(); if (_briscola == null) { _briscola = new Evento(); _briscola.id = Guid.NewGuid(); _briscola.descrizione = "BRISCOLA"; dbContext.Eventi.Add(_briscola); } dbContext.SaveChanges(); } }
/// <summary> /// Elimino e distruggo le foto sparse indicate /// </summary> /// <param name="fotosDaCanc"></param> public int elimina(IEnumerable <Fotografia> fotosDaCanc) { _possoChiudere = false; int conta = 0; _giornale.Info("E' stata richiesta la distruzione di " + fotosDaCanc.Count() + " fotografie. Iniizo eliminazione"); LumenEntities lumenEntities = UnitOfWorkScope.currentDbContext; foreach (Fotografia ff in fotosDaCanc) { Fotografia ff2 = ff; OrmUtil.forseAttacca <Fotografia>(ref ff2); AiutanteFoto.disposeImmagini(ff2); // Elimino la foto da disco seEsisteCancella(PathUtil.nomeCompletoRisultante(ff2)); seEsisteCancella(PathUtil.nomeCompletoProvino(ff2)); seEsisteCancella(PathUtil.nomeCompletoOrig(ff2)); // Poi dal database lumenEntities.Fotografie.Remove(ff2); _giornale.Debug("Eliminata Fotogarfia dal db: id=" + ff2.id + " num=" + ff2.numero); ++conta; } int test3 = lumenEntities.SaveChanges(); _giornale.Info("Eliminazione foto completata. Tot = " + conta); _giornale.Debug("la SaveChanges ha ritornato: " + test3); if (test3 > 0) { // Rilancio un messaggio in modo che tutta l'applicazione (e tutti i componenti) vengano notificati FotoEliminateMsg msg = new FotoEliminateMsg(this as IEliminaFotoVecchieSrv); msg.listaFotoEliminate = fotosDaCanc; pubblicaMessaggio(msg); } _possoChiudere = true; return(conta); }
// Se non esistono le informazioni fisse, allora le creo di default internal static InfoFissa forseCreaInfoFisse() { LumenEntities objContext = UnitOfWorkScope.currentDbContext; InfoFissa infoFissa = objContext.InfosFisse.SingleOrDefault(f => f.id == "K"); if (infoFissa == null) { _giornale.Info("Informazioni fisse non trovate. Le creo con i default"); infoFissa = new InfoFissa(); infoFissa.id = "K"; infoFissa.pixelProvino = 400; infoFissa.urlPrefixSelfServiceWeb = "http://server-lumen:80"; objContext.InfosFisse.Add(infoFissa); objContext.SaveChanges(); } return(infoFissa); }
public void crudAzioneAuto() { using (LumenEntities context = new LumenEntities()) { Random r = new Random(); AzioneAuto aa = new AzioneAuto(); aa.id = Guid.NewGuid(); aa.nome = "Test-" + r.Next(1000, 9999); aa.attivo = false; aa.correzioniXml = "Questa è una prova"; context.AzioniAutomatiche.Add(aa); int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
public void crudEvento() { using (LumenEntities context = new LumenEntities()) { Random r = new Random(); Evento ev = new Evento(); ev.id = Guid.NewGuid(); ev.descrizione = "Test-" + r.Next(1000, 9999); ev.attivo = false; context.Eventi.Add(ev); int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
public void DoPromoPolimorfTest() { using (LumenEntities dbContext = new LumenEntities()) { PromoStessaFotoSuFile p1 = (PromoStessaFotoSuFile)dbContext.Promozioni.SingleOrDefault(p => p.id == 1); bool nuovo1 = (p1 == null); if (nuovo1) { p1 = new PromoStessaFotoSuFile(); } p1.id = 1; p1.descrizione = "prova1"; p1.prezzoFile = 1; if (nuovo1) { dbContext.Promozioni.Add(p1); } // PromoPrendiNPaghiM p2 = (PromoPrendiNPaghiM)dbContext.Promozioni.SingleOrDefault(p => p.id == 2); bool nuovo2 = (p2 == null); if (nuovo2) { p2 = new PromoPrendiNPaghiM(); } p2.id = 2; p2.descrizione = "prova2"; p2.qtaDaPrendere = 6; p2.qtaDaPagare = 5; if (nuovo2) { dbContext.Promozioni.Add(p2); } dbContext.SaveChanges(); } }
public void crudScaricoCard() { using (LumenEntities context = new LumenEntities()) { Random r = new Random(); ScaricoCard sc = new ScaricoCard(); sc.id = Guid.NewGuid(); sc.totFoto = (short)r.Next(1, 999); sc.giornata = DateTime.Today; sc.fotografo = context.Fotografi.First(); sc.tempo = DateTime.Now; context.ScarichiCards.Add(sc); int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
internal static int incrementaNumeratoreFoto(int quante) { LumenEntities objContext = UnitOfWorkScope.currentDbContext; InfoFissa infoFissa = objContext.InfosFisse.Single <InfoFissa>(f => f.id == "K"); int ultimoNum = infoFissa.ultimoNumFotogramma; if (ultimoNum > 0) { ultimoNum = eventualeAzzeramento(infoFissa.modoNumerazFoto, infoFissa.ultimoNumFotogramma, infoFissa.dataUltimoScarico); } // Aggiorno sempre e comunque infoFissa.ultimoNumFotogramma = ultimoNum + quante; infoFissa.dataUltimoScarico = DateTime.Today; objContext.SaveChanges(); return(ultimoNum); }
/** * dato il nome del file della immagine, creo l'oggetto Fotografia e lo aggiungo al suo contenitore * (in pratica faccio una insert nel database). */ private Fotografia aggiungiFoto(FileInfo fileInfo, int numFotogramma, DateTime tempoScarico) { _giornale.Debug("Sto per aggiungere la foto " + fileInfo + " al database"); // Ad ogni foto persisto. // Se per esempio ho 500 foto da salvare, non posso permettermi che se una salta, perdo anche le altre 499 ! Fotografia foto = null; LumenEntities objContext = UnitOfWorkScope.currentDbContext; foto = new Fotografia(); foto.id = Guid.NewGuid(); foto.dataOraAcquisizione = tempoScarico; foto.fotografo = _fotografo; foto.evento = _evento; foto.didascalia = _paramScarica.flashCardConfig.didascalia; foto.numero = numFotogramma; foto.faseDelGiorno = (short?)_paramScarica.faseDelGiorno; foto.giornata = LumenApplication.Instance.stato.giornataLavorativa; // il nome del file, lo memorizzo solamente relativo // scarto la parte iniziale di tutto il path togliendo il nome della cartella di base delle foto. // Questo perché le stesse foto le devono vedere altri computer della rete che // vedono il percorso condiviso in maniera differente. foto.nomeFile = PathUtil.nomeRelativoFoto(fileInfo); caricaMetadatiImmagine(fileInfo.FullName, foto); if (foto.dataOraScatto == null || foto.dataOraScatto == DateTime.MinValue) { foto.dataOraScatto = fileInfo.CreationTime; } objContext.Fotografie.Add(foto); objContext.SaveChanges(); _giornale.Debug("Inserita nuova foto: " + foto.ToString() + " ora sono " + contaAggiunteDb); return(foto); }
public void crudConsumoCartaGG() { using (LumenEntities context = new LumenEntities()) { Random r = new Random(); ConsumoCartaGiornaliero cc = new ConsumoCartaGiornaliero(); cc.id = Guid.NewGuid(); cc.diCuiFoto = (short)r.Next(1, 999); cc.diCuiProvini = (short)r.Next(1, 999); cc.totFogli = (short)r.Next(1, 999); cc.giornata = DateTime.Today; cc.formatoCarta = context.FormatiCarta.First(); context.ConsumiCartaGiornalieri.Add(cc); int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
public void crudGiornata() { using (LumenEntities context = new LumenEntities()) { Random r = new Random(); Giornata gg = new Giornata(); gg.id = DateTime.Today; gg.firma = "il Barna"; gg.incassoDichiarato = decimal.Parse("12345,67"); gg.incassoPrevisto = decimal.Parse("12345,67"); gg.orologio = DateTime.Now; gg.totScarti = (short)r.Next(1, 50); context.Giornate.Add(gg); int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
public void crudFotografia() { using (LumenEntities context = new LumenEntities()) { Fotografo ff = context.Fotografi.First(); Evento ee = context.Eventi.FirstOrDefault(); Fotografia foto = new Fotografia(); foto.id = Guid.NewGuid(); foto.dataOraAcquisizione = DateTime.Now; foto.fotografo = ff; foto.evento = ee; foto.didascalia = "TEST"; foto.nomeFile = "nontelodico.jpg"; context.Fotografie.Add(foto); int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
public void crudFotografo() { using (LumenEntities context = new LumenEntities()) { Fotografo ff = new Fotografo(); ff.id = "Barna " + DateTime.Now.ToString("HH-mm-ss"); ff.cognomeNome = "Bernardini Luca"; ff.iniziali = "BL"; context.Fotografi.Add(ff); using (var stream = new MemoryStream()) { Resource2.Image01.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); ff.immagine = stream.ToArray(); } int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
public void crudCarrello2() { using (LumenEntities context = new LumenEntities()) { Random r = new Random(); Carrello cc = new Carrello(); cc.id = Guid.NewGuid(); cc.giornata = DateTime.Today; cc.tempo = DateTime.Today; cc.intestazione = "Test-" + r.Next(1000, 9999); cc.note = "Prova"; cc.prezzoDischetto = r.Next(1, 90); cc.totaleAPagare = r.Next(10, 80); cc.totMasterizzate = (short)r.Next(1, 100); RigaCarrello rc = new RigaCarrello(); rc.id = Guid.NewGuid(); rc.carrello = cc; rc.descrizione = "Test-" + r.Next(1000, 9999); rc.discriminator = "S"; rc.prodotto = context.FormatiCarta.First(); rc.fotografo = context.Fotografi.First(); rc.prezzoLordoUnitario = r.Next(1, 12); rc.quantita = (short)r.Next(1, 12); rc.prezzoNettoTotale = rc.prezzoLordoUnitario * rc.quantita; rc.totFogliStampati = 1; rc.sconto = (decimal)r.Next(1, 12); rc.fotografia = context.Fotografie.First(); rc.bordiBianchi = true; cc.righeCarrello.Add(rc); context.Carrelli.Add(cc); int test = context.SaveChanges(); Assert.IsTrue(test > 0); } }
internal void stornoMasterizzate(Guid idCarrello, short totFotoOk, short totFotoErrate) { _giornale.Debug("Devo stornare " + totFotoErrate + " foto masterizzate dal carrello " + idCarrello + " perché qualcosa è andato storto"); if (carrello != null) { throw new InvalidOperationException("Esiste già un carrello caricato"); } using (new UnitOfWorkScope(true)) { LumenEntities dbContext = UnitOfWorkScope.currentDbContext; var query = from c in dbContext.Carrelli.Include("righeCarrello") where c.id == idCarrello select c; carrello = query.SingleOrDefault(); if (carrello == null) { throw new ObjectNotFoundException("Il carrello con id = " + idCarrello + " non è usabile"); } // Carattere speciale che non c'è sulla tastiera per evitare cancellazioni fraudolente char marca = '\u0251'; // Devo individuare qual'è la riga da modificare foreach (RigaCarrello r in carrello.righeCarrello) { if (r.isTipoMasterizzata) { // Se non ho masterizzato nulla, azzero il totale riga e poi abbasso il totale documento r.descrizione = marca + "Storno foto masterizzate"; r.quantita = 0; } } completaAttributiMancanti(true); dbContext.SaveChanges(); } }
public void clonaFotoTest() { // Carico 3 foto da clonare using (LumenEntities dbContext = new LumenEntities()) { Fotografia[] fotos = dbContext.Fotografie.Take(3).ToArray <Fotografia>(); _impl.clonaFotografie(fotos); foreach (Fotografia foto in fotos) { string pathCartellaFoto = PathUtil.decidiCartellaFoto(foto); string pathCartellaProvino = PathUtil.decidiCartellaProvini(foto); string pathCartellaRisultante = PathUtil.decidiCartellaRisultanti(foto); // Verifico che il file sia stato copiato su disco int countFile = Directory.EnumerateFiles(pathCartellaFoto, Path.GetFileNameWithoutExtension(foto.nomeFile) + "_CLONE_[*.*").Count(); // Verifico che il provino sia stato copiato su disco int countProvino = Directory.EnumerateFiles(pathCartellaProvino, Path.GetFileNameWithoutExtension(foto.nomeFile) + "_CLONE_[*.*").Count(); // Verifico che la risultante sia stata copiato su disco if (foto.imgRisultante != null) { int countRisultante = Directory.EnumerateFiles(pathCartellaRisultante, Path.GetFileNameWithoutExtension(foto.nomeFile) + "_CLONE_[*.*").Count(); } // Verifico il salvataggio sul db int count = dbContext.Fotografie.Where(f => f.numero == foto.numero).Count <Fotografia>(); Assert.IsTrue(count >= 2 && countFile > 0 && countProvino > 0 && countProvino > 0); } dbContext.SaveChanges(); } }
/// <summary> /// Called on the end of the scope. Disposes the ObjectContext. /// </summary> public void Dispose() { if (!_isDisposed) { try { /* End of scope, so clear the thread static * _currentScope member: */ _currentScope = null; Thread.EndThreadAffinity(); if (_saveAllChangesAtEndOfScope) { // Qui ci potrebbero essere delle eccezioni _dbContext.SaveChanges(); } } catch (Exception ee) { _giornale.Error("Salvataggio sul db fallito: " + ErroriUtil.estraiMessage(ee), ee); throw ee; } finally { // In ogni caso devo chiudere tutto _dbContext.Dispose(); _dbContext = null; _isDisposed = true; _giornale.Debug("-Chiudo Unit-Of-Work"); } } else { _giornale.Warn("Come mai casco qui ?? Impossibile. Debuggare!"); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debugger.Break(); } } }
public void carrelloConPezziStaccati() { Carrello c3 = new Carrello { id = Guid.NewGuid(), giornata = DateTime.Today, tempo = DateTime.Now, totaleAPagare = 123m }; c3.righeCarrello = new EntityCollection <RigaCarrello>(); // ---------- FormatoCarta formato; using (LumenEntities dbContext = new LumenEntities()) { formato = dbContext.FormatiCarta.FirstOrDefault(); } Fotografia fotografia; using (LumenEntities dbContext = new LumenEntities()) { fotografia = dbContext.Fotografie.FirstOrDefault(); } Fotografo fotografo; using (LumenEntities dbContext = new LumenEntities()) { fotografo = dbContext.Fotografi.FirstOrDefault(); } // ---------- using (LumenEntities dbContext = new LumenEntities()) { // Creo la riga con gli attributi scalari RigaCarrello r1 = new RigaCarrello { discriminator = RigaCarrello.TIPORIGA_STAMPA, id = Guid.NewGuid(), prezzoLordoUnitario = 5, quantita = 3, prezzoNettoTotale = 15, totFogliStampati = 11, descrizione = "RicaFotoStampata1", }; // Aggiungo le associazioni r1.prodotto = formato; r1.fotografo = fotografo; r1.fotografia = fotografia; // Aggiungo la riga al carrello c3.righeCarrello.Add(r1); } // ---------- using (LumenEntities dbContext = new LumenEntities()) { RigaCarrello r1 = c3.righeCarrello.ElementAt(0); dbContext.Fotografie.Attach(r1.fotografia); dbContext.FormatiCarta.Attach(r1.prodotto as FormatoCarta); dbContext.Fotografi.Attach(r1.fotografo); // The EntityKey property can only be set when the current value of the property is null dbContext.Carrelli.Add(c3); dbContext.SaveChanges(); } }
/** * dato il nome del file della immagine, creo l'oggetto Fotografia e lo aggiungo al suo contenitore * (in pratica faccio una insert nel database). */ private Fotografia aggiungiFotoDB(Fotografia foto, string nomeFileClone) { // Ad ogni foto persisto. // Se per esempio ho 500 foto da salvare, non posso permettermi che se una salta, perdo anche le altre 499 ! Fotografia fotoClone = null; LumenEntities objContext = UnitOfWorkScope.currentDbContext; try { fotoClone = new Fotografia(); fotoClone.id = Guid.NewGuid(); fotoClone.dataOraAcquisizione = foto.dataOraAcquisizione; Fotografo f = foto.fotografo; OrmUtil.forseAttacca <Fotografo>(ref f); fotoClone.fotografo = f; if (foto.evento != null) { Evento e = foto.evento; OrmUtil.forseAttacca <Evento>(ref e); fotoClone.evento = e; } fotoClone.didascalia = foto.didascalia; fotoClone.numero = foto.numero; fotoClone.correzioniXml = foto.correzioniXml; if (foto.imgOrig != null) { fotoClone.imgOrig = (IImmagine)foto.imgOrig.Clone(); } if (foto.imgProvino != null) { fotoClone.imgProvino = (IImmagine)foto.imgProvino.Clone(); } if (foto.imgRisultante != null) { fotoClone.imgRisultante = (IImmagine)foto.imgRisultante.Clone(); } fotoClone.faseDelGiorno = foto.faseDelGiorno; fotoClone.giornata = foto.giornata; // il nome del file, lo memorizzo solamente relativo // scarto la parte iniziale di tutto il path togliendo il nome della cartella di base delle foto. // Questo perché le stesse foto le devono vedere altri computer della rete che // vedono il percorso condiviso in maniera differente. fotoClone.nomeFile = nomeFileClone; objContext.Fotografie.Add(fotoClone); objContext.SaveChanges(); ++conta; _giornale.Debug("Clonata nuova foto: " + foto.ToString() + " ora sono " + conta); } catch (Exception ee) { _giornale.Error("Non riesco ad inserire una foto clonata. Nel db non c'è ma nel filesystem si: " + fotoClone.nomeFile, ee); } return(foto); }
public void simulaUiStaccando() { Carrello c3; using (LumenEntities dbContext = new LumenEntities()) { c3 = new Carrello { id = Guid.NewGuid(), giornata = DateTime.Today, tempo = DateTime.Now, totaleAPagare = 123m }; c3.righeCarrello = new EntityCollection <RigaCarrello>(); } // ---------- FormatoCarta formato; using (LumenEntities dbContext = new LumenEntities()) { formato = dbContext.FormatiCarta.FirstOrDefault(); } Fotografia fotografia; using (LumenEntities dbContext = new LumenEntities()) { fotografia = dbContext.Fotografie.FirstOrDefault(); } Fotografo fotografo; using (LumenEntities dbContext = new LumenEntities()) { fotografo = dbContext.Fotografi.FirstOrDefault(); } // ---------- using (LumenEntities dbContext = new LumenEntities()) { RigaCarrello r1 = new RigaCarrello(); r1.discriminator = RigaCarrello.TIPORIGA_STAMPA; r1.id = Guid.NewGuid(); r1.prezzoLordoUnitario = new Decimal(5); r1.quantita = 3; r1.prezzoNettoTotale = Decimal.Multiply(r1.prezzoLordoUnitario, r1.quantita); r1.descrizione = "RicaFotoStampata1"; r1.totFogliStampati = 11; r1.prodotto = formato; r1.fotografo = fotografo; r1.fotografia = fotografia; c3.righeCarrello.Add(r1); } // ---------- using (LumenEntities dbContext = new LumenEntities()) { RigaCarrello r1 = c3.righeCarrello.ElementAt(0); // Riattacco le associazioni altrimeti si spacca (sembra) dbContext.FormatiCarta.Attach(r1.prodotto as FormatoCarta); dbContext.Fotografi.Attach(r1.fotografo); dbContext.Fotografie.Attach(r1.fotografia); dbContext.Carrelli.Add(c3); try { dbContext.SaveChanges(); } catch (DbEntityValidationException ee) { string msg = ErroriUtil.estraiMessage(ee); Console.WriteLine(msg); throw; } } }
public void crudCarrello() { Guid guid = Guid.NewGuid(); using (LumenEntities context = new LumenEntities()) { // Prima scrivo un carrello da solo. Carrello c = new Carrello(); c.id = guid; c.giornata = DateTime.Today; c.intestazione = "test1"; c.prezzoDischetto = 123; c.tempo = DateTime.Now; c.venduto = false; c.totaleAPagare = 234; // Creo anche una riga RigaCarrello r = new RigaCarrello(); r.id = Guid.NewGuid(); r.prezzoLordoUnitario = 12.34m; r.quantita = 1; r.descrizione = "test case"; r.prezzoNettoTotale = r.prezzoLordoUnitario; r.fotografia = context.Fotografie.FirstOrDefault(); r.fotografo = r.fotografia.fotografo; r.discriminator = RigaCarrello.TIPORIGA_MASTERIZZATA; c.righeCarrello = new List <RigaCarrello>(); c.righeCarrello.Add(r); // Creo anche un incasso fotografo IncassoFotografo i = new IncassoFotografo(); i.id = Guid.NewGuid(); i.fotografo = r.fotografo; i.incasso = r.prezzoNettoTotale; i.incassoMasterizzate = i.incasso; i.contaMasterizzate = 1; c.incassiFotografi = new List <IncassoFotografo>(); c.incassiFotografi.Add(i); context.Carrelli.Add(c); try { context.SaveChanges(); } catch (DbEntityValidationException qq) { foreach (var item in qq.EntityValidationErrors) { foreach (var item2 in item.ValidationErrors) { String errore = item2.ErrorMessage; Console.WriteLine(errore); } } throw; } catch (Exception) { throw; } } using (LumenEntities context = new LumenEntities()) { Carrello ct = context.Carrelli.Single(c => c.id == guid); Assert.IsTrue(ct.intestazione == "test1"); Assert.IsTrue(ct.righeCarrello.Count == 1); ct.intestazione = "test2"; context.SaveChanges(); } using (LumenEntities context = new LumenEntities()) { Carrello ct = context.Carrelli.Single(c => c.id == guid); Assert.IsTrue(ct.intestazione == "test2"); context.Carrelli.Remove(ct); // Se tutto va bene, mi deve buttare via con il trigger di cascade, anche le RigheCarrello e gli IncassiFotografi context.SaveChanges(); } using (LumenEntities context = new LumenEntities()) { Carrello ct = context.Carrelli.SingleOrDefault(c => c.id == guid); Assert.IsNull(ct); } }
public void aggiungiUnaRigaAdUnCarrelloEsistente() { int countRigheCarrello = 0; Carrello carrelloCorrente; using (LumenEntities dbContext = new LumenEntities()) { carrelloCorrente = dbContext.Carrelli.Include("righeCarrello").Take(1).Single(); countRigheCarrello = carrelloCorrente.righeCarrello.Count(); } FormatoCarta formato; using (LumenEntities dbContext = new LumenEntities()) { formato = dbContext.FormatiCarta.First(); } Fotografia fotografia; using (LumenEntities dbContext = new LumenEntities()) { fotografia = dbContext.Fotografie.Include("fotografo").Where(f => f.fotografo != null).First(); } Fotografo fotografo; using (LumenEntities dbContext = new LumenEntities()) { fotografo = dbContext.Fotografi.First(); } using (LumenEntities dbContext = new LumenEntities()) { var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; objectContext.AttachTo("Carrelli", carrelloCorrente); ObjectStateEntry s1 = objectContext.ObjectStateManager.GetObjectStateEntry(carrelloCorrente); objectContext.AttachTo("FormatiCarta", formato); ObjectStateEntry s2 = objectContext.ObjectStateManager.GetObjectStateEntry(formato); objectContext.AttachTo("Fotografie", fotografia); ObjectStateEntry s3 = objectContext.ObjectStateManager.GetObjectStateEntry(fotografia); // ======= Occhio qui !!!! poi ti spiego ===== if (fotografo.id.Equals(fotografia.fotografo.id)) { fotografo = fotografia.fotografo; } else { objectContext.AttachTo("Fotografi", fotografo); } ObjectStateEntry s4 = objectContext.ObjectStateManager.GetObjectStateEntry(fotografo); // ======= Occhio qui !!!! poi ti spiego ===== RigaCarrello riga = objectContext.CreateObject <RigaCarrello>(); riga.id = Guid.NewGuid(); riga.discriminator = RigaCarrello.TIPORIGA_STAMPA; riga.prezzoLordoUnitario = new Decimal(5); riga.quantita = 3; riga.prezzoNettoTotale = Decimal.Multiply(riga.prezzoLordoUnitario, riga.quantita); riga.descrizione = "SaveCarrelloLodingTest"; riga.totFogliStampati = 3; riga.prodotto = formato; riga.fotografo = fotografo; riga.fotografia = fotografia; carrelloCorrente.righeCarrello.Add(riga); s1 = objectContext.ObjectStateManager.GetObjectStateEntry(carrelloCorrente); int quanti = dbContext.SaveChanges(); } // Controllo che le righe siano aumentate di uno. using (LumenEntities dbContext = new LumenEntities()) { var testCarrello2 = dbContext.Carrelli.Include("righeCarrello").Where(c => c.id == carrelloCorrente.id).Single(); Assert.IsTrue(countRigheCarrello + 1 == testCarrello2.righeCarrello.Count); } }
public void simulaUiStaccando2() { Carrello carrello; ObjectStateEntry stato; using (LumenEntities dbContext = new LumenEntities()) { ObjectContext objContext = ((IObjectContextAdapter)dbContext).ObjectContext; carrello = dbContext.Carrelli.FirstOrDefault(c => c.venduto == false); bool trovato = objContext.ObjectStateManager.TryGetObjectStateEntry(carrello, out stato); Assert.IsTrue(trovato); Assert.AreEqual(stato.State, EntityState.Unchanged); } using (LumenEntities dbContext = new LumenEntities()) { ObjectContext objContext = ((IObjectContextAdapter)dbContext).ObjectContext; bool isDetached = dbContext.Entry(carrello).State == EntityState.Detached; Assert.IsTrue(isDetached); // Modifico l'oggetto da staccato Random rnd = new Random(); int randomNumber = rnd.Next(0, 9); carrello.note = carrello.note + randomNumber.ToString(); } using (LumenEntities dbContext = new LumenEntities()) { ObjectContext objContext = ((IObjectContextAdapter)dbContext).ObjectContext; bool isDetached = dbContext.Entry(carrello).State == EntityState.Detached; Assert.IsTrue(isDetached); var poldo = dbContext.Carrelli.Attach(carrello); isDetached = dbContext.Entry(carrello).State == EntityState.Detached; Assert.IsFalse(isDetached); // Qui non ci devono essere modifiche, perché prima ho modificato l'oggetto quando era staccato. int quanti = dbContext.SaveChanges(); Assert.IsTrue(quanti == 0); } // -- Ora provo a modificare l'oggetto da attaccato. using (LumenEntities dbContext = new LumenEntities()) { ObjectContext objContext = ((IObjectContextAdapter)dbContext).ObjectContext; bool isDetached = dbContext.Entry(carrello).State == EntityState.Detached; Assert.IsTrue(isDetached); var poldo = dbContext.Carrelli.Attach(carrello); isDetached = dbContext.Entry(carrello).State == EntityState.Detached; Assert.IsFalse(isDetached); // Modifico l'oggetto da attaccato Random rnd = new Random(); int randomNumber = rnd.Next(0, 9); carrello.note = carrello.note + randomNumber.ToString(); var tt = dbContext.Entry(carrello); Assert.AreEqual(tt.State, EntityState.Modified); } using (LumenEntities dbContext = new LumenEntities()) { ObjectContext objContext = ((IObjectContextAdapter)dbContext).ObjectContext; // Provo a salvare l'oggetto staccato e mi deve dare errore. int quantiQ = dbContext.SaveChanges(); Assert.IsTrue(quantiQ == 0); // Ora forzo lo stato della entità a modificato var poldo = dbContext.Carrelli.Attach(carrello); var test2 = dbContext.Entry(carrello); Assert.AreEqual(test2.State, EntityState.Unchanged); objContext.DetectChanges(); var test3 = dbContext.Entry(carrello); Assert.AreEqual(test3.State, EntityState.Unchanged); test3.State = EntityState.Modified; int quanti = dbContext.SaveChanges(); Assert.IsTrue(quanti > 0); } }
public void carrelloTest() { using (LumenEntities dbContext = new LumenEntities()) { Carrello c1 = new Carrello(); c1.id = Guid.NewGuid(); c1.giornata = DateTime.Today; c1.tempo = DateTime.Now; c1.totaleAPagare = 123m; c1.righeCarrello = new EntityCollection <RigaCarrello>(); _carrelloInserito = c1; // --- RigaCarrello r1 = new RigaCarrello(); r1.fotografia = Costanti.findUnaFotografiaRandom(dbContext); r1.fotografo = r1.fotografia.fotografo; r1.discriminator = RigaCarrello.TIPORIGA_MASTERIZZATA; r1.id = Guid.NewGuid(); r1.prezzoLordoUnitario = new Decimal(20); r1.quantita = 2; r1.prezzoNettoTotale = Decimal.Multiply(r1.prezzoLordoUnitario, r1.quantita); r1.descrizione = "Foto masterizzata"; c1.righeCarrello.Add(r1); _contaMasterizzate++; // --- RigaCarrello r2 = new RigaCarrello(); r2.fotografia = Costanti.findUnaFotografiaRandom(dbContext); r2.discriminator = RigaCarrello.TIPORIGA_STAMPA; r2.id = Guid.NewGuid(); r2.prezzoLordoUnitario = new Decimal(5); r2.quantita = 3; r2.prezzoNettoTotale = Decimal.Multiply(r2.prezzoLordoUnitario, r2.quantita); r2.descrizione = "RicaFotoStampata1"; r2.totFogliStampati = 3; r2.prodotto = Utilita.ottieniFormatoCarta(dbContext, "A4"); r2.fotografo = Utilita.ottieniFotografoMario(dbContext); c1.righeCarrello.Add(r2); _contaStampate++; // --- RigaCarrello r3 = new RigaCarrello(); r3.fotografia = Costanti.findUnaFotografiaRandom(dbContext); r3.discriminator = RigaCarrello.TIPORIGA_STAMPA; r3.id = Guid.NewGuid(); r3.prezzoLordoUnitario = new Decimal(5); r3.quantita = 2; r3.prezzoNettoTotale = Decimal.Multiply(r3.prezzoLordoUnitario, r3.quantita); r3.descrizione = "RicaFotoStampata1"; r3.totFogliStampati = 3; r3.prodotto = Utilita.ottieniFormatoCarta(dbContext, "A4"); r3.fotografo = Utilita.ottieniFotografoMario(dbContext); c1.righeCarrello.Add(r3); _contaStampate++; // --- dbContext.Carrelli.Add(c1); try { dbContext.SaveChanges(); } catch (Exception ee) { String msg = ErroriUtil.estraiMessage(ee); Console.WriteLine(msg); throw ee; } } // Verifico che l'inserimento appena effettuato sia andato bene. queryPolimorficaCorrente(); // provo altre tecniche di query, giusto per sport. queryPolimorficaSql(); queryPolimorfica(); }
/** * Se una stampa è andata male, * tramite la riga che è fallita, ricarico il carrello relativo * e lo vado a stornare. */ public void stornoRiga(Guid idRigaCarrello) { if (carrello != null) { throw new InvalidOperationException("Esiste già un carrello caricato"); } using (new UnitOfWorkScope(true)) { LumenEntities dbContext = UnitOfWorkScope.currentDbContext; var query = from c in dbContext.Carrelli.Include("righeCarrello") where c.righeCarrello.Any(q => q.id == idRigaCarrello) select c; carrello = query.SingleOrDefault(); if (carrello == null) { throw new ObjectNotFoundException("La riga carrello con id = " + idRigaCarrello + " non è usabile"); } // Carattere speciale che non c'è sulla tastiera per evitare cancellazioni fraudolente char marca = '\u0251'; RigaCarrello r = carrello.righeCarrello.SingleOrDefault(rr => rr.id == idRigaCarrello); // Devo individuare qual'è la riga da modificare if (r.id != null) { short qtaPrec = r.quantita; decimal totRigaPrec = r.prezzoNettoTotale; // azzero il valore della riga r.quantita = 0; r.prezzoNettoTotale = 0; // decremento il totale a pagare del carrello (evito per qualsiasi ragione di scendere negativo) carrello.totaleAPagare -= totRigaPrec; if (carrello.totaleAPagare < 0) { carrello.totaleAPagare = 0; } if (r.isTipoStampa) { r.descrizione = marca + " Storno " + r.totFogliStampati + " fogli"; r.totFogliStampati = 0; Fotografia f = r.fotografia; f.contaStampata = (short)Math.Max(0, f.contaStampata - qtaPrec); } if (r.isTipoMasterizzata) { r.descrizione = marca + "Storno foto masterizzate"; r.quantita = 0; } completaAttributiMancanti(false); } dbContext.SaveChanges(); } }