public void BarDao() { var session = NhSessManager.OpenSession(); var dao = new DaoFactory(session).BarDao; dao.Add(new Bar { Name = "blah" }); //dao.Find(BarSpecs.named("blah")); //dao.match().SingleOrDefault(b => b.Name.Equals("blah")); dao.All().Where(b => b.Name.Equals("blah")).SingleOrDefault(); }
public void Test_Constructor_FactorySupplied_InternalFactorySet() { var factory = new Mock<IDaoFactory>().Object; var sut = new DaoFactory(factory, null, NHibernateHelper); Assert.That(sut.Factory, Is.SameAs(factory)); }
public static void update(Int64 playlistId, Airplay Airplay, Int32 Position, Int32 OldPosition) { if (Math.Abs(Position - OldPosition) < 2) { return; } IPlaylistDao pdao = new DaoFactory().getPlaylistDao(); Playlist p = pdao.GetById(playlistId, false); p.biDeassociateAt(OldPosition); p.biAssociateAt(Airplay, Position); pdao.CommitTransactionFlush(); }
public static IList<AirplayDto> select(Int64 playlistId) { Playlist p = new DaoFactory().getPlaylistDao().GetById(playlistId, false); IList<AirplayDto> data = new List<AirplayDto>(p.Airplays.Count); int listIndex = 0; foreach( Airplay airplay in p.Airplays) data.Add(new AirplayDto(airplay,listIndex++)); return data; }
public void Test_GetDao_FactorySupplied_VerifySuppliedFactoryCreateIsCalled() { var factoryMock = new Mock<IDaoFactory>(); var factory = factoryMock.Object; var sut = new DaoFactory(factory, null, NHibernateHelper); sut.GetDao<IIdentifiable>(); factoryMock.Verify(x => x.GetDao<IIdentifiable>()); }
public void Test_GetDao_AllreadyUsed_SameFactoryIsReturned() { var factoryMock = new Mock<IDaoFactory>(); var factory = factoryMock.Object; var sut = new DaoFactory(factory, null, NHibernateHelper); var firstTime=sut.GetDao<IIdentifiable>(); Assert.That(sut.GetDao<IIdentifiable>(), Is.SameAs(firstTime)); }
public DaoIqReport(DaoFactory factory) : base(factory) { }
public OpportunityWrapper UpdateDeal( int opportunityid, int contactid, IEnumerable <int> members, string title, string description, Guid responsibleid, BidType bidType, decimal bidValue, string bidCurrencyAbbr, int perPeriodValue, int stageid, int successProbability, ApiDateTime actualCloseDate, ApiDateTime expectedCloseDate, IEnumerable <ItemKeyValuePair <int, string> > customFieldList, bool isPrivate, IEnumerable <Guid> accessList) { var deal = DaoFactory.GetDealDao().GetByID(opportunityid); if (deal == null) { throw new ItemNotFoundException(); } deal.Title = title; deal.Description = description; deal.ResponsibleID = responsibleid; deal.BidType = bidType; deal.BidValue = bidValue; deal.PerPeriodValue = perPeriodValue; deal.DealMilestoneID = stageid; deal.DealMilestoneProbability = successProbability < 0 ? 0 : (successProbability > 100 ? 100 : successProbability); deal.ContactID = contactid; deal.ActualCloseDate = actualCloseDate; deal.ExpectedCloseDate = expectedCloseDate; deal.BidCurrency = !String.IsNullOrEmpty(bidCurrencyAbbr) ? bidCurrencyAbbr.ToUpper() : null; CRMSecurity.DemandCreateOrUpdate(deal); DaoFactory.GetDealDao().EditDeal(deal); deal = DaoFactory.GetDealDao().GetByID(opportunityid); var membersList = members.ToList(); if (members != null && membersList.Any()) { var contacts = DaoFactory.GetContactDao().GetContacts(membersList.ToArray()).Where(CRMSecurity.CanAccessTo).ToList(); membersList = contacts.Select(m => m.ID).ToList(); DaoFactory.GetDealDao().SetMembers(deal.ID, membersList.ToArray()); } if (CRMSecurity.IsAdmin || deal.CreateBy == SecurityContext.CurrentAccount.ID) { var accessListLocal = accessList.ToList(); if (isPrivate && accessListLocal.Count > 0) { CRMSecurity.SetAccessTo(deal, accessListLocal); } else { CRMSecurity.MakePublic(deal); } } var existingCustomFieldList = DaoFactory.GetCustomFieldDao().GetFieldsDescription(EntityType.Opportunity).Select(fd => fd.ID).ToList(); foreach (var field in customFieldList) { if (string.IsNullOrEmpty(field.Value) || !existingCustomFieldList.Contains(field.Key)) { continue; } DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Opportunity, deal.ID, field.Key, field.Value); } return(ToOpportunityWrapper(deal)); }
public abstract ICollection GetItemsByFilter(DaoFactory daofactory);
public DaoC_CasNumber(DaoFactory factory) : base(factory) { }
public DaoMeasureType(DaoFactory factory) : base(factory) { }
public DaoDocumentType(DaoFactory factory) : base(factory) { }
public DaoDocumentAddress(DaoFactory factory) : base(factory) { }
public static List <LpaUnfit> SelLpaUnfits(LpaUnfit _param) { return(DaoFactory.GetList <LpaUnfit>("Qms.SelLpaUnfit", _param)); }
public static LpaUnfit SelLpaUnfit(LpaUnfit _param) { return(DaoFactory.GetData <LpaUnfit>("Qms.SelLpaUnfit", _param)); }
public void RecalculateFolders(Action <MailOperationRecalculateMailboxProgress> callback = null) { using (var db = new DbManager(Defines.CONNECTION_STRING_NAME, Defines.RecalculateFoldersTimeout)) { var daoFactory = new DaoFactory(db); var daoFolder = daoFactory.CreateFolderDao(Tenant, User); using (var tx = db.BeginTransaction(IsolationLevel.ReadUncommitted)) { var folderTypes = Enum.GetValues(typeof(FolderType)).Cast <int>(); var daoMailInfo = daoFactory.CreateMailInfoDao(Tenant, User); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.CountUnreadMessages); } var unreadMessagesCountByFolder = daoMailInfo.GetMailCount( SimpleMessagesExp.CreateBuilder(Tenant, User) .SetUnread(true) .Build()); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.CountTotalMessages); } var totalMessagesCountByFolder = daoMailInfo.GetMailCount( SimpleMessagesExp.CreateBuilder(Tenant, User) .Build()); var daoChain = daoFactory.CreateChainDao(Tenant, User); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.CountUreadConversation); } var unreadConversationsCountByFolder = daoChain.GetChainCount( SimpleConversationsExp.CreateBuilder(Tenant, User) .SetUnread(true) .Build()); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.CountTotalConversation); } var totalConversationsCountByFolder = daoChain.GetChainCount( SimpleConversationsExp.CreateBuilder(Tenant, User) .Build()); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.UpdateFoldersCounters); } var now = DateTime.UtcNow; var folders = (from folderId in folderTypes let unreadMessCount = unreadMessagesCountByFolder.ContainsKey(folderId) ? unreadMessagesCountByFolder[folderId] : 0 let totalMessCount = totalMessagesCountByFolder.ContainsKey(folderId) ? totalMessagesCountByFolder[folderId] : 0 let unreadConvCount = unreadConversationsCountByFolder.ContainsKey(folderId) ? unreadConversationsCountByFolder[folderId] : 0 let totalConvCount = totalConversationsCountByFolder.ContainsKey(folderId) ? totalConversationsCountByFolder[folderId] : 0 select new Folder { FolderType = (FolderType)folderId, Tenant = Tenant, UserId = User, UnreadCount = unreadMessCount, UnreadChainCount = unreadConvCount, TotalCount = totalMessCount, TotalChainCount = totalConvCount, TimeModified = now }) .ToList(); foreach (var folder in folders) { daoFolder.Save(folder); } var userFolder = folders.FirstOrDefault(f => f.FolderType == FolderType.UserFolder); if (userFolder != null) { var daoUserFolder = daoFactory.CreateUserFolderDao(Tenant, User); var userFolders = daoUserFolder.GetList( SimpleUserFoldersExp.CreateBuilder(Tenant, User) .Build()); if (userFolders.Any()) { var totalMessagesCountByUserFolder = daoMailInfo.GetMailUserFolderCount(); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.CountTotalUserFolderMessages); } var unreadMessagesCountByUserFolder = daoMailInfo.GetMailUserFolderCount(true); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.CountUnreadUserFolderMessages); } var totalConversationsCountByUserFolder = daoChain.GetChainUserFolderCount(); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.CountTotalUserFolderConversation); } var unreadConversationsCountByUserFolder = daoChain.GetChainUserFolderCount(true); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.CountUreadUserFolderConversation); } var newUserFolders = (from folder in userFolders let unreadMessCount = unreadMessagesCountByUserFolder.ContainsKey(folder.Id) ? unreadMessagesCountByUserFolder[folder.Id] : 0 let totalMessCount = totalMessagesCountByUserFolder.ContainsKey(folder.Id) ? totalMessagesCountByUserFolder[folder.Id] : 0 let unreadConvCount = unreadConversationsCountByUserFolder.ContainsKey(folder.Id) ? unreadConversationsCountByUserFolder[folder.Id] : 0 let totalConvCount = totalConversationsCountByUserFolder.ContainsKey(folder.Id) ? totalConversationsCountByUserFolder[folder.Id] : 0 select new UserFolder { Id = folder.Id, ParentId = folder.ParentId, Name = folder.Name, FolderCount = folder.FolderCount, Tenant = Tenant, User = User, UnreadCount = unreadMessCount, UnreadChainCount = unreadConvCount, TotalCount = totalMessCount, TotalChainCount = totalConvCount, TimeModified = now }) .ToList(); if (callback != null) { callback(MailOperationRecalculateMailboxProgress.UpdateUserFoldersCounters); } foreach (var folder in newUserFolders) { daoUserFolder.Save(folder); } } } tx.Commit(); } } }
private void ImportCaseData(DaoFactory _daoFactory) { using (var CSVFileStream = _dataStore.GetReadStream("temp", _CSVFileURI)) using (CsvReader csv = ImportFromCSV.CreateCsvReaderInstance(CSVFileStream, _importSettings)) { int currentIndex = 0; var casesDao = _daoFactory.CasesDao; var customFieldDao = _daoFactory.CustomFieldDao; var tagDao = _daoFactory.TagDao; var findedTags = new Dictionary <int, List <String> >(); var findedCustomField = new List <CustomField>(); var findedCases = new List <ASC.CRM.Core.Entities.Cases>(); var findedCasesMembers = new Dictionary <int, List <int> >(); while (csv.ReadNextRecord()) { _columns = csv.GetCurrentRowFields(false); var objCases = new ASC.CRM.Core.Entities.Cases(); objCases.ID = currentIndex; objCases.Title = GetPropertyValue("title"); if (String.IsNullOrEmpty(objCases.Title)) { continue; } foreach (JProperty jToken in _importSettings.ColumnMapping.Children()) { var propertyValue = GetPropertyValue(jToken.Name); if (String.IsNullOrEmpty(propertyValue)) { continue; } if (!jToken.Name.StartsWith("customField_")) { continue; } var fieldID = Convert.ToInt32(jToken.Name.Split(new[] { '_' })[1]); var field = customFieldDao.GetFieldDescription(fieldID); if (field != null) { findedCustomField.Add(new CustomField { EntityID = objCases.ID, EntityType = EntityType.Case, ID = fieldID, Value = field.FieldType == CustomFieldType.CheckBox ? (propertyValue == "on" || propertyValue == "true" ? "true" : "false") : propertyValue }); } } var tag = GetPropertyValue("tag"); if (!String.IsNullOrEmpty(tag)) { var tagList = tag.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); tagList.AddRange(_importSettings.Tags); tagList = tagList.Distinct().ToList(); findedTags.Add(objCases.ID, tagList); } else if (_importSettings.Tags.Count != 0) { findedTags.Add(objCases.ID, _importSettings.Tags); } var localMembersCases = new List <int>(); var members = GetPropertyValue("member"); if (!String.IsNullOrEmpty(members)) { var membersList = members.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in membersList) { var findedMember = _daoFactory.ContactDao.GetContactsByName(item, true); if (findedMember.Count > 0) { localMembersCases.Add(findedMember[0].ID); } else { findedMember = _daoFactory.ContactDao.GetContactsByName(item, false); if (findedMember.Count > 0) { localMembersCases.Add(findedMember[0].ID); } } } } if (localMembersCases.Count > 0) { findedCasesMembers.Add(objCases.ID, localMembersCases); } objCases.ID = currentIndex; findedCases.Add(objCases); if (currentIndex + 1 > ImportFromCSV.MaxRoxCount) { break; } currentIndex++; } Percentage = 62.5; if (ImportDataCache.CheckCancelFlag(EntityType.Case)) { ImportDataCache.ResetAll(EntityType.Case); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Case, (ImportDataOperation)Clone()); var newIDs = casesDao.SaveCasesList(findedCases); findedCases.ForEach(d => d.ID = newIDs[d.ID]); findedCustomField.ForEach(item => item.EntityID = newIDs[item.EntityID]); customFieldDao.SaveList(findedCustomField); Percentage += 12.5; if (ImportDataCache.CheckCancelFlag(EntityType.Case)) { ImportDataCache.ResetAll(EntityType.Case); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Case, (ImportDataOperation)Clone()); foreach (var findedCasesMemberKey in findedCasesMembers.Keys) { _daoFactory.DealDao.SetMembers(newIDs[findedCasesMemberKey], findedCasesMembers[findedCasesMemberKey].ToArray()); } Percentage += 12.5; if (ImportDataCache.CheckCancelFlag(EntityType.Case)) { ImportDataCache.ResetAll(EntityType.Case); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Case, (ImportDataOperation)Clone()); foreach (var findedTagKey in findedTags.Keys) { tagDao.SetTagToEntity(EntityType.Case, newIDs[findedTagKey], findedTags[findedTagKey].ToArray()); } if (_importSettings.IsPrivate) { findedCases.ForEach(dealItem => CRMSecurity.SetAccessTo(dealItem, _importSettings.AccessList)); } Percentage += 12.5; if (ImportDataCache.CheckCancelFlag(EntityType.Case)) { ImportDataCache.ResetAll(EntityType.Case); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Case, (ImportDataOperation)Clone()); } Complete(); }
private IEnumerable <OpportunityWrapper> ToListOpportunityWrapper(ICollection <Deal> deals) { if (deals == null || deals.Count == 0) { return(new List <OpportunityWrapper>()); } var result = new List <OpportunityWrapper>(); var contactIDs = new List <int>(); var dealIDs = new List <int>(); var dealMilestoneIDs = new List <int>(); foreach (var deal in deals) { contactIDs.Add(deal.ContactID); dealIDs.Add(deal.ID); dealMilestoneIDs.Add(deal.DealMilestoneID); } dealMilestoneIDs = dealMilestoneIDs.Distinct().ToList(); var contacts = new Dictionary <int, ContactBaseWrapper>(); var customFields = DaoFactory.GetCustomFieldDao().GetEnityFields(EntityType.Opportunity, dealIDs.ToArray()) .GroupBy(item => item.EntityID) .ToDictionary(item => item.Key, item => item.Select(ToCustomFieldBaseWrapper)); var dealMilestones = DaoFactory.GetDealMilestoneDao().GetAll(dealMilestoneIDs.ToArray()) .ToDictionary(item => item.ID, item => new DealMilestoneBaseWrapper(item)); var dealMembers = DaoFactory.GetDealDao().GetMembers(dealIDs.ToArray()); foreach (var value in dealMembers.Values) { contactIDs.AddRange(value); } contactIDs = contactIDs.Distinct().ToList(); if (contactIDs.Count > 0) { DaoFactory.GetContactDao().GetContacts(contactIDs.ToArray()).ForEach(item => { if (item == null) { return; } contacts.Add(item.ID, ToContactBaseWrapper(item)); }); } foreach (var deal in deals) { var dealWrapper = new OpportunityWrapper(deal); if (contacts.ContainsKey(deal.ContactID)) { dealWrapper.Contact = contacts[deal.ContactID]; } dealWrapper.CustomFields = customFields.ContainsKey(deal.ID) ? customFields[deal.ID] : new List <CustomFieldBaseWrapper>(); dealWrapper.Members = dealMembers.ContainsKey(dealWrapper.ID) ? dealMembers[dealWrapper.ID].Where(contacts.ContainsKey).Select(item => contacts[item]) : new List <ContactBaseWrapper>(); if (dealMilestones.ContainsKey(deal.DealMilestoneID)) { dealWrapper.Stage = dealMilestones[deal.DealMilestoneID]; } dealWrapper.IsPrivate = CRMSecurity.IsPrivate(deal); if (dealWrapper.IsPrivate) { dealWrapper.AccessList = CRMSecurity.GetAccessSubjectTo(deal).Select(item => EmployeeWraper.Get(item.Key)).ToItemList(); } if (!string.IsNullOrEmpty(deal.BidCurrency)) { dealWrapper.BidCurrency = ToCurrencyInfoWrapper(CurrencyProvider.Get(deal.BidCurrency)); } result.Add(dealWrapper); } return(result); }
public IEnumerable <OpportunityWrapper> GetDeals(int contactid) { var deals = DaoFactory.GetDealDao().GetDealsByContactID(contactid); return(ToListOpportunityWrapper(deals)); }
private void ImportOpportunityData(DaoFactory _daoFactory) { var allUsers = ASC.Core.CoreContext.UserManager.GetUsers(EmployeeStatus.All).ToList(); using (var CSVFileStream = _dataStore.GetReadStream("temp", _CSVFileURI)) using (CsvReader csv = ImportFromCSV.CreateCsvReaderInstance(CSVFileStream, _importSettings)) { int currentIndex = 0; var customFieldDao = _daoFactory.CustomFieldDao; var contactDao = _daoFactory.ContactDao; var tagDao = _daoFactory.TagDao; var dealDao = _daoFactory.DealDao; var dealMilestoneDao = _daoFactory.DealMilestoneDao; var findedTags = new Dictionary <int, List <String> >(); var findedCustomField = new List <CustomField>(); var findedDeals = new List <Deal>(); var findedDealMembers = new Dictionary <int, List <int> >(); var dealMilestones = dealMilestoneDao.GetAll(); while (csv.ReadNextRecord()) { _columns = csv.GetCurrentRowFields(false); var obj = new Deal(); obj.ID = currentIndex; obj.Title = GetPropertyValue("title"); if (String.IsNullOrEmpty(obj.Title)) { continue; } obj.Description = GetPropertyValue("description"); var csvResponsibleValue = GetPropertyValue("responsible"); var responsible = allUsers.Where(n => n.DisplayUserName().Equals(csvResponsibleValue)).FirstOrDefault(); if (responsible != null) { obj.ResponsibleID = responsible.ID; } else { obj.ResponsibleID = Constants.LostUser.ID; } DateTime actualCloseDate; DateTime expectedCloseDate; if (DateTime.TryParse(GetPropertyValue("actual_close_date"), out actualCloseDate)) { obj.ActualCloseDate = actualCloseDate; } if (DateTime.TryParse(GetPropertyValue("expected_close_date"), out expectedCloseDate)) { obj.ExpectedCloseDate = expectedCloseDate; } var currency = CurrencyProvider.Get(GetPropertyValue("bid_currency")); if (currency != null) { obj.BidCurrency = currency.Abbreviation; } else { obj.BidCurrency = Global.TenantSettings.DefaultCurrency.Abbreviation; } decimal bidValue; var bidValueStr = GetPropertyValue("bid_amount"); if (Decimal.TryParse(bidValueStr, out bidValue)) { obj.BidValue = bidValue; } else { obj.BidValue = 0; } var bidTypeStr = GetPropertyValue("bid_type"); BidType bidType = BidType.FixedBid; if (!String.IsNullOrEmpty(bidTypeStr)) { if (String.Compare(CRMDealResource.BidType_FixedBid, bidTypeStr, true) == 0) { bidType = BidType.FixedBid; } else if (String.Compare(CRMDealResource.BidType_PerDay, bidTypeStr, true) == 0) { bidType = BidType.PerDay; } else if (String.Compare(CRMDealResource.BidType_PerHour, bidTypeStr, true) == 0) { bidType = BidType.PerHour; } else if (String.Compare(CRMDealResource.BidType_PerMonth, bidTypeStr, true) == 0) { bidType = BidType.PerMonth; } else if (String.Compare(CRMDealResource.BidType_PerWeek, bidTypeStr, true) == 0) { bidType = BidType.PerWeek; } else if (String.Compare(CRMDealResource.BidType_PerYear, bidTypeStr, true) == 0) { bidType = BidType.PerYear; } } obj.BidType = bidType; if (obj.BidType != BidType.FixedBid) { int perPeriodValue; if (int.TryParse(GetPropertyValue("per_period_value"), out perPeriodValue)) { obj.PerPeriodValue = perPeriodValue; } } int probabilityOfWinning; if (int.TryParse(GetPropertyValue("probability_of_winning"), out probabilityOfWinning)) { obj.DealMilestoneProbability = probabilityOfWinning; } var dealMilestoneTitle = GetPropertyValue("deal_milestone"); var tag = GetPropertyValue("tag"); if (!String.IsNullOrEmpty(tag)) { var tagList = tag.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); tagList.AddRange(_importSettings.Tags); tagList = tagList.Distinct().ToList(); findedTags.Add(obj.ID, tagList); } else if (_importSettings.Tags.Count != 0) { findedTags.Add(obj.ID, _importSettings.Tags); } if (String.IsNullOrEmpty(dealMilestoneTitle)) { obj.DealMilestoneID = dealMilestones[0].ID; } else { var dealMilestone = dealMilestones.Find(item => String.Compare(item.Title, dealMilestoneTitle, true) == 0); if (dealMilestone == null) { obj.DealMilestoneID = dealMilestones[0].ID; } else { obj.DealMilestoneID = dealMilestone.ID; } } var contactName = GetPropertyValue("client"); var localMembersDeal = new List <int>(); if (!String.IsNullOrEmpty(contactName)) { var contacts = contactDao.GetContactsByName(contactName, true); if (contacts.Count > 0) { obj.ContactID = contacts[0].ID; localMembersDeal.Add(obj.ContactID); } else { contacts = contactDao.GetContactsByName(contactName, false); if (contacts.Count > 0) { obj.ContactID = contacts[0].ID; localMembersDeal.Add(obj.ContactID); } } } var members = GetPropertyValue("member"); if (!String.IsNullOrEmpty(members)) { var membersList = members.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in membersList) { var findedMember = contactDao.GetContactsByName(item, true); if (findedMember.Count > 0) { localMembersDeal.Add(findedMember[0].ID); } else { findedMember = _daoFactory.ContactDao.GetContactsByName(item, false); if (findedMember.Count > 0) { localMembersDeal.Add(findedMember[0].ID); } } } } if (localMembersDeal.Count > 0) { findedDealMembers.Add(obj.ID, localMembersDeal); } foreach (JProperty jToken in _importSettings.ColumnMapping.Children()) { var propertyValue = GetPropertyValue(jToken.Name); if (String.IsNullOrEmpty(propertyValue)) { continue; } if (!jToken.Name.StartsWith("customField_")) { continue; } var fieldID = Convert.ToInt32(jToken.Name.Split(new[] { '_' })[1]); var field = customFieldDao.GetFieldDescription(fieldID); if (field != null) { findedCustomField.Add(new CustomField { EntityID = obj.ID, EntityType = EntityType.Opportunity, ID = fieldID, Value = field.FieldType == CustomFieldType.CheckBox ? (propertyValue == "on" || propertyValue == "true" ? "true" : "false") : propertyValue }); } } Percentage += 1.0 * 100 / (ImportFromCSV.MaxRoxCount * 2); if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity)) { ImportDataCache.ResetAll(EntityType.Opportunity); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone()); findedDeals.Add(obj); if (currentIndex + 1 > ImportFromCSV.MaxRoxCount) { break; } currentIndex++; } Percentage = 50; if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity)) { ImportDataCache.ResetAll(EntityType.Opportunity); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone()); var newDealIDs = dealDao.SaveDealList(findedDeals); findedDeals.ForEach(d => d.ID = newDealIDs[d.ID]); Percentage += 12.5; if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity)) { ImportDataCache.ResetAll(EntityType.Opportunity); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone()); findedCustomField.ForEach(item => item.EntityID = newDealIDs[item.EntityID]); customFieldDao.SaveList(findedCustomField); Percentage += 12.5; if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity)) { ImportDataCache.ResetAll(EntityType.Opportunity); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone()); foreach (var findedDealMemberKey in findedDealMembers.Keys) { dealDao.SetMembers(newDealIDs[findedDealMemberKey], findedDealMembers[findedDealMemberKey].ToArray()); } Percentage += 12.5; if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity)) { ImportDataCache.ResetAll(EntityType.Opportunity); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone()); foreach (var findedTagKey in findedTags.Keys) { tagDao.SetTagToEntity(EntityType.Opportunity, newDealIDs[findedTagKey], findedTags[findedTagKey].ToArray()); } if (_importSettings.IsPrivate) { findedDeals.ForEach(dealItem => CRMSecurity.SetAccessTo(dealItem, _importSettings.AccessList)); } Percentage += 12.5; if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity)) { ImportDataCache.ResetAll(EntityType.Opportunity); throw new OperationCanceledException(); } ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone()); } Complete(); }
public DaoZoneEntityRelation(DaoFactory factory) : base(factory) { }
public static LpaUnfitCheck SelLpaUnfitCheck(LpaUnfitCheck _param) { return(DaoFactory.GetData <LpaUnfitCheck>("Qms.SelLpaUnfitCheck", _param)); }
public DaoDocumentPackage(DaoFactory factory) : base(factory) { }
public static List <LpaUnfitCheck> SelLpaUnfitChecks(LpaUnfitCheck _param) { return(DaoFactory.GetList <LpaUnfitCheck>("Qms.SelLpaUnfitCheck", _param)); }
public DaoBin(DaoFactory factory) : base(factory) { }
public static int InsLpaUnfitCheck(LpaUnfitCheck _param) { _param.CreateUs = 1; return(DaoFactory.SetInsert("Qms.InsLpaUnfitCheck", _param)); }
public DaoConnectionType(DaoFactory factory) : base(factory) { }
public static int UdtLpaUnfitCheck(LpaUnfitCheck _param) { _param.ModifyUs = 1; return(DaoFactory.SetUpdate("Qms.UdtLpaUnfitCheck", _param)); }
public DaoDataDefinition(DaoFactory factory) : base(factory) { }
public WorkerProcessDb() { _workerDao = DaoFactory.GetWorker(); }
public static int DelLpaUnfitCheck(LpaUnfitCheck _param) { _param.DeleteUs = 1; return(DaoFactory.SetUpdate("Qms.DelLpaUnfitCheck", _param)); }
public IEnumerable <OpportunityWrapper> GetDeals( Guid responsibleid, int opportunityStagesid, IEnumerable <string> tags, int contactid, DealMilestoneStatus?stageType, bool?contactAlsoIsParticipant, ApiDateTime fromDate, ApiDateTime toDate) { DealSortedByType dealSortedByType; IEnumerable <OpportunityWrapper> result; var searchString = _context.FilterValue; OrderBy dealsOrderBy; if (Web.CRM.Classes.EnumExtension.TryParse(_context.SortBy, true, out dealSortedByType)) { dealsOrderBy = new OrderBy(dealSortedByType, !_context.SortDescending); } else if (string.IsNullOrEmpty(_context.SortBy)) { dealsOrderBy = new OrderBy(DealSortedByType.Stage, true); } else { dealsOrderBy = null; } var fromIndex = (int)_context.StartIndex; var count = (int)_context.Count; var tagsList = tags.ToList(); if (dealsOrderBy != null) { result = ToListOpportunityWrapper(DaoFactory.GetDealDao().GetDeals( searchString, responsibleid, opportunityStagesid, tagsList, contactid, stageType, contactAlsoIsParticipant, fromDate, toDate, fromIndex, count, dealsOrderBy)).ToList(); _context.SetDataPaginated(); _context.SetDataFiltered(); _context.SetDataSorted(); } else { result = ToListOpportunityWrapper(DaoFactory.GetDealDao().GetDeals( searchString, responsibleid, opportunityStagesid, tagsList, contactid, stageType, contactAlsoIsParticipant, fromDate, toDate, 0, 0, null)).ToList(); } int totalCount; if (result.Count() < count) { totalCount = fromIndex + result.Count(); } else { totalCount = DaoFactory .GetDealDao() .GetDealsCount(searchString, responsibleid, opportunityStagesid, tagsList, contactid, stageType, contactAlsoIsParticipant, fromDate, toDate); } _context.SetTotalCount(totalCount); return(result.ToSmartList()); }
public DaoIqTable(DaoFactory factory) : base(factory) { }
public void FooDao() { var session = NhSessManager.OpenSession(); var dao = new DaoFactory(session).FooDao; dao.Find(FooSpecs.named(Guid.NewGuid().ToString())); }
public DaoMType(DaoFactory factory) : base(factory) { }
public DaoDocumentBalance(DaoFactory factory) : base(factory) { }
public ServerDomainGroupData AddMailGroupMember(int mailgroupId, int addressId) { if (!IsAdmin) { throw new SecurityException("Need admin privileges."); } if (addressId < 0) { throw new ArgumentException(@"Invalid address id.", "addressId"); } if (mailgroupId < 0) { throw new ArgumentException(@"Invalid mailgroup id.", "mailgroupId"); } using (var daoFactory = new DaoFactory()) { var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant); var group = serverGroupDao.Get(mailgroupId); if (group == null) { throw new Exception("Group not found"); } var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant); var groupMembers = serverAddressDao.GetGroupAddresses(mailgroupId); if (groupMembers.Exists(a => a.Id == addressId)) { throw new DuplicateNameException("Member already exists"); } var newMemberAddress = serverAddressDao.Get(addressId); if (newMemberAddress == null) { throw new Exception("Member not found"); } var serverDao = daoFactory.CreateServerDao(); var server = serverDao.Get(Tenant); var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString); var utcNow = DateTime.UtcNow; ServerAddress groupAddress; string groupEmail; List <ServerDomainAddressData> newGroupMemberDataList; using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted)) { serverAddressDao.AddAddressesToMailGroup(mailgroupId, new List <int> { addressId }); groupMembers.Add(newMemberAddress); groupAddress = serverAddressDao.Get(group.AddressId); var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant); var serverDomain = serverDomainDao.GetDomain(groupAddress.DomainId); var goTo = string.Join(",", groupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name))); groupEmail = string.Format("{0}@{1}", groupAddress.AddressName, serverDomain.Name); newGroupMemberDataList = groupMembers.ConvertAll(m => ServerMailboxEngine.ToServerDomainAddressData(m, string.Format("{0}@{1}", m.AddressName, serverDomain.Name))); var serverAddress = new Alias { Name = "", Address = groupEmail, GoTo = goTo, Domain = serverDomain.Name, IsActive = true, IsGroup = true, Modified = utcNow, Created = utcNow }; engine.SaveAlias(serverAddress); tx.Commit(); } var groupAddressData = ServerMailboxEngine.ToServerDomainAddressData(groupAddress, groupEmail); CacheEngine.ClearAll(); return(ToServerDomainGroupData(group.Id, groupAddressData, newGroupMemberDataList)); } }
public IEnumerable <CurrencyRateWrapper> GetCurrencyRates() { return(DaoFactory.GetCurrencyRateDao().GetAll().ConvertAll(ToCurrencyRateWrapper)); }
public DaoDataType(DaoFactory factory) : base(factory) { }
public void RemoveMailGroupMember(int mailgroupId, int addressId) { if (!IsAdmin) { throw new SecurityException("Need admin privileges."); } if (addressId < 0) { throw new ArgumentException(@"Invalid address id.", "addressId"); } if (mailgroupId < 0) { throw new ArgumentException(@"Invalid mailgroup id.", "mailgroupId"); } using (var daoFactory = new DaoFactory()) { var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant); var group = serverGroupDao.Get(mailgroupId); if (group == null) { throw new Exception("Group not found"); } var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant); var groupMembers = serverAddressDao.GetGroupAddresses(mailgroupId); var removeMember = groupMembers.FirstOrDefault(a => a.Id == addressId); if (removeMember == null) { throw new ArgumentException("Member not found"); } groupMembers.Remove(removeMember); if (groupMembers.Count == 0) { throw new Exception("Can't remove last member; Remove group."); } var serverDao = daoFactory.CreateServerDao(); var server = serverDao.Get(Tenant); var groupAddress = serverAddressDao.Get(group.AddressId); var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant); var serverDomain = serverDomainDao.GetDomain(groupAddress.DomainId); var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString); var utcNow = DateTime.UtcNow; using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted)) { serverAddressDao.DeleteAddressFromMailGroup(mailgroupId, addressId); var goTo = string.Join(",", groupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name))); var groupEmail = string.Format("{0}@{1}", groupAddress.AddressName, serverDomain.Name); var serverAddress = new Alias { Name = "", Address = groupEmail, GoTo = goTo, Domain = serverDomain.Name, IsActive = true, IsGroup = true, Modified = utcNow, Created = group.DateCreated }; engine.SaveAlias(serverAddress); tx.Commit(); } } CacheEngine.ClearAll(); }
public DaoCountSchedule(DaoFactory factory) : base(factory) { }
public ServerDomainGroupData CreateMailGroup(string name, int domainId, List <int> addressIds) { if (!IsAdmin) { throw new SecurityException("Need admin privileges."); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException(@"Invalid mailgroup name.", "name"); } if (domainId < 0) { throw new ArgumentException(@"Invalid domain id.", "domainId"); } if (name.Length > 64) { throw new ArgumentException(@"Local part of mailgroup exceed limitation of 64 characters.", "name"); } if (!Parser.IsEmailLocalPartValid(name)) { throw new ArgumentException(@"Incorrect group name.", "name"); } if (!addressIds.Any()) { throw new ArgumentException(@"Empty collection of address_ids.", "addressIds"); } var mailgroupName = name.ToLowerInvariant(); using (var daoFactory = new DaoFactory()) { var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant); var serverDomain = serverDomainDao.GetDomain(domainId); if (serverDomain.Tenant == Defines.SHARED_TENANT_ID) { throw new InvalidOperationException("Creating mail group is not allowed for shared domain."); } var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant); if (serverAddressDao.IsAddressAlreadyRegistered(mailgroupName, serverDomain.Name)) { throw new DuplicateNameException("You want to create a group with already existing address."); } var utcNow = DateTime.UtcNow; var address = new ServerAddress { Id = 0, Tenant = Tenant, MailboxId = -1, DomainId = serverDomain.Id, AddressName = mailgroupName, IsAlias = false, IsMailGroup = true, DateCreated = utcNow }; var groupEmail = string.Format("{0}@{1}", mailgroupName, serverDomain.Name); var groupAddressData = ServerMailboxEngine.ToServerDomainAddressData(address, groupEmail); var newGroupMembers = serverAddressDao.GetList(addressIds); var newGroupMemberIds = newGroupMembers.ConvertAll(m => m.Id); var newGroupMemberDataList = newGroupMembers.ConvertAll(m => ServerMailboxEngine.ToServerDomainAddressData(m, string.Format("{0}@{1}", m.AddressName, serverDomain.Name))); var goTo = string.Join(",", newGroupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name))); var serverDao = daoFactory.CreateServerDao(); var server = serverDao.Get(Tenant); var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString); var group = new ServerGroup { Id = 0, Tenant = Tenant, Address = groupEmail, AddressId = 0, DateCreated = utcNow }; using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted)) { address.Id = serverAddressDao.Save(address); group.AddressId = address.Id; var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant); group.Id = serverGroupDao.Save(group); serverAddressDao.AddAddressesToMailGroup(group.Id, newGroupMemberIds); var serverAddress = new Alias { Name = "", Address = groupEmail, GoTo = goTo, Domain = serverDomain.Name, IsActive = true, IsGroup = true, Modified = utcNow, Created = utcNow }; engine.SaveAlias(serverAddress); tx.Commit(); } CacheEngine.ClearAll(); return(ToServerDomainGroupData(group.Id, groupAddressData, newGroupMemberDataList)); } }
public DaoLabelMissingComponent(DaoFactory factory) : base(factory) { }
public DaoStatus(DaoFactory factory) : base(factory) { }
public DaoProductCategory(DaoFactory factory) : base(factory) { }
public static void SendAutoReminderAboutTask(DateTime scheduleDate) { var execAlert = new List <int>(); var defaultDao = new DaoFactory(Tenant.DEFAULT_TENANT, CRMConstants.StorageModule); foreach (var row in defaultDao.GetTaskDao() .GetInfoForReminder(scheduleDate)) { var tenantId = Convert.ToInt32(row[0]); var taskId = Convert.ToInt32(row[1]); var deadline = Convert.ToDateTime(row[2]); var alertValue = Convert.ToInt32(row[3]); var responsibleID = !string.IsNullOrEmpty(Convert.ToString(row[4])) ? new Guid(Convert.ToString(row[4])) : Guid.Empty; var deadlineReminderDate = deadline.AddMinutes(-alertValue); if (deadlineReminderDate.Subtract(scheduleDate).Minutes > 1) { continue; } execAlert.Add(taskId); var tenant = CoreContext.TenantManager.GetTenant(tenantId); if (tenant == null || tenant.Status != TenantStatus.Active || TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenant.TenantId).State) { continue; } try { CoreContext.TenantManager.SetCurrentTenant(tenant); SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); var user = CoreContext.UserManager.GetUsers(responsibleID); if (!(!Constants.LostUser.Equals(user) && user.Status == EmployeeStatus.Active)) { continue; } SecurityContext.AuthenticateMe(user.ID); Thread.CurrentThread.CurrentCulture = user.GetCulture(); Thread.CurrentThread.CurrentUICulture = user.GetCulture(); var task = new DaoFactory(tenantId, CRMConstants.StorageModule).GetTaskDao().GetByID(taskId); if (task == null) { continue; } NotifyClient.Instance.SendTaskReminder(task); } catch (Exception ex) { LogManager.GetLogger("ASC.CRM.Tasks").Error("SendAutoReminderAboutTask, tenant: " + tenant.TenantDomain, ex); } } defaultDao.GetTaskDao().ExecAlert(execAlert); }
public DaoMenuOptionType(DaoFactory factory) : base(factory) { }
public EnterpriseProcessDb() { _enterpriseDao = DaoFactory.GetEnterprisesDao(); }
public DaoDocumentLine(DaoFactory factory) : base(factory) { }
public DaoMMaster(DaoFactory factory) : base(factory) { }
public DaoProcessEntityResource(DaoFactory factory) : base(factory) { }
public DaoC_CasNumberRule(DaoFactory factory) : base(factory) { }
public DaoDocumentClass(DaoFactory factory) : base(factory) { }
public IEnumerable <TaskTemplateContainerWrapper> GetTaskTemplateContainers(String entityType) { return(ToTaskListTemplateContainerWrapper(DaoFactory.GetTaskTemplateContainerDao().GetItems(ToEntityType(entityType)))); }
public DaoMeasureUnitConvertion(DaoFactory factory) : base(factory) { }
public static void DataBaseRoutines() { Connection localSQL = null; BasicMngr BasicMngr = new BasicMngr(); DaoFactory Factory = new DaoFactory(); try { localSQL = Factory.DaoConnection().Select(new Connection { Name = "MY" }).First(); } catch { } try { //BasicMngr.DirectSQLNonQuery("EXEC WMS30.dbo.spRoutines", localSQL); Console.WriteLine("\tRoutines OK."); } catch (Exception ex) { Console.WriteLine("\tRoutines Fail. " + ex.Message); } //REcorre los rtProcess que este pendientes por actulizar las tablas de consulta y las actuliza //1. Consultar lo procesosa //Aqui obtiene los registros XML que tiene que procesar IList <DataInformation> list = Factory.DaoDataInformation().Select( new DataInformation { ModTerminal = "T" }).Where(f => f.EntityRowID > 0).ToList(); if (list != null && list.Count > 0) { Document Document; Label Label; string NombreTabla = ""; string updQuery = ""; IList <ShowData> metaData; foreach (DataInformation di in list.Where(f => !string.IsNullOrEmpty(f.XmlData))) { try { if (di.Entity.ClassEntityID == EntityID.Document) { //Obtengo los datos del documento para tener el nombre de la bodega Document = Factory.DaoDocument().Select(new Document { DocID = di.EntityRowID }).First(); //Obtengo el nombre de la bodega que pertenece el registro y creo el nombre de la tabla NombreTabla = "Datos_" + Document.Location.ErpCode; } else if (di.Entity.ClassEntityID == EntityID.Label) { //Obtengo los datos del label para tener el nombre de la bodega Label = Factory.DaoLabel().Select(new Label { LabelID = di.EntityRowID }).First(); try { Location location = Factory.DaoLocation().Select(new Location { LocationID = int.Parse(Label.CreTerminal) }).First(); NombreTabla = "Datos_" + location.ErpCode; } catch { //Obtengo el nombre de la bodega que pertenece el registro y creo el nombre de la tabla NombreTabla = "Datos_" + Label.Bin.Location.ErpCode; } } //Parte incial del update updQuery = "UPDATE dbo." + NombreTabla + " SET ModDate = GETDATE(), RowID = " + di.EntityRowID.ToString() + " "; //Obtiene la lista de campos a actualizar segun la bodega //Es decir los codgios de campos que son tus nombres de columna metaData = DeserializeMetaDataWF(di.XmlData); if (metaData.Count == 0) { di.ModTerminal = null; Factory.DaoDataInformation().Update(di); continue; } //Crear el Update //Aqui va contacenando nombre columna y valor para el update List <string> sColumns = new List <string>(); for (int i = 0; i < metaData.Count; i++) { if (metaData[i].DataKey.ToLower().Equals("id")) { continue; } if (metaData[i].DataKey.ToLower().Equals("productid")) { continue; } if (metaData[i].DataKey.ToLower().Equals("producto")) { continue; } if (metaData[i].DataKey.ToLower().Equals("cantidad")) { continue; } if (!sColumns.Contains(metaData[i].DataKey)) { updQuery += "," + metaData[i].DataKey + " = '" + metaData[i].DataValue + "' \n"; sColumns.Add(metaData[i].DataKey); } } //parte final del update updQuery += " WHERE InstanceID = " + di.RowID.ToString(); //Intenta crear el ID por si no existe //Esto lo hace por si el registro que vpy a actualizar no existe, entonces ///primero se crea un registro en blano en la tabla para que el update funcione ///el ID del registro deberia ser el LabelID para elc aso de los labels y el docuemntid en los docuemntos try { BasicMngr.DirectSQLNonQuery("EXEC dbo.spAdminDynamicData 2, " + di.RowID.ToString() + ",'" + NombreTabla + "'," + di.Entity.ClassEntityID.ToString(), localSQL); } catch { } //Ejecutando el query BasicMngr.DirectSQLNonQuery(updQuery, localSQL); //POniendo la entidad como actualizada di.ModTerminal = null; Factory.DaoDataInformation().Update(di); Console.WriteLine("OK => " + di.EntityRowID + ". " + di.RowID); } catch (Exception ex) { //report the mistake. ExceptionMngr.WriteEvent("Routines: ", ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business); Console.WriteLine(" ERR => " + di.EntityRowID + ". " + di.RowID + ". " + ex.Message); } } } try { //Missing process, si pasadas dos horas falta label o proceso el proceso se recrea a partir del dato recibido. //MissingProcess(localSQL); } catch (Exception ex) { //report the mistake. ExceptionMngr.WriteEvent("Routines: MissingProcess", ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business); } }
public DaoLabelTemplate(DaoFactory factory) : base(factory) { }
protected BasePage() { Scope = DIHelper.Resolve(); DaoFactory = Scope.Resolve <DaoFactory>(); }
public DaoContactEntityRelation(DaoFactory factory) : base(factory) { }
public MailAttachmentData AttachFile(int tenant, string user, MailMessageData message, string name, Stream inputStream, long contentLength, string contentType = null) { if (message == null) { throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found."); } if (string.IsNullOrEmpty(message.StreamId)) { throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "StreamId is empty."); } var messageId = message.Id; var engine = new EngineFactory(tenant, user); var totalSize = engine.AttachmentEngine.GetAttachmentsSize(new ConcreteMessageAttachmentsExp(messageId, tenant, user)); totalSize += contentLength; if (totalSize > Defines.ATTACHMENTS_TOTAL_SIZE_LIMIT) { throw new AttachmentsException(AttachmentsException.Types.TotalSizeExceeded, "Total size of all files exceeds limit!"); } var fileNumber = engine.AttachmentEngine.GetAttachmentNextFileNumber(new ConcreteMessageAttachmentsExp(messageId, tenant, user)); var attachment = new MailAttachmentData { fileName = name, contentType = string.IsNullOrEmpty(contentType) ? MimeMapping.GetMimeMapping(name) : contentType, fileNumber = fileNumber, size = contentLength, data = inputStream.ReadToEnd(), streamId = message.StreamId, tenant = tenant, user = user, mailboxId = message.MailboxId }; engine.QuotaEngine.QuotaUsedAdd(contentLength); try { var storage = new StorageManager(tenant, user); storage.StoreAttachmentWithoutQuota(attachment); } catch { engine.QuotaEngine.QuotaUsedDelete(contentLength); throw; } int attachCount; using (var daoFactory = new DaoFactory()) { var db = daoFactory.DbManager; using (var tx = db.BeginTransaction()) { var daoAttachment = daoFactory.CreateAttachmentDao(tenant, user); attachment.fileId = daoAttachment.SaveAttachment(attachment.ToAttachmnet(messageId)); attachCount = daoAttachment.GetAttachmentsCount( new ConcreteMessageAttachmentsExp(messageId, tenant, user)); var daoMailInfo = daoFactory.CreateMailInfoDao(tenant, user); daoMailInfo.SetFieldValue( SimpleMessagesExp.CreateBuilder(tenant, user) .SetMessageId(messageId) .Build(), MailTable.Columns.AttachCount, attachCount); engine.ChainEngine.UpdateMessageChainAttachmentsFlag(daoFactory, tenant, user, messageId); tx.Commit(); } } if (attachCount == 1) { var data = new MailWrapper { HasAttachments = true }; engine.IndexEngine.Update(data, s => s.Where(m => m.Id, messageId), wrapper => wrapper.HasAttachments); } return(attachment); }