Example #1
0
 public virtual void Delete(int id)
 {
     using (DbSession dbSession = GetDbSession())
     {
         dbSession.Delete <T>(SqlCriteria.New.Equal(OrmUtil.GetIdentityColumnName <T>(), id));
     }
 }
Example #2
0
        private static IList <T> MergeList <T>(IList <DataSet> dataSets, SqlTable sqlTable)
        {
            if (dataSets == null || dataSets.Count == 0)
            {
                return(null);
            }
            if (sqlTable == null || sqlTable.ColumnList == null || sqlTable.ColumnList.Count == 0)
            {
                return(null);
            }

            var result = new List <T>();

            foreach (var dataSet in dataSets)
            {
                if (dataSet != null && dataSet.Tables.Count > 0)
                {
                    var dataTable = dataSet.Tables[0];
                    var list      = new List <T>();
                    OrmUtil.FillDataTableByName(dataTable, sqlTable.ColumnList, typeof(T), list);
                    result.AddRange(list);
                }
            }

            return(result);
        }
Example #3
0
        public ControllerBase()
        {
            if (OrmUtil.CheckCacheFlag <T>())
            {
                DbSession.RegisterCacheTable(TableName, true);
            }

            EntityProxy <T> entityProxy = EntityProxyManager.Instance.GetEntityProxy <T>();

            foreach (PropertySchema item in entityProxy.GetPropertyList())
            {
                if (item.PropertyType.IsEnum)
                {
                    Dictionary <string, string> dict = new Dictionary <string, string>();

                    foreach (object enumItem in Enum.GetValues(item.PropertyType))
                    {
                        long l = Convert.ToInt64(enumItem);
                        dict.Add(l.ToString(), enumItem.ToString());
                    }

                    DataMapping.Instance.Add(item.PropertyType.ToString(), dict);
                }
            }
        }
Example #4
0
        public void removeRiga(RigaCarrello rigaDacanc)
        {
            EntityState stato = OrmUtil.getEntityState(rigaDacanc, mioDbContext);

            // Rimuovo l'elemento dalla collezione.
            // Non so perché, ma essendo una relazione identificante, perché EF NON si preoccua di rimuovere anche da disco la riga da solo ??
            // Dovrebbe chiamare la delete sul db, ma non lo fa! ...
            bool test = carrello.righeCarrello.Remove(rigaDacanc);

            if (!test)
            {
                _giornale.Error("Si è cercato di cancellare una riga dal carrello che non esiste. Probabilmente la riga era già stata eliminata dal carrello in precedenza");
                throw new LumenException("La riga non è presente nel carrello");
            }

            // ... per quanto sopra, se l'oggetto era persistente, devo preoccuparmi io di rimuoverlo anche dal dbcontext
            if (isStatoModifica == true && rigaDacanc.id != Guid.Empty)
            {
                if (stato == EntityState.Detached || stato == EntityState.Modified || stato == EntityState.Unchanged)
                {
                    mioDbContext.RigheCarrelli.Remove(rigaDacanc);
                }
            }

            isCarrelloModificato = true;
        }
Example #5
0
        /// <summary>
        /// Uso tutti try-catch perché è importante che io arrivi a fare la dispose del DbContext,
        /// altrimenti mi rimangono le entità tracciate.
        /// </summary>
        public void Dispose()
        {
            // Se ho delle fotografie caricate, rilascio le immagini
            if (carrello != null && carrello.righeCarrello != null)
            {
                foreach (RigaCarrello riga in carrello.righeCarrello)
                {
                    try {
                        AiutanteFoto.disposeImmagini(riga.fotografia);
                    } catch (Exception) {
                    }
                }
            }

            // Se il carrello è stato modificato nel db o aggiunto al db ma non ancora committato, allora devo "tornare indietro"
            if (carrello != null && isCarrelloTransient == false)
            {
                try {
                    OrmUtil.rinuncioAlleModifiche(carrello, mioDbContext);
                } catch (Exception) {
                }

                carrello = null;
            }

            isCarrelloModificato = false;

            // Distruggo anche il contesto. In questo modo riparto pulito per il prossimo carrello, ma sopattutto devo rilasciare le entità che sono "tracciate" da questo context
            this.mioDbContext.Dispose();
            this.mioDbContext = null;
        }
Example #6
0
        /*
         *              public ObjectResult<TEntity> execute() {
         *                      ObjectSet<TEntity> objectSet = UnitOfWorkScope.CurrentObjectContext.ObjectContext.CreateObjectSet<TEntity>();
         *                      return objectSet.Execute( MergeOption.AppendOnly );
         *              }
         */

        public void refresh(TEntity entita)
        {
            // Se era staccato l'oggetto, allora lo riattacco.
            OrmUtil.forseAttacca <TEntity>(ref entita);

            // Poi lo rinfesco dal db
            UnitOfWorkScope.currentObjectContext.Refresh(RefreshMode.StoreWins, entita);
        }
Example #7
0
        public virtual void update(ref TEntity entita, bool forzaDaModificare)
        {
            // Riattacco l'entità
            OrmUtil.forseAttacca <TEntity>(ref entita);

            // Flaggo l'oggetto come modificato. In questo modo mi assicuro che quando chiamero il SaveChanges, questo verrà aggiornato
            if (forzaDaModificare)
            {
                UnitOfWorkScope.currentObjectContext.ObjectStateManager.ChangeObjectState(entita, EntityState.Modified);
            }
        }
        /// <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);
        }
Example #9
0
        public virtual PageResult Show(int id)
        {
            BeeDataAdapter dataAdapter = new BeeDataAdapter();

            if (id >= 0)
            {
                using (DbSession dbSession = GetDbSession())
                {
                    T result =
                        dbSession.Query <T>(SqlCriteria.New.Equal(OrmUtil.GetIdentityColumnName <T>(), id)).FirstOrDefault();
                    dataAdapter = BeeDataAdapter.From <T>(result);
                }
            }

            ViewData.Merge(dataAdapter, true);

            return(View("BeeAutoShow"));
        }
Example #10
0
        internal void elimina(Carrello carrelloDacanc)
        {
            if (!carrelloDacanc.Equals(this.carrello))
            {
                OrmUtil.forseAttacca <Carrello>(ref carrelloDacanc, mioDbContext);
            }

            if (carrelloDacanc.venduto)
            {
                throw new InvalidOperationException("Carrello venduto. Impossibile cancellare");
            }

            mioDbContext.Carrelli.Remove(carrelloDacanc);

            mioDbContext.SaveChanges();

            isCarrelloModificato = false;
        }
Example #11
0
        private static IList <T> MergeListOfSingleField <T>(IList <IDataReader> dataReaders, Boolean isSameShard)
        {
            if (dataReaders == null || dataReaders.Count == 0)
            {
                return(null);
            }

            var result = new List <T>();
            var funcs  = new List <Func <IList <T> > >();

            for (Int32 i = 0; i < dataReaders.Count; i++)
            {
                var dataReader = dataReaders[i];
                funcs.Add(() =>
                {
                    try
                    {
                        LogManager.Logger.StartTracing();
                        var list = new List <T>();
                        using (dataReader)
                        {
                            OrmUtil.FillBySingleFied(dataReader, list);
                        }
                        return(list);
                    }
                    finally
                    {
                        LogManager.Logger.StopTracing();
                    }
                });
            }

            var temp = ExecuteParallelHelper.ParallelExcuter(funcs, isSameShard);

            if (temp.Count > 0)
            {
                foreach (var item in temp)
                {
                    result.AddRange(item);
                }
            }

            return(result);
        }
Example #12
0
        public Fotografia get(Guid id)
        {
            Fotografia foto = null;

            // Prima guardo se ce l'ho in pancia io
            foto = fotografie.FirstOrDefault(ff => ff.id == id);

            if (foto == null)
            {
                foto = UnitOfWorkScope.currentDbContext.Fotografie.SingleOrDefault(f => f.id == id);

                // Stacco l'oggetto altrimenti sarebbe a carico del chiamante.
                if (foto != null)
                {
                    OrmUtil.forseStacca <Fotografia>(ref foto);
                }
            }

            return(foto);
        }
Example #13
0
        private static IList <T> MergeFirst <T>(IList <IDataReader> dataReaders, SqlTable sqlTable, Boolean isSameShard)
        {
            if (dataReaders == null || dataReaders.Count == 0)
            {
                return(null);
            }

            if (sqlTable == null || sqlTable.ColumnList == null || sqlTable.ColumnList.Count == 0)
            {
                return(null);
            }

            var funcs = new List <Func <T> >();

            for (Int32 i = 0; i < dataReaders.Count; i++)
            {
                var dataReader = dataReaders[i];
                funcs.Add(() =>
                {
                    try
                    {
                        LogManager.Logger.StartTracing();
                        T item = default(T);
                        using (dataReader)
                        {
                            OrmUtil.FillFirstByName(dataReader, sqlTable.ColumnList, ref item);
                        }
                        return(item);
                    }
                    finally
                    {
                        LogManager.Logger.StopTracing();
                    }
                });
            }

            var result = ExecuteParallelHelper.ParallelExcuter(funcs, isSameShard);

            return(result);
        }
Example #14
0
        protected override void InitPagePara(BeeDataAdapter dataAdapter)
        {
            EntityProxy <T> entityProxy           = EntityProxyManager.Instance.GetEntityProxy <T>();
            ModelAttribute  modelAttribute        = entityProxy.GetCustomerAttribute <ModelAttribute>();
            string          identityColumnName    = OrmUtil.GetIdentityColumnName <T>();
            int             defaultPageSize       = 20;
            string          defaultOrderField     = identityColumnName;
            string          defaultOrderDirection = "desc";

            if (modelAttribute != null)
            {
                defaultPageSize       = modelAttribute.PageSize;
                defaultOrderField     = modelAttribute.DefaultOrderField;
                defaultOrderDirection = modelAttribute.DefaultOrderAscFlag ? "asc" : "desc";
            }

            ViewData.TryGetValue <int>("pagenum", 1, true);
            ViewData.TryGetValue <int>("pagesize", defaultPageSize, true);
            ViewData.TryGetValue <int>("recordcount", 0, true);
            ViewData.TryGetValue <string>("orderField", defaultOrderField, true);
            ViewData.TryGetValue <string>("orderDirection", defaultOrderDirection, true);
        }
Example #15
0
        protected virtual string GetQuerySelectClause(Type modelType)
        {
            IEntityProxy entityProxy = EntityProxyManager.Instance.GetEntityProxyFromType(modelType);

            string      tableName   = OrmUtil.GetTableName(modelType);
            TableSchema tableSchema = DbSession.Current.GetTableSchema(tableName);

            StringBuilder selectClause = new StringBuilder();

            foreach (PropertySchema propertySchema in entityProxy.GetPropertyList())
            {
                string columnName = propertySchema.Name;
                ModelPropertyAttribute modelPropertyAttribute
                    = propertySchema.GetCustomerAttribute <ModelPropertyAttribute>();
                if (modelPropertyAttribute != null)
                {
                    if (!modelPropertyAttribute.Visible)
                    {
                        continue;
                    }
                }

                OrmColumnAttribute ormColumnAttribute = propertySchema.GetCustomerAttribute <OrmColumnAttribute>();
                if (ormColumnAttribute != null && !string.IsNullOrEmpty(ormColumnAttribute.DbColumnName))
                {
                    columnName = ormColumnAttribute.DbColumnName;
                }

                if (tableSchema != null && !tableSchema.ContainsColumn(columnName))
                {
                    continue;
                }

                selectClause.AppendFormat("{0},", columnName);
            }
            selectClause.Remove(selectClause.Length - 1, 1);

            return(selectClause.ToString());
        }
        private void eliminareFormatoCarta()
        {
            FormatoCarta dacanc = formatoCartaSelezionato;

            try {
                try {
                    OrmUtil.forseAttacca(ref dacanc);
                } catch (Exception) {
                }

                var test = UnitOfWorkScope.currentDbContext.FormatiCarta.Remove(dacanc);

                var test2 = UnitOfWorkScope.currentDbContext.SaveChanges();

                // Se tutto è andato bene, allora rimuovo l'elemento dalla collezione visuale.
                formatoCartaSelezionato = null;
                formatiCarta.Remove(dacanc);
            } catch (Exception ee) {
                UnitOfWorkScope.currentObjectContext.ObjectStateManager.ChangeObjectState(dacanc, System.Data.Entity.EntityState.Unchanged);
                throw ee;
            }
        }
Example #17
0
        private void rinomina()
        {
            InputBoxDialog d = new InputBoxDialog();

            d.Title = "Inserire il nome dell'azione";
            bool?esito = d.ShowDialog();

            if (esito != true)
            {
                return;
            }

            AzioneAuto azione = azioneAutomaticaSelezionata;

            OrmUtil.forseAttacca <AzioneAuto>(ref azione);
            azione.nome = d.inputValue.Text;
            OrmUtil.cambiaStatoModificato(azione);

            azioneAutomaticaSelezionata = azione;

            rileggereAzioniAutomatiche();

            dialogProvider.ShowMessage("Modifica Effettuata con successo", "Avviso");
        }
Example #18
0
        /*
         *
         * private List<BeeDataAdapter> GetSearchInfo(BeeDataAdapter dataAdapter)
         * {
         *  List<BeeDataAdapter> result = new List<BeeDataAdapter>();
         *
         *  EntityProxy<T> entityProxy = EntityProxyManager.Instance.GetEntityProxy<T>();
         *  foreach (PropertySchema propertySchema in entityProxy.GetPropertyList())
         *  {
         *      ModelPropertyAttribute modelPropertyAttribute
         *          = propertySchema.GetCustomerAttribute<ModelPropertyAttribute>();
         *      if (modelPropertyAttribute != null)
         *      {
         *          if (!modelPropertyAttribute.Visible)
         *          {
         *              continue;
         *          }
         *
         *          if (!modelPropertyAttribute.Queryable)
         *          {
         *              continue;
         *          }
         *
         *          BeeDataAdapter dataItem = new BeeDataAdapter();
         *
         *          string descriptionInfo = modelPropertyAttribute.Description;
         *          if (string.IsNullOrEmpty(descriptionInfo))
         *          {
         *              descriptionInfo = propertySchema.Name;
         *          }
         *
         *          dataItem.Add("name", propertySchema.Name);
         *          dataItem.Add("Type", propertySchema.PropertyType);
         *          dataItem.Add("QueryType", modelPropertyAttribute.QueryType);
         *          dataItem.Add("Description", descriptionInfo);
         *          dataItem.Add("MappingName", modelPropertyAttribute.MappingName);
         *
         *          result.Add(dataItem);
         *      }
         *  }
         *
         *  return result;
         * }
         *
         * private List<BeeDataAdapter> GetHeaderInfo()
         * {
         *  List<BeeDataAdapter> result = new List<BeeDataAdapter>();
         *  EntityProxy<T> entityProxy = EntityProxyManager.Instance.GetEntityProxy<T>();
         *
         *  ModelAttribute modelAttribute = entityProxy.GetCustomerAttribute<ModelAttribute>();
         *
         *  foreach (PropertySchema propertySchema in entityProxy.GetPropertyList())
         *  {
         *      ModelPropertyAttribute modelPropertyAttribute
         *          = propertySchema.GetCustomerAttribute<ModelPropertyAttribute>();
         *
         *      BeeDataAdapter dataAdapter = new BeeDataAdapter();
         *      string descriptionInfo;
         *      if (modelPropertyAttribute != null)
         *      {
         *          if (!modelPropertyAttribute.Visible)
         *          {
         *              continue;
         *          }
         *
         *          descriptionInfo = modelPropertyAttribute.Description;
         *          if (string.IsNullOrEmpty(descriptionInfo))
         *          {
         *              descriptionInfo = propertySchema.Name;
         *          }
         *
         *          dataAdapter.Add("description", descriptionInfo);
         *          dataAdapter.Add("name", propertySchema.Name);
         *
         *          if (modelPropertyAttribute.ColumnWidth != 0)
         *          {
         *              dataAdapter.Add("width", modelPropertyAttribute.ColumnWidth.ToString());
         *          }
         *
         *          if (!string.IsNullOrEmpty(modelPropertyAttribute.Align))
         *          {
         *              dataAdapter.Add("align", modelPropertyAttribute.Align);
         *          }
         *
         *          if (modelPropertyAttribute.OrderableFlag)
         *          {
         *              dataAdapter.Add("orderField", propertySchema.Name);
         *          }
         *
         *      }
         *      else
         *      {
         *          dataAdapter.Add("description", propertySchema.Name);
         *          dataAdapter.Add("Name", propertySchema.Name);
         *      }
         *
         *      result.Add(dataAdapter);
         *  }
         *
         *
         *  return result;
         * }
         *
         * private List<BeeDataAdapter> GetDetailInfo()
         * {
         *  List<BeeDataAdapter> result = new List<BeeDataAdapter>();
         *
         *  EntityProxy<T> entityProxy = EntityProxyManager.Instance.GetEntityProxy<T>();
         *
         *  ModelAttribute modelAttribute = entityProxy.GetCustomerAttribute<ModelAttribute>();
         *  string identityColumn = OrmUtil.GetIdentityColumnName<T>();
         *
         *  foreach (PropertySchema propertySchema in entityProxy.GetPropertyList())
         *  {
         *      ModelPropertyAttribute modelPropertyAttribute
         *          = propertySchema.GetCustomerAttribute<ModelPropertyAttribute>();
         *      BeeDataAdapter dataAdapter = new BeeDataAdapter();
         *      string descriptionInfo;
         *      if (modelPropertyAttribute != null)
         *      {
         *          descriptionInfo = modelPropertyAttribute.Description;
         *          if (string.IsNullOrEmpty(descriptionInfo))
         *          {
         *              descriptionInfo = propertySchema.Name;
         *          }
         *      }
         *      else
         *      {
         *          descriptionInfo = propertySchema.Name;
         *      }
         *
         *      dataAdapter.Add("description", descriptionInfo);
         *      dataAdapter.Add("name", propertySchema.Name);
         *      bool readOnly = false;
         *
         *      if (string.Compare(identityColumn, propertySchema.Name, true) == 0)
         *      {
         *          readOnly = true;
         *      }
         *
         *      dataAdapter.Add("readonly", readOnly);
         *      dataAdapter.Add("mappingname", modelPropertyAttribute.MappingName);
         *
         *      result.Add(dataAdapter);
         *  }
         *
         *  return result;
         * }
         *
         */


        private BeeAutoModelInfo InitBeeAutoModelInfo()
        {
            BeeAutoModelInfo result = new BeeAutoModelInfo();

            List <BeeDataAdapter>       headerInfo      = new List <BeeDataAdapter>();
            List <BeeDataAdapter>       searchInfo      = new List <BeeDataAdapter>();
            List <BeeDataAdapter>       detailInfo      = new List <BeeDataAdapter>();
            Dictionary <string, string> dataMappingInfo = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

            EntityProxy <T> entityProxy = EntityProxyManager.Instance.GetEntityProxy <T>();

            ModelAttribute modelAttribute = entityProxy.GetCustomerAttribute <ModelAttribute>();

            string identityColumn = OrmUtil.GetIdentityColumnName <T>();

            TableSchema tableSchema = null;

            using (DbSession dbSession = GetDbSession())
            {
                tableSchema = dbSession.GetTableSchema(OrmUtil.GetTableName <T>());
            }

            foreach (PropertySchema propertySchema in entityProxy.GetPropertyList())
            {
                string             columnName         = propertySchema.Name;
                OrmColumnAttribute ormColumnAttribute = propertySchema.GetCustomerAttribute <OrmColumnAttribute>();
                if (ormColumnAttribute != null && !string.IsNullOrEmpty(ormColumnAttribute.DbColumnName))
                {
                    columnName = ormColumnAttribute.DbColumnName;
                }

                if (tableSchema != null && !tableSchema.ContainsColumn(columnName))
                {
                    continue;
                }

                BeeDataAdapter headerItem = GetHeaderItem(propertySchema);
                if (headerItem != null)
                {
                    headerInfo.Add(headerItem);
                }

                BeeDataAdapter searchItem = GetSearchItem(propertySchema);
                if (searchItem != null)
                {
                    searchInfo.Add(searchItem);
                }

                BeeDataAdapter detailItem = GetDetailItem(propertySchema, identityColumn);
                if (detailItem != null)
                {
                    detailInfo.Add(detailItem);
                }

                ModelPropertyAttribute modelPropertyAttribute
                    = propertySchema.GetCustomerAttribute <ModelPropertyAttribute>();
                if (modelPropertyAttribute != null && !string.IsNullOrEmpty(modelPropertyAttribute.MappingName))
                {
                    dataMappingInfo.Add(propertySchema.Name, modelPropertyAttribute.MappingName);
                }

                if (propertySchema.PropertyType.IsEnum && !dataMappingInfo.ContainsKey("mappingname"))
                {
                    dataMappingInfo.Add(propertySchema.Name, propertySchema.PropertyType.ToString());
                }
            }

            result.DetailInfo      = detailInfo;
            result.HeaderInfo      = headerInfo;
            result.SearchInfo      = searchInfo;
            result.DataMappingInfo = dataMappingInfo;

            return(result);
        }
Example #19
0
        public void clonaImmagineIncorniciata(Fotografia fotoOrig, string nomeFileImg)
        {
            FileInfo fileInfoSrc   = new FileInfo(fotoOrig.nomeFile);
            string   nomeOrig      = fileInfoSrc.Name;
            string   nomeFotoClone = ClonaImmaginiWorker.getNomeFileClone(fotoOrig);
            string   nomeFileDest  = Path.Combine(Config.Configurazione.cartellaRepositoryFoto, Path.GetDirectoryName(fotoOrig.nomeFile), nomeFotoClone);

            //Sposto la foto nella coartellaRepository e gli attribuisco il suo nome originale.
            File.Move(nomeFileImg, nomeFileDest);

            Fotografia fotoMsk = null;

            using (new UnitOfWorkScope(false))
            {
                try
                {
                    fotoMsk    = new Fotografia();
                    fotoMsk.id = Guid.NewGuid();
                    fotoMsk.dataOraAcquisizione = fotoOrig.dataOraAcquisizione;

                    Fotografo f = fotoOrig.fotografo;
                    OrmUtil.forseAttacca <Fotografo>(ref f);
                    fotoMsk.fotografo = f;

                    if (fotoOrig.evento != null)
                    {
                        Evento e = fotoOrig.evento;
                        OrmUtil.forseAttacca <Evento>(ref e);
                        fotoMsk.evento = e;
                    }

                    fotoMsk.didascalia = fotoOrig.didascalia;
                    fotoMsk.numero     = fotoOrig.numero;
                    // Le correzioni non devo duplicarle perché non sono tipiche della composizione finale, ma della foto originale.

                    fotoMsk.faseDelGiorno = fotoOrig.faseDelGiorno;
                    fotoMsk.giornata      = fotoOrig.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.
                    fotoMsk.nomeFile = Path.Combine(Path.GetDirectoryName(fotoOrig.nomeFile), nomeFotoClone);

                    fotografieRepositorySrv.addNew(fotoMsk);
                    fotografieRepositorySrv.saveChanges();
                }

                catch (Exception ee)
                {
                    _giornale.Error("Non riesco ad inserire una foto clonata. Nel db non c'è ma nel filesystem si: " + fotoOrig.nomeFile, ee);
                }

                AiutanteFoto.creaProvinoFoto(nomeFileDest, fotoMsk);

                // Libero la memoria occupata dalle immagini, altrimenti esplode.
                AiutanteFoto.disposeImmagini(fotoMsk, IdrataTarget.Tutte);

                // Notifico la lista delle foto da mandare in modifica
                NuovaFotoMsg msg = new NuovaFotoMsg(this, fotoMsk);
//				msg.descrizione += Configurazione.ID_FOTOGRAFO_ARTISTA;
                LumenApplication.Instance.bus.Publish(msg);
            }
        }
Example #20
0
        public bool  modificaMetadatiFotografie(IEnumerable <Fotografia> fotografie, MetadatiFoto metadati)
        {
            bool esito = false;

            try
            {
                // riattacco l'entità che non si sa mai
                if (metadati.evento != null)
                {
                    try {
                        Evento e = metadati.evento;
                        OrmUtil.forseAttacca <Evento>(ref e);
                    } catch (Exception ee) {
                        _giornale.Debug("Potenziale errore", ee);
                    }
                }

                foreach (Fotografia f in fotografie)
                {
                    Fotografia fotografia = f;
                    try {
                        OrmUtil.forseAttacca(ref fotografia);
                    } catch (Exception ee) {
                        _giornale.Debug("Potenziale errore", ee);
                        fotografia = UnitOfWorkScope.currentDbContext.Fotografie.Single(f2 => f2.id == f.id);
                    }

#if DEBUG
                    String didascaliaNew = null;
                    if (metadati.usoDidascalia)
                    {
                        if (!String.IsNullOrWhiteSpace(metadati.didascalia))
                        {
                            didascaliaNew = metadati.didascalia.TrimEnd().ToUpper();
                        }
                    }

                    string strDidascaliaOld    = fotografia.didascalia;
                    string strFaseDelGiornoOld = fotografia.faseDelGiorno == null ? "empty" : FaseDelGiornoUtil.valoreToString(fotografia.faseDelGiorno);
                    string strEventoOld        = fotografia.evento == null ? "empty" : fotografia.evento.descrizione;

                    string strFaseDelGiornoNew = metadati.faseDelGiorno == null ? "empty" : metadati.faseDelGiorno.ToString();
                    string strEventoNew        = metadati.evento == null ? "empty" : metadati.evento.descrizione;

                    String msg = String.Format("Modificati metadati: {0} da: dida:{1} faseGG:{2} evento:{3} in dida:{4} faseGG:{5} evento:{6}",
                                               fotografia.ToString(),
                                               strDidascaliaOld,
                                               strFaseDelGiornoOld,
                                               strEventoOld,
                                               didascaliaNew,
                                               strFaseDelGiornoNew,
                                               strEventoNew
                                               );
#endif

                    modificaMetadatiFotografie(fotografia, metadati);

#if DEBUG
                    _giornale.Debug(msg);
#endif
                }

                UnitOfWorkScope.currentDbContext.SaveChanges();
                _giornale.Debug("Modifica metadati salvataggio eseguito. Ora committo la transazione");

                _giornale.Info("Commit metadati andato a buon fine");

                esito = true;
            } catch (Exception eee) {
                _giornale.Error("Modifica metadati", eee);
                esito = false;
                _giornale.Error("Impossibile modificare metadati", eee);
            }

            return(esito);
        }
Example #21
0
        public Carrello Applica(Carrello cin, Promozione promo, PromoContext contestoDiVendita)
        {
            PromoProdXProd _promoProdXProd = (PromoProdXProd)promo;

            try {
                OrmUtil.forseAttacca <PromoProdXProd>(ref _promoProdXProd);
            } catch (Exception) {
            }

            // NOTA: non controllo più il flag di applicazione stampe/file che c'è sul database.
            //       tanto è il prodotto di innesco che mi guida.

            var qta = cin.righeCarrello
                      .Where(r => r.prezzoLordoUnitario > 0 && r.prodotto.Equals(_promoProdXProd.prodottoInnesco))
                      .Sum(r2 => r2.quantita);

            // Non entro in promozione: esco subito
            if (qta < _promoProdXProd.qtaInnesco)
            {
                return(cin);
            }

            // Ok la quantità è sufficiente per cascare nella promo.
            // Ora agisco sul carrello

            // Ora determino quante foto di quella misura posso elargire.
            var multiploRegali = ((int)(qta / _promoProdXProd.qtaInnesco));
            var qtaElarg       = multiploRegali * (_promoProdXProd.qtaElargito);

            _giornale.Debug("devo elargire " + qtaElarg + " omaggio");

            bool elargito = false;

            // -- Ora itero le righe del carrello con quel tipo e prendo per prima le righe a prezzo pieno.

            var righeOma1 = cin.righeCarrello
                            .Where(r => r.prodotto.Equals(_promoProdXProd.prodottoElargito) && r.sconto == null);
            var righeOma2 = cin.righeCarrello
                            .Where(r => r.prodotto.Equals(_promoProdXProd.prodottoElargito) && r.sconto != null).OrderByDescending(r => r.sconto);

            // Faccio due giri : 1) righe non ancora scontate. 2) righe scontate
            for (int ii = 1; ii < 2; ii++)
            {
                var righeOma = (ii == 1 ? righeOma1 : righeOma2);
                foreach (RigaCarrello riga in righeOma)
                {
                    if (qtaElarg >= riga.quantita)
                    {
                        riga.sconto = riga.prezzoLordoUnitario;
                        qtaElarg   -= riga.quantita;
                        elargito    = true;
                    }
                }
            }

            // Aggiungo la promo alla lista di quelle elargite
            if (elargito && contestoDiVendita.promoApplicate.Contains(promo) == false)
            {
                contestoDiVendita.promoApplicate.Add(promo);
            }

            return(cin);
        }
Example #22
0
 private void modificaDidascaliaFotografie(Fotografia ff, String findBarCode)
 {
     OrmUtil.forseAttacca <Fotografia>(ref ff);
     ff.didascalia = findBarCode;
     OrmUtil.cambiaStatoModificato(ff);
 }
Example #23
0
        public virtual PageResult List(BeeDataAdapter dataAdapter)
        {
            DbSession dbSession = GetDbSession();

            DataTable dataTable = null;

            try
            {
                InitPagePara(dataAdapter);

                #region datetime 处理
                EntityProxy <T> entityProxy = EntityProxyManager.Instance.GetEntityProxy <T>();

                //List<PropertySchema> propertyList = entityProxy.GetPropertyList();

                //propertyList = (from item in propertyList
                // where item.PropertyType == typeof(DateTime)
                // select item).ToList();

                BeeDataAdapter realDataAdapter = new BeeDataAdapter(dataAdapter);

                //foreach (PropertySchema item in propertyList)
                //{
                //    string beginkey = "{0}begin".FormatWith(item.Name);
                //    string endkey = "{0}end".FormatWith(item.Name);
                //    if (realDataAdapter.ContainsKey(item.Name))
                //    {
                //        realDataAdapter[item.Name] = ConvertUtil.CommonConvert<DateTime>(realDataAdapter[item.Name]);
                //    }
                //    if (realDataAdapter.ContainsKey(beginkey))
                //    {
                //        realDataAdapter[beginkey] = ConvertUtil.CommonConvert<DateTime>(realDataAdapter[beginkey]);
                //    }
                //    if (realDataAdapter.ContainsKey(endkey))
                //    {
                //        realDataAdapter[endkey] = ConvertUtil.CommonConvert<DateTime>(realDataAdapter[endkey]);
                //    }
                //}

                #endregion

                string tableName = OrmUtil.GetTableName <T>();

                SqlCriteria sqlCriteria = GetQueryCondition(realDataAdapter);

                int recordCount = dataAdapter.TryGetValue <int>("recordcount", 0);

                string selectClause = GetQuerySelectClause(typeof(T));

                dataTable = InnerQuery(tableName, selectClause, dataAdapter, sqlCriteria);
            }
            catch (Exception e)
            {
                Logger.Error("List object({0}) Error".FormatWith(typeof(T)), e);
            }
            finally
            {
                dbSession.Dispose();
            }

            return(View(null, "BeeAutoList", dataTable));
        }
Example #24
0
        void forseAssociareMaschere()
        {
            if (!modalitaAssociazione)
            {
                return;
            }

            // Per poter iniziare l'associazione, ocorre che la riga selezionata, contenga una mascheratura
            Mascheratura mascheratura2 = estraiMascheratura(azioneAutomaticaSelezionata);

            if (mascheratura2 == null)
            {
                dialogProvider.ShowError("L'azione selezionata non contiene Mascheratura", "Azioni non associate", null);
                return;
            }

            // Dalla prima azione, estraggo la mascheratura, perché devo controllare che sia di Orientamento opposto alla prima che ho fissato.
            CorrezioniList correzioni1   = SerializzaUtil.stringToObject <CorrezioniList>(azioneAutoAssociare1.correzioniXml);
            Mascheratura   mascheratura1 = (Mascheratura)correzioni1.ToList <Correzione>().FirstOrDefault(c => c is Mascheratura);

            var ratio1 = mascheratura1.width / mascheratura1.height;
            var ratio2 = mascheratura2.width / mascheratura2.height;

            if ((ratio1 < 1 && ratio2 < 1) || (ratio1 > 1 && ratio2 > 1))
            {
                dialogProvider.ShowError("Le maschere devono ossere di diverso orientamento.\nUna orizzontale ed una verticale!", "Azioni non associate", null);
                return;
            }

            // Ok : adesso posso procedere alla associazione

            MascheraturaOrientabile mo = new MascheraturaOrientabile();

            mo.mascheraturaH = (ratio1 < 1 ? mascheratura2 : mascheratura1);
            mo.mascheraturaV = (ratio1 < 1 ? mascheratura1 : mascheratura2);

            using (new UnitOfWorkScope()) {
                // Sostituisco la correzione nella lista, cercando di mettere quella nuova nella stessa posizione
                int pos = correzioni1.IndexOf(mascheratura1);
                correzioni1.RemoveAt(pos);
                correzioni1.Insert(pos, mo);

                // Rimuovo l'azione2 dalla collezione a video
                AzioneAuto azioneDacanc = azioneAutomaticaSelezionata;
                azioniAutomatiche.Remove(azioneDacanc);

                // Ora vado ad aggiornare l'azione1 con le correzioni nuove
                AzioneAuto azione = azioneAutoAssociare1;
                OrmUtil.forseAttacca <AzioneAuto>(ref azione);
                azioneAutoAssociare1.correzioniXml = SerializzaUtil.objectToString(correzioni1);

                // Elimino dal db la azione2
                OrmUtil.forseAttacca <AzioneAuto>(ref azioneDacanc);

                // Rimuovo l'azione dal database
                UnitOfWorkScope.currentDbContext.AzioniAutomatiche.Remove(azioneDacanc);

                UnitOfWorkScope.currentDbContext.SaveChanges();

                // Torno in modalità normale
                modalitaAssociazione = false;
            }

            // Purtroppo non si aggiornano le icone di overlay. devo ricaricare.
            App.Current.Dispatcher.BeginInvoke(new Action(() => {
                rileggereAzioniAutomaticheCommand.Execute(null);
            }
                                                          ));
        }
Example #25
0
        private void modificaMetadatiFotografie(Fotografia foto, MetadatiFoto metadati, bool forzaNullo)
        {
            // L'entità è sicuramente staccata
            //UnitOfWorkScope.CurrentObjectContext.Fotografie.Attach( foto );

            Fotografia f = foto;

            try {
                OrmUtil.forseAttacca <Fotografia>(ref f);
            } catch (Exception) {
            }

            //Consento la modifica anche di valori nulli
            //if( !String.IsNullOrWhiteSpace( metadati.didascalia ) )
            if (metadati.usoDidascalia)
            {
                if (String.IsNullOrWhiteSpace(metadati.didascalia))
                {
                    foto.didascalia = null;
                }
                else
                {
                    foto.didascalia = metadati.didascalia.Trim().ToUpper();                      // pulisco spazi e converto in maiuscolo
                }
            }
            else
            {
                if (forzaNullo)
                {
                    foto.didascalia = null;
                }
            }

            if (metadati.usoFaseDelGiorno)
            {
                if (metadati.faseDelGiorno != null)
                {
                    foto.faseDelGiorno = (short)metadati.faseDelGiorno;
                }
                else
                {
                    foto.faseDelGiorno = null;
                }
            }

            else
            {
                if (forzaNullo)
                {
                    foto.faseDelGiorno = null;
                }
            }

            if (metadati.usoEvento)
            {
                foto.evento = metadati.evento;
            }
            else
            {
                if (forzaNullo)
                {
                    foto.evento = null;
                }
            }

            OrmUtil.cambiaStatoModificato(f);
        }
Example #26
0
        /// <summary>
        /// Se una azione automatica contiene una mascheratura orientabile (quindi doppia)
        /// posso disassociarla e creare una nuova azione
        /// </summary>
        void disassociareMascheratura()
        {
            CorrezioniList correzioniList = null;
            AzioneAuto     azioneAuto     = azioneAutomaticaSelezionata;

            MascheraturaOrientabile mascheraturaOrientabile = null;

            // Controllo che l'azione corrente contenga una mascheratura orientabile
            if (azioneAuto.correzioniXml != null)
            {
                correzioniList = SerializzaUtil.stringToObject <CorrezioniList>(azioneAuto.correzioniXml);
                if (correzioniList != null && correzioniList.Count > 0)
                {
                    mascheraturaOrientabile = (MascheraturaOrientabile)correzioniList.SingleOrDefault(mo => mo is MascheraturaOrientabile);
                }
            }

            if (mascheraturaOrientabile == null)
            {
                dialogProvider.ShowError("L'azione selezionata non contiene una <MascheraturaOrientabile>.\nSolo queste si possono separare!", "Azione non separabile", null);
                return;
            }

            // ok procedo a separare le cornici
            // Sostituisco la correzione nella lista, cercando di mettere quella nuova nella stessa posizione
            Mascheratura masH = mascheraturaOrientabile.mascheraturaH;
            Mascheratura masV = mascheraturaOrientabile.mascheraturaV;

            // Elimino la mascheratura doppia ...
            correzioniList.Remove(mascheraturaOrientabile);
            // aggiungo solo la mascheratura Orizzontale
            correzioniList.Insert(0, masV);

            // Aggiorno l'entità sul db
            OrmUtil.forseAttacca <AzioneAuto>(ref azioneAuto);
            azioneAuto.correzioniXml = SerializzaUtil.objectToString(correzioniList);

            // Ora creo l'altra azione
            CorrezioniList correzioniList2 = new CorrezioniList();

            correzioniList2.Add(masH);
            AzioneAuto azioneV = new AzioneAuto {
                id            = Guid.NewGuid(),
                attivo        = true,
                nome          = "Separata",
                correzioniXml = SerializzaUtil.objectToString(correzioniList2)
            };

            UnitOfWorkScope.currentDbContext.AzioniAutomatiche.Add(azioneV);

            // Ora aggiungo anche alla collezione visiva
            azioniAutomatiche.Add(azioneV);

            deselezionareTutto();

            // Purtroppo non si aggiornano le icone di overlay. devo ricaricare.
            App.Current.Dispatcher.BeginInvoke(new Action(() => {
                rileggereAzioniAutomaticheCommand.Execute(null);
            }
                                                          ));
        }
Example #27
0
        /**
         * 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);
        }