public bool PercentageIncrement(IList <ProductPrice> prodPlist, decimal percentage, Guid user) { int count = 0; foreach (ProductPrice pP in prodPlist) { ControllerManager.ProductPriceAudit.SaveAudit(pP); pP.Price = pP.Price * (1 + (percentage / 100)); Modification(pP); Save(pP); count++; if (count > 300) { count = 0; NHibernateSession.Flush(); NHibernateSession.Clear(); } } NHibernateSession.Flush(); return(true); }
public void Synchronize(Currency currency) { currency = ControllerManager.Currency.GetById(currency.ID); Currency baseCurrency = ControllerManager.Currency.GetBaseCurrency(); this.BeginTransaction(); Synchronize(currency, baseCurrency); this.CommitChanges(); NHibernateSession.Clear(); }
protected void HasA <T>(Expression <Func <TEntity, T> > expression) where T : IHaveAnId { var compiledExpression = expression.Compile(); var entity = BuildEntity(); NHibernateSession.Flush(); var entityId = entity.Id; var childId = compiledExpression.Invoke(entity).Id; NHibernateSession.Clear(); entity = NHibernateSession.Get <TEntity>(entityId); Assert.Equal(childId, compiledExpression.Invoke(entity).Id); }
public void Synchronize() { Currency baseCurrency = ControllerManager.Currency.GetBaseCurrency(); IList <Currency> lstCurrency = ControllerManager.Currency.GetAll(); this.BeginTransaction(); foreach (Currency currency in lstCurrency) { Synchronize(currency, baseCurrency); } this.CommitChanges(); Utils.GetLogger().Info(string.Format("[[CURRENCY UPDATE]] {0} Currencies Updated", lstCurrency.Count)); NHibernateSession.Clear(); }
/// <summary> /// Gets the by ID. /// </summary> /// <param name="keyValues"></param> /// <returns></returns> public object GetByID(object keyValues, GetByIDParameters parameters) { NHibernateSession.Clear(); // it should get the object freshly from database to avoid inconsistency object id = keyValues; object entity = null; var persistentType = persistentTypeT; if (parameters.SourceType == GetSourceTypeEnum.View) { persistentType = persistentTypeV; } if (parameters.GetMode == GetModeEnum.Get) { entity = NHibernateSession.Get(persistentType, id, parameters.GetNHibernateLockMode()); } else { entity = NHibernateSession.Load(persistentType, id, parameters.GetNHibernateLockMode()); } //bool shouldLock = false; //if (shouldLock) //{ // //entity = NHibernateSession.Load(persitentType, id, LockMode.Upgrade); // entity = NHibernateSession.Get(persitentType, id, LockMode.Upgrade); //} //else //{ // //entity = NHibernateSession.Load(persitentType, id); // entity = NHibernateSession.Get(persitentType, id); //} return(entity); }
protected void HasMany <TMany>(Expression <Func <TEntity, IEnumerable <TMany> > > expression) where TMany : IHaveAnId { var compiledExpression = expression.Compile(); var entity = BuildEntity(); NHibernateSession.Flush(); var manies = compiledExpression.Invoke(entity).ToList(); Assert.NotEqual(0, manies.Count()); var entityId = entity.Id; var ids = manies.Select(many => many.Id).ToList(); NHibernateSession.Clear(); entity = NHibernateSession.Get <TEntity>(entityId); manies = compiledExpression.Invoke(entity).ToList(); Assert.Equal(ids.Count, manies.Count()); foreach (var many in manies) { Assert.True(ids.Contains(many.Id)); } }
/// <summary> /// Imports an existing PriceImport into the final tables. /// </summary> /// <param name="id">Id of the PriceImport to process</param> /// <returns>True if import was successfully, otherwise false.</returns> /// public bool Import(Guid id, Guid userId) { List <CategoryBase> lstcat = new List <CategoryBase>(); PriceImport pi = GetById(id); if (pi == null) { return(false); } #if !DEBUG if (pi.ImportStatus != ImportStatus.SendToExecute) { Utils.GetLogger().Info(string.Format("[[PRODUCT IMPORT PROCESS]] Invalid Status: {0}", pi.ImportStatus)); return(false); } pi.ImportStatus = ImportStatus.Executing; Save(pi); NHibernateSession.Flush(); #endif Utils.GetLogger().Info(string.Format("[[PRODUCT IMPORT PROCESS]] Starting ID: {0}", id)); List <Currency> currlist = ControllerManager.Currency.GetAll() as List <Currency>; Currency baseCurrency = ControllerManager.Currency.GetByDescription("€"); List <CurrencyRate> currencyRates = ControllerManager.CurrencyRate.GetLastList(); // Todo make sure to free memory NHibernateSession.Flush(); NHibernateSession.Clear(); DetachedCriteria groupPermissionCriteria = DetachedCriteria.For <CategoryBase>() .SetProjection(Projections.Property("ID")) .CreateCriteria("PriceImportLogs").Add(Expression.Eq("PriceImport", pi)); ICriterion groupSubquery = Subqueries.PropertyIn("ID", groupPermissionCriteria); ICriteria critCategories = NHibernateSession.CreateCriteria(typeof(CategoryBase)); critCategories.SetFetchMode("Products", FetchMode.Join); critCategories.Add(groupSubquery); critCategories.SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer()); List <CategoryBase> catlist = critCategories.List <CategoryBase>() as List <CategoryBase>; pi = this.GetById(id); // Save temporal priceBases changes IList <PriceBase> priceBasesAdd = new List <PriceBase>(); IList <PriceBase> priceBasesModify = new List <PriceBase>(); ICriteria critLogResults = NHibernateSession.CreateCriteria(typeof(PriceImportLog)). SetFetchMode("ParsedCategories", FetchMode.Join). SetFetchMode("ParsedPriceBase", FetchMode.Join). SetFetchMode("ParsedPriceBase.PriceImports", FetchMode.Join). SetFetchMode("ParsedProvider", FetchMode.Join). Add(Expression.Eq("PriceImport", pi)). Add(Expression.Not(Expression.Eq("Status", PriceImportLogStatus.Error))); IList <PriceImportLog> pilList = critLogResults.List <PriceImportLog>(); this.BeginTransaction(); Utils.GetLogger().Info("[[PRODUCT IMPORT PROCESS]] Starting."); try { foreach (PriceImportLog logResult in pilList) { PriceBase currentPriceBase = null; switch (logResult.Status) { case PriceImportLogStatus.Add: Product p = new Product(); p.Status = ProductStatus.Active; currentPriceBase = ControllerManager.PriceBase.Create(pi, logResult.CodGrundfos, logResult.CodProvider, logResult.Model, logResult.Description, logResult.ParsedProvider, logResult.ParsedFrequency, logResult.TP, FindInMemory(currlist, logResult.TPCurrency), logResult.GRP, FindInMemory(currlist, logResult.GRPCurrency), logResult.PL, FindInMemory(currlist, logResult.PLCurrency), logResult.ParsedCategories, p, baseCurrency, currencyRates); priceBasesAdd.Add(currentPriceBase); break; case PriceImportLogStatus.Modify: currentPriceBase = logResult.ParsedPriceBase; //ControllerManager.PriceBaseHistory.SaveAudit(currentPriceBase, HistoryStatus.ModificationImport, userId); currentPriceBase = ControllerManager.PriceBase.Modify(pi, logResult.CodGrundfos, logResult.CodProvider, logResult.Model, logResult.Description, logResult.ParsedProvider, logResult.ParsedFrequency, logResult.TP, FindInMemory(currlist, logResult.TPCurrency), logResult.GRP, FindInMemory(currlist, logResult.GRPCurrency), logResult.PL, FindInMemory(currlist, logResult.PLCurrency), logResult.ParsedCategories, currentPriceBase, baseCurrency, HistoryStatus.PriceChange, currencyRates); priceBasesModify.Add(currentPriceBase); break; } if (currentPriceBase != null) { foreach (CategoryBase cb in logResult.ParsedCategories) { catlist[catlist.IndexOf(cb)].Products.Add(currentPriceBase.Product); if (!lstcat.Exists(delegate(CategoryBase record){ if ((record.ID == cb.ID)) { return(true); } return(false); })) { lstcat.Add(cb); } } } if (logResult.FileIndex % 500 == 0) { Utils.GetLogger().Debug(string.Format("[[PRODUCT IMPORT PROCESS]] Processing line: {0}", logResult.FileIndex)); } } #if !DEBUG pi.ImportStatus = ImportStatus.Processed; pi.TimeStamp.ModifiedBy = userId; pi.TimeStamp.ModifiedOn = DateTime.Now; Save(pi); #endif // Make sure to process insert & updates in order. foreach (PriceBase pb in priceBasesAdd) { pb.Product.TimeStamp.CreatedBy = userId; pb.Product.TimeStamp.CreatedOn = DateTime.Now; NHibernateSession.Save(pb.Product); } foreach (PriceBase pb in priceBasesAdd) { pb.TimeStamp.CreatedBy = userId; pb.TimeStamp.CreatedOn = DateTime.Now; NHibernateSession.Save(pb); } foreach (PriceBase pb in priceBasesModify) { pb.TimeStamp.ModifiedBy = userId; pb.TimeStamp.ModifiedOn = DateTime.Now; NHibernateSession.Save(pb); } foreach (PriceBase pb in priceBasesModify) { pb.Product.TimeStamp.ModifiedBy = userId; pb.Product.TimeStamp.ModifiedOn = DateTime.Now; NHibernateSession.Save(pb.Product); } // Commit changes to DB CommitChanges(); IQuery q = NHibernateSession.GetNamedQuery("CategoryCountUpdate"); foreach (CategoryBase categoryBase in lstcat) { q.SetInt32("CategoryId", categoryBase.ID); q.UniqueResult(); } IList <PriceBase> pbList = ControllerManager.PriceBase.Get(pi, PriceBaseStatus.NotVerified); PriceCalculator pc = new PriceCalculator(false, userId); pc.Run(pbList); // TODO: Send email to creator looking for the userId. // TODO: This process is run out of the web server, so it should look for it. Utils.GetLogger().Info("[[PRODUCT IMPORT PROCESS]] Finished Processing"); } catch (Exception ex) { Utils.GetLogger().Error(ex); this.RollbackChanges(); pi = GetById(id); pi.ImportStatus = ImportStatus.Failed; Save(pi); CommitChanges(); throw ex; } return(true); }
/// <summary> /// Create a new PriceImport object based on the input file. /// </summary> /// <param name="filename">File with the CSV to import</param> /// <param name="description">Description for the new import process</param> /// <param name="haveHeader">Indicates if the file has header line</param> /// <param name="separationChar">Indicates the separation character in the CSV file</param> /// <param name="path">Indicates the path of the CSV file</param> /// <returns></returns> public PriceImport Create(string newfilename, string description, bool haveHeader, char separationChar, string path, string originalfilename) { Utils.GetLogger().Debug(string.Format("[[Product Import]] Start {0}", description)); DelimitedClassBuilder cb = CreateClassBuilder(separationChar, haveHeader); FileHelperEngine engine = new FileHelperEngine(cb.CreateRecordClass()); object[] items = engine.ReadFile(path + newfilename); if (items.Length <= 0) { throw new EmptyImportationFileException("No se encontraron registros para ingresar."); } Utils.GetLogger().Debug(string.Format("[[Product Import]] Starting to get database data {0}", description)); // TODO: We should only get the necessary fields for each object and not the whole object. provlist = ControllerManager.Provider.GetActives() as List <Provider>; catlist = ControllerManager.CategoryBase.GetAll() as List <CategoryBase>; currlist = ControllerManager.Currency.GetAll() as List <Currency>; // Get Needed PriceBase Data IQuery q = NHibernateSession.CreateQuery("select lower(trim(P.Code)), lower(trim(PB.ProviderCode)), PB.Provider.ID, PB.ID FROM PriceBase PB JOIN PB.Product P"); q.SetResultTransformer(new NHibernate.Transform.AliasToBeanConstructorResultTransformer(typeof(PriceBaseFound).GetConstructors()[0])); List <PriceBaseFound> lst = q.List <PriceBaseFound>() as List <PriceBaseFound>; // Clear the memory NHibernateSession.Flush(); NHibernateSession.Clear(); Utils.GetLogger().Info(string.Format("[[Product Import]] Ready {0}", description)); List <PriceImportLog> lstDuplicates = new List <PriceImportLog>(items.Length); // Start the transaction this.BeginTransaction(); // Create the PriceImport item PriceImport pi = new PriceImport(); pi.ImportStatus = ImportStatus.Invalid; pi.File = originalfilename; pi.Description = description; pi.DateImported = DateTime.Now; pi.HaveHeader = haveHeader; pi.SeparationChar = separationChar; Save(pi); bool error = false; bool atLeastOneValid = false; for (int i = 0; i < items.Length; i++) { string originalline = ""; // Create the item PriceImportLog lr = new PriceImportLog(); lr.CodGrundfos = GetValue("CodGrundfos", items[i]).ToString(); lr.CodProvider = GetValue("CodProv", items[i]).ToString(); lr.Model = GetValue("Modelo", items[i]).ToString(); lr.Description = GetValue("Descripcion", items[i]).ToString(); lr.Provider = GetValue("Proveedor", items[i]).ToString(); lr.Frequency = GetValue("Frecuencia", items[i]).ToString(); lr.TP = (decimal?)GetValue("TP", items[i]); lr.TPCurrency = GetValue("MonedaTP", items[i]).ToString(); lr.GRP = (decimal?)GetValue("GRP", items[i]); lr.GRPCurrency = GetValue("MonedaGRP", items[i]).ToString(); lr.PL = (decimal?)GetValue("PL", items[i]); lr.PLCurrency = GetValue("MonedaPL", items[i]).ToString(); lr.Cat1 = GetValue("Familia", items[i]).ToString(); lr.Cat2 = GetValue("Tipo", items[i]).ToString(); lr.Cat3 = GetValue("Linea", items[i]).ToString(); lr.OriginalLine = originalline; lr.FileIndex = i; // Check if at least the required fields are completed, otherwise ignore. if (string.IsNullOrEmpty(lr.Provider) || (string.IsNullOrEmpty(lr.CodGrundfos) && string.IsNullOrEmpty(lr.CodProvider))) { NHibernateSession.Evict(lr); error = true; continue; } // Check the whole item data CheckLogResultItem(lr); if (lr.CodGrundfos == string.Empty || lr.CodProvider == string.Empty) { if (lstDuplicates.Exists(delegate(PriceImportLog record) { if ((record.CodGrundfos != string.Empty && record.CodGrundfos == lr.CodGrundfos && record.Provider == lr.Provider) || (record.CodProvider != string.Empty && record.CodProvider == lr.CodProvider && record.Provider == lr.Provider)) { return(true); } return(false); })) { SetErrorOnItem(lr, Resource.Business.GetString("DuplicatedProduct")); } } lstDuplicates.Add(lr); if (lr.Status != PriceImportLogStatus.Error) { string codGrundFos = lr.CodGrundfos.Trim(); string codProvider = lr.CodProvider.Trim(); Provider prov = FindInMemory(provlist, lr.Provider); PriceBaseFound pb; if (!string.IsNullOrEmpty(codGrundFos)) { codGrundFos = codGrundFos.ToLower(); pb = lst.Find(delegate(PriceBaseFound record) { if (record.Code == codGrundFos && record.ProviderId == prov.ID) { return(true); } return(false); }); } else { codProvider = codProvider.ToLower(); pb = lst.Find(delegate(PriceBaseFound record) { if (record.CodeProvider == codProvider && record.ProviderId == prov.ID) { return(true); } return(false); }); } if (pb != null) { lr.Status = PriceImportLogStatus.Modify; lr.ParsedPriceBase = new PriceBase(pb.PriceBaseId); if (string.IsNullOrEmpty(GetValue("Frecuencia", items[i]).ToString())) { lr.Frequency = string.Empty; lr.ParsedFrequency = null; } if (string.IsNullOrEmpty(GetValue("MonedaTP", items[i]).ToString())) { lr.TPCurrency = string.Empty; } if (string.IsNullOrEmpty(GetValue("MonedaGRP", items[i]).ToString())) { lr.GRPCurrency = string.Empty; } if (string.IsNullOrEmpty(GetValue("MonedaPL", items[i]).ToString())) { lr.PLCurrency = string.Empty; } } } // Save the item lr.PriceImport = pi; NHibernateSession.Save(lr); if (lr.Status != PriceImportLogStatus.Error) { atLeastOneValid = true; } else { error = true; } } // Update the status of the PriceImport item if (error) { pi.ImportStatus = (atLeastOneValid) ? ImportStatus.VerifiedSomeInvalid : ImportStatus.Invalid; } else { pi.ImportStatus = ImportStatus.Verified; } // Commit Changes CommitChanges(); Utils.GetLogger().Info(string.Format("[[Product Import]] Finished with Identifier {0} and status {1}", pi.ID, pi.ImportStatus)); File.Move(@path + newfilename, @path + pi.ID + ".csv"); return(pi); }