public void AddOrderDetail(OrderDetail orderDetail, int userId, OrderType type) { var user = _userRepository.TableNoTracking.FirstOrDefault(c => c.Id == userId); if (user == null) { throw new ArgumentNullException(nameof(orderDetail)); } if (IsLocked(DateTime.Now)) { throw new StaffingPurchaseException(_resourceManager.GetString("Order.Validation.IsLocked")); } if (!IsEligibleUser(user)) { throw new StaffingPurchaseException(_resourceManager.GetString("Order.Validation.NotEligibleUser")); } if (GetOrder(user.Id, new[] { OrderStatus.Approved, OrderStatus.Packaged, OrderStatus.Submitted }, type) != null) { throw new StaffingPurchaseException(_resourceManager.GetString("Order.Validation.OrderInSessionExist")); } using (var transaction = _dbContext.BeginDbTransaction()) { try { // If there is no order existing, create new order and add into it this order detail var order = GetOrder(user.Id, new[] { OrderStatus.Draft }, type); if (order != null) { AddOrderDetailExistOrder(orderDetail, user, order); } else { AddOrderDetailNoOrder(orderDetail, type, user); } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } }
public void UpdateMultiLevelGroups(IEnumerable <LevelGroup> levelGroups) { using (var transaction = _dbContext.BeginDbTransaction()) { try { var oldLevelGroups = GetAllLevelGroups().Select(x => new { x.Id, x.PV }); var results = from t in levelGroups join l in oldLevelGroups on t.Id equals l.Id where Math.Abs(t.PV - l.PV) > float.Epsilon select t; foreach (var result in results) { var efLevelGroup = GetLevelGroupById(result.Id); efLevelGroup.PV = result.PV; UpdateLevelGroup(efLevelGroup); } transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw; } } }
public void UpdateMultiLevels(IEnumerable <Level> levels) { using (var transaction = _dbContext.BeginDbTransaction()) { try { var oldLevels = GetAllLevels().Select(x => new { x.Id, x.GroupId }); var results = from t in levels join l in oldLevels on t.Id equals l.Id where t.GroupId != l.GroupId select t; foreach (var result in results) { var level = GetLevelById(result.Id); level.GroupId = result.GroupId; UpdateLevel(level); } transaction.Commit(); } catch (System.Exception) { transaction.Rollback(); throw; } } }
public void Approve(WorkingUser user, OrderBatch orderBatch) { using (var dbTransaction = _dbContext.BeginDbTransaction()) { try { ApproveBatch(user, orderBatch); dbTransaction.Commit(); } catch (Exception ex) { dbTransaction.Rollback(); _logger.WriteLog(string.Format("Failed to approve orderBatch {0}", orderBatch.Id), ex); } } }
public void CopyDistributorFromDSS(IEnumerable <DistributorUpdateDTO> distUpdates, out string errorMessage) { var dssDists = GetDSSDistributors(distUpdates.Select(x => x.DistNumber)); StringBuilder sbMessage = new StringBuilder(); foreach (var dssDist in dssDists) { if (_distributorRepository.TableNoTracking.Any(x => x.DistNumber == dssDist.DistributorNo)) { _logger.WriteLog(string.Format("Distributor {0} already existed in ABO", dssDist.DistributorNo), LogLevel.Warning); } else { var dist = ConvertDSSDistributor(dssDist); var distUpdate = distUpdates.FirstOrDefault(x => x.DistNumber == dist.DistNumber); dist.WarehouseId = GetWarehouseId(distUpdate.Logs[0].WAREHOUSE); using (var dbTransaction = _dbContext.BeginDbTransaction()) { try { dist.DistributorUpdates.Add(new DistributorUpdate() { DistNumber = dist.DistNumber, UpdatedDate = DateTime.Now, UpdatedType = GetDistributorUpdateTypeDesc(distUpdate.Logs[0].UPDATETYPE), WarehouseId = dist.WarehouseId, StatusId = (short)DistributorUpdateStatus.NotCompleted, }); _distributorRepository.Insert(dist); dbTransaction.Commit(); _logger.WriteLog("Success to copy distributor " + dist.DistNumber, LogLevel.Info); } catch (Exception ex) { dbTransaction.Rollback(); sbMessage.AppendFormat("\r\nFailed to insert distributor {0}. Error: {1}; ", dist.DistNumber, CommonHelper.GetFullExceptionDetails(ex)); } } } } errorMessage = sbMessage.ToString(); }
public void PackageAllOrder(WorkingUser warehouseStaff, OrderType?orderType = null) { using (var transation = _dbContext.BeginDbTransaction()) { try { var user = _userRepository.TableNoTracking.FirstOrDefault(c => c.Id == warehouseStaff.Id); var departments = GetDepartmentsWithOrderStatus(user.LocationId.Value, new[] { OrderStatus.Approved }); var currentDateTime = DateTime.Now; foreach (var department in departments) { var log = new PackageLog { LocationId = user.LocationId.GetValueOrDefault(0), DepartmentId = department.Id, PackedDate = currentDateTime, WarehouseUserId = user.Id, WarehouseUserName = user.UserName, FullPacked = true, Comment = "", OrderType = (int)orderType }; _pkgLogRepository.Insert(log); _orderRepository.BulkUpdate(PackageFilter(warehouseStaff, orderType, department.Id), c => new Order { StatusId = (short)OrderStatus.Packaged, PackageLogId = log.Id }); } transation.Commit(); } catch (Exception ex) { transation.Rollback(); _logger.WriteLog($"Cannot package all orders with warehouser {warehouseStaff.UserName} and orderType {orderType}", ex); throw; } } }
public void UploadUsersImage(long adaNo, ProspectAvatar avatar1, ProspectAvatar avatar2) { var currentAvatars = this.GetImageByAdaNo(adaNo, false); var inactiveToken = "I"; using (var transaction = _wtaDbContext.BeginDbTransaction()) { try { for (int i = 0; i < 2; i++) { var clonedAvatar = i == 0 ? (ProspectAvatar)avatar1.Clone() : (ProspectAvatar)avatar2.Clone(); if (clonedAvatar.img_streamdata != null && clonedAvatar.img_streamdata.Length != 0 && !string.IsNullOrEmpty(currentAvatars[i].img_cmnd_id)) { var currentCmndId = currentAvatars[i].img_cmnd_id; var inactiveAvatar = _prospectAvatarRepository.Table.FirstOrDefault( c => c.img_cmnd_id == currentCmndId && c.img_status == inactiveToken); if (inactiveAvatar != null) { _prospectAvatarRepository.Delete(inactiveAvatar); } var remoteAvatar1 = (ProspectAvatar)currentAvatars[i].Clone(); remoteAvatar1.img_status = "I"; _prospectAvatarRepository.Delete(currentAvatars[i]); _prospectAvatarRepository.Insert(remoteAvatar1); clonedAvatar.img_cmnd_id = remoteAvatar1.img_cmnd_id; clonedAvatar.img_status = "A"; clonedAvatar.img_file_path = remoteAvatar1.img_file_path; _prospectAvatarRepository.Insert(clonedAvatar); } } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } }
public void ScanAndCopyProfiles() { Console.WriteLine("Profile Box folder: " + _appSettings.ProfileBoxFolder); // Get scannable boxes var boxes = GetScannableBoxes(); foreach (var box in boxes.Where(x => !string.IsNullOrEmpty(x.ScannedFolder))) // only scan box whose ScannedFolder was configured { if (Directory.Exists(box.ScannedFolder)) { if (CommonHelper.HasPermissionOnFolder(box.ScannedFolder, System.Security.AccessControl.FileSystemRights.Modify)) { _logger.WriteLog(string.Format("Scanning box \"{0}\" - folder: \"{1}\"", box.Name, box.ScannedFolder), LogLevel.Info); var scannedFilePaths = Directory.GetFiles(box.ScannedFolder); if (scannedFilePaths.Length > 0) { _logger.WriteLog(string.Format("Found {1} file(s) in folder: {0}", box.ScannedFolder, scannedFilePaths.Length), LogLevel.Debug); var scanResult = ProfileScanResult.OK; var sbMoveFileError = new StringBuilder(); var sbDistNotFound = new StringBuilder(); var joinProfileExistedDists = new List <long>(); var scannedDistributorUpdateIds = new List <int>(); var movedFileList = new List <Tuple <string, string> >(); if (box.Profiles == null) { box.Profiles = new List <Profile>(); } foreach (var filePath in scannedFilePaths) { #region Move file and create new profile var fileName = Path.GetFileName(filePath); var distNumber = GetDistNumberFromFileName(fileName, (SystemProfileBoxType)box.TypeId); if (distNumber > 0) { if (_distributorService.IsDistributorExisted(distNumber)) { // Check if 'join' profile existed for this distributor if (IsJoinProfileExisted(distNumber, box.TypeId)) { joinProfileExistedDists.Add(distNumber); } else { Profile profile = null; try { // Enqueue file var copiedFileName = GetCopiedProfileFileName(fileName); movedFileList.Add(new Tuple <string, string>(filePath, copiedFileName)); // Create new profile profile = new Profile() { CreatedDate = DateTime.Now, DistNumber = distNumber, StatusId = (short)ProfileStatus.Valid, TypeId = box.TypeId, WarehouseId = box.WarehouseId, FileName = copiedFileName, ScannedDate = DateTime.Now }; box.Profiles.Add(profile); // Find and update DistributorUpdate record var distUpdates = _distributorService.SearchDistributorUpdates(new DistributorUpdateSearchCriteria { DistNumber = distNumber, Statuses = new[] { (short)DistributorUpdateStatus.NotCompleted } }, 1, 100, null, null); if (distUpdates.Count > 0) { var distUpdateIds = distUpdates.Select(x => x.Id); scannedDistributorUpdateIds.AddRange(distUpdateIds); _logger.WriteLog(string.Format("Found {0} DistributorUpdate record(s) with id {1} for distributor {2}", distUpdates.Count, string.Join(", ", distUpdateIds), distNumber), LogLevel.Info); } _logger.WriteLog("Success to enqueue file: " + fileName, LogLevel.Info); } catch (Exception ex) { if (profile != null) { box.Profiles.Remove(profile); } sbMoveFileError.AppendFormat(", {0}", fileName); scanResult = ProfileScanResult.Error; _logger.WriteLog(string.Format("Failed to enqueue file: {0}", fileName), ex); } } } else { sbDistNotFound.AppendFormat(", {0}", distNumber); } } #endregion } // build description string var description = (sbMoveFileError.Length > 0 ? string.Format(PROFILESCAN_MOVEFILE_ERROR, sbMoveFileError.Remove(0, 2)) : string.Empty) + (sbDistNotFound.Length > 0 ? "\r\n" + string.Format(PROFILESCAN_DISTRIBUTOR_NOTFOUND, sbDistNotFound.Remove(0, 2)) : string.Empty) + (joinProfileExistedDists.Any() ? "\r\n" + string.Format(PROFILESCAN_JOINPROFILE_EXISTED, string.Join(", ", joinProfileExistedDists)) : string.Empty); // Log to ProfileScan table var profileScan = new ProfileScan() { WarehouseId = box.WarehouseId, FileCount = scannedFilePaths.Length, Result = (short)scanResult, ScannedDate = DateTime.Now, Description = description }; box.ProfileScans.Add(profileScan); box.UpdatedDate = DateTime.Now; // Update database using (var dbTransaction = _dbContext.BeginDbTransaction()) { try { _profileBoxRepository.Update(box); UpdateProfileAndADACount(box); // Write log for each profile after Id is generated foreach (var profile in box.Profiles) { CreateLogRecord("tblProfile", "Id", profile.Id, null, profile.Id, AUTO_JOB_USER, PROFILE_SCAN_LOG); } // Update DistributorUpdate table _distributorService.MarkDistributorUpdatesCompleted(scannedDistributorUpdateIds); dbTransaction.Commit(); // Move files only after all data are saved to DB successfully string fileMoveMessage; MoveProfileFiles(movedFileList, Path.Combine(_appSettings.ProfileBoxFolder, box.Name), out fileMoveMessage); // Update profile description if any if (!string.IsNullOrEmpty(fileMoveMessage)) { profileScan.Description = (string.IsNullOrEmpty(profileScan.Description) ? "" : "\r\n") + fileMoveMessage; _profileScanRepository.Update(profileScan); } } catch (Exception ex) { dbTransaction.Rollback(); _logger.WriteLog(string.Format("Failed to update box \"{0}\" in database.", box.Name), ex); } } } else { _logger.WriteLog(string.Format("No profile found in folder: {0}", box.ScannedFolder), LogLevel.Debug); } } else { // Record error _profileScanRepository.Insert(new ProfileScan() { BoxId = box.Id, WarehouseId = box.WarehouseId, FileCount = 0, Result = (short)ProfileScanResult.Error, ScannedDate = DateTime.Now, Description = PROFILESCAN_FOLDER_NOPERMISSION }); } } else { // Record error _profileScanRepository.Insert(new ProfileScan() { BoxId = box.Id, WarehouseId = box.WarehouseId, FileCount = 0, Result = (short)ProfileScanResult.Error, ScannedDate = DateTime.Now, Description = PROFILESCAN_FOLDER_NOTFOUND }); } } }