private void StoreValuesToDataSet() { if (DsLogs == null) { ImportDetails impDetails = new ImportDetails(CurrentConnectionManager); DsLogs = impDetails.SelectImportDetailsWithErrors(IdImport, Request.ApplicationPath); DsLogs.Tables[0].PrimaryKey = new DataColumn[] { DsLogs.Tables[0].Columns["IdRow"] }; } Hashtable newValues = new Hashtable(); foreach (GridDataItem item in grdImportDetails.Items) { if (item.IsInEditMode) { if (IsItemModified(item)) { item.ExtractValues(newValues); DataRow row = DsLogs.Tables[0].Rows.Find(item["RowNumber"].Text); if (row.RowState != DataRowState.Deleted) { row["CostCenter"] = DSUtils.GetValueToInsertInDataSet(newValues["CostCenter"]); row["ProjectCode"] = DSUtils.GetValueToInsertInDataSet(newValues["ProjectCode"]); row["WPCode"] = DSUtils.GetValueToInsertInDataSet(newValues["WPCode"]); row["AccountNumber"] = DSUtils.GetValueToInsertInDataSet(newValues["AccountNumber"]); row["AssociateNumber"] = DSUtils.GetValueToInsertInDataSet(newValues["AssociateNumber"]); row["Quantity"] = DSUtils.GetValueToInsertInDataSet(newValues["Quantity"]); row["UnitQty"] = DSUtils.GetValueToInsertInDataSet(newValues["UnitQty"]); row["Value"] = DSUtils.GetValueToInsertInDataSet(newValues["Value"]); row["CurrencyCode"] = DSUtils.GetValueToInsertInDataSet(newValues["CurrencyCode"]); } } } } }
public virtual ActionResult SaveImportDetail(ImportDetailModel model) { if (model.ImportDetailId <= 0) //Create News { if (!ModelState.IsValid) { var categories = _categoryRepository.Search("").ToList(); model.Categories = categories; return(View("_CreateImportDetail", model)); } Random rnd = new Random(); var products = _productRepository.Search("").Where(p => model.ProductIds.Contains(p.ProductId)).ToList(); foreach (var item in products) { int importDetailId = rnd.Next(-9999, -1); ImportDetails.Add(new ImportDetailModel { ImportDetailId = importDetailId, Amount = model.Amount, Note = model.Note, ProductId = item.ProductId, ProductName = item.ProductName, ImportTrackId = model.ImportTrackId, CategoryName = item.Category.CategoryName }); } } this.SetSuccessNotification(string.Format("{0} đã được thêm vào thành công.", "Sản phẩm")); return(RedirectToAction("Create", "ImportTrack", new { area = "Administrator", mode = 1, blank = false })); }
public IActionResult AddPost() { List <int> lstProduct = HttpContext.Session.Get <List <int> >("ssCart"); StoreImportVM.ImportDetails.DateImport = StoreImportVM.ImportDetails.DateImport; //upload chi tiết nhập với tổng giá tiền //ImportDetails import = StoreImportVM.ImportDetails; var productlist = _db.Products.ToList(); foreach (int item in lstProduct) { for (int i = 0; i < productlist.Count; i++) { if (item == productlist[i].ID) { ImportDetails importDetails = new ImportDetails() { DateImport = StoreImportVM.ImportDetails.DateImport, ProductId = item }; _db.ImportDetails.Add(importDetails); } } } _db.SaveChanges(); lstProduct = new List <int>(); HttpContext.Session.Set("ssCart", lstProduct); return(RedirectToAction(nameof(Index))); }
/// <summary> /// Map file to domain entities /// </summary> /// <param name="fileInfo"></param> /// <param name="details"></param> /// <returns></returns> private Transaction[] MapEntities(FileInfo fileInfo, ImportDetails details) { var sw = Stopwatch.StartNew(); try { var items = this.mapper.Map(fileInfo, details.IdImport); details.Total = items.Count(); var itemsWithoutDuplicates = from c in items group c by new { c.BankId, c.AccountAgency, c.AccountId, c.Date, c.Name, c.Value } into grp select grp.FirstOrDefault(); details.TotalWithoutDuplicates = itemsWithoutDuplicates.Count(); return(itemsWithoutDuplicates.ToArray()); } finally { sw.Stop(); details.MappingTime = sw.ElapsedMilliseconds; } }
public async Task <IActionResult> Edit() { if (ModelState.IsValid) { var productFromDb = _db.Products.Where(m => m.ID == StoreImportVM.Products.ID).FirstOrDefault(); int intock = productFromDb.InStock; productFromDb.InStock = StoreImportVM.Products.InStock; int idpro = productFromDb.ID; int count = productFromDb.InStock; await _db.SaveChangesAsync(); int old = Int32.Parse(HttpContext.Session.GetString("oldAmount")); var proc = _db.Products.Where(a => a.ID == idpro).FirstOrDefault(); ImportDetails import = StoreImportVM.ImportDetails; import.ProductId = idpro; import.AmountProduct = count - old; _db.ImportDetails.Add(import); await _db.SaveChangesAsync(); return(RedirectToAction(nameof(Update))); } return(View(StoreImportVM)); }
/// <summary> /// Execute the processing of a given file. /// </summary> /// <param name="fileInfo">File path to import</param> /// <returns>True if success</returns> private async Task <bool> ProcessFile(FileInfo fileInfo) { var details = new ImportDetails() { IdImport = Guid.NewGuid(), StartTime = DateTime.Now, FileName = fileInfo.Name, User = "******" }; try { logger.LogInformation($"Start processing the XML file {fileInfo.Name}"); //Step 1: Map entities var entities = MapEntities(fileInfo, details); //Step 2: Saving entities await SaveEntities(entities, details); //Step 3: Log Success LogSuccess(fileInfo, details); return(true); } catch (Exception e) { LogError(fileInfo, details, e); return(false); } }
protected void grdImportDetails_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e) { try { if (e.CommandName == "UpdateAll") { List <ImportDetails> imList = new List <ImportDetails>(); //First store modifications made in this page to the dataset StoreValuesToDataSet(); //populate list for modified or deleted rows PopulateImportDetailsList(imList); //send modifications to the DB image of the import ImportDetails importDetails = new ImportDetails(CurrentConnectionManager); DataSet dsNewCreatedFile = importDetails.UpdateBatchImportDetails(imList, IdImport); //create new file with current state of import bool result = CreateNewFile(dsNewCreatedFile); if (result) { if (!Page.ClientScript.IsClientScriptBlockRegistered(this.Page.GetType(), "ButtonUpdateClick")) { Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "ButtonUpdateClick", "window.returnValue = 1; window.close();", true); } } else { //After saving, if something went wrong re-load the grid DsLogs = null; LoadEditableGrid(); } } //When changing the page, we need to store any possible modifications made to the current page in the underlying datasource of the //grid if (e.CommandName == "Page") { StoreValuesToDataSet(); } } catch (IndException indExc) { SaveSuccessful = false; ShowError(indExc); } catch (Exception exc) { SaveSuccessful = false; ShowError(new IndException(exc)); } finally { if (!ClientScript.IsClientScriptBlockRegistered(this.GetType(), "ResizePopUp")) { ClientScript.RegisterClientScriptBlock(this.GetType(), "ResizePopUp", "SetPopUpHeight();", true); } } }
/// <summary> /// Logs information for monitoring /// </summary> /// <param name="path">Name of the file.</param> /// <param name="details">Instance of <see cref="ImportDetails" /></param> private void LogSuccess(FileInfo fileInfo, ImportDetails details) { details.Status = nameof(ImportDetailsStatus.Success); details.Message = $"Finishing OFX file '{fileInfo.Name}' processing with success"; details.FinishTime = DateTime.Now; logger.LogInformation($"Finishing import file '{fileInfo.Name}'"); logger.LogInformation(JsonConvert.SerializeObject(details)); }
/// <summary> /// Logs error for monitoring /// </summary> /// <param name="path">Path of the file</param> /// <param name="details">Instance of <see cref="ImportDetails" /></param> /// <param name="exception">Instance of <see cref="Exception"/></param> private void LogError(FileInfo fileInfo, ImportDetails details, Exception exception) { details.Status = nameof(ImportDetailsStatus.Error); details.Message = $"Fail to import file from '{fileInfo.Name}' - Message: {exception.Message} >> StackStrace: {exception.StackTrace}"; details.FinishTime = DateTime.Now; logger.LogInformation($"Finishing import file '{fileInfo.Name}'"); logger.LogError(JsonConvert.SerializeObject(details)); }
/// <summary> /// Imports the in port manning. /// </summary> /// <param name="importedFileData">The imported file data.</param> /// <returns> /// The Collection of In Port Manning Details. /// </returns> public async Task<ListResult<PortManning>> ImportPortManning(ImportDetails importedFileData) { var portManningDetail = string.Empty; var uri = string.Format(CultureInfo.InvariantCulture, ImportPortManningRelativeAddress, this.BaseAddress, ShipResource, string.Format(CultureInfo.InvariantCulture, ImportResource, importedFileData.ShipId)); importedFileData.ShipId = string.Empty; portManningDetail = await this.httpClientHelper.PostRequest(uri, RepositoryBase.SerializeObject(importedFileData), new CancellationToken(false)); return await Task.FromResult(!string.IsNullOrEmpty(portManningDetail) ? JsonConvert.DeserializeObject<ListResult<PortManning>>(portManningDetail) : default(ListResult<PortManning>)); }
public async Task ImportPortManningTest() { var importDetails = new ImportDetails { FileModifiedDate = DateTime.Now, FileName = "Test", NextEmbarkationDate = DateTime.UtcNow, RejectedReason = "Test", ShipId = "5", ImportPortManningDetail = "<IPMDetails><IPMDetail><IPM_POSITION_NAME>QRT -FIRE TEAM 2</IPM_POSITION_NAME><IPM_POSITION_NUMBER>20</IPM_POSITION_NUMBER><IPM_DEPARTMENT>DECK</IPM_DEPARTMENT><FILLED_BY_SAFETY_POSITIONS>0071,0073,0011</FILLED_BY_SAFETY_POSITIONS><IPM_ROLE>QRT - SCBA 3</IPM_ROLE><IPM_EMERGENCY_STATION>FIRE TEAM LOCKER</IPM_EMERGENCY_STATION><IPM_IN_PORT>YES</IPM_IN_PORT><IPM_AT_ANCHOR>No</IPM_AT_ANCHOR></IPMDetail></IPMDetails>", DepartmentDetail = "<DeptDetails><DeptDetail><DeptID> 2</DeptID><DeptName>ART AUCTION</DeptName></DeptDetail></DeptDetails>" }; this.httpClientHelper.Setup(mock => mock.PostRequest(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult("{\"Items\": [ { \"IPMPositionId\": \"3\", \"PositionName\": \"FIRE TEAM 1\", \"PositionNumber\": \"123\", \"DepartmentId\": \"3\", \"Role\": \"QRT - SCBA 3\", \"EmergencyStation\": \"FIRE TEAM LOCKER\", \"ShipId\": \"5\", \"IsInPort\": true, \"IsAtAnchor\": false, \"AddedDate\": \"0001-01-01T00:00:00\", \"PortManningPosition\": [ { \"IPMPositionId\": \"3\", \"SafetyRoleId\": \"3\", \"LastIPMDate\": \"0001-01-01T00:00:00\" } ] }],\"TotalResults\": 0}")); var portManningDetails = await this.repository.ImportPortManning(importDetails); Assert.IsNotNull(portManningDetails); Assert.IsInstanceOfType(portManningDetails, typeof(ListResult<PortManning>)); }
public ActionResult DeleteImportDetail(int id) { try { ImportDetails = ImportDetails.Where(p => p.ImportDetailId != id).ToList(); this.SetSuccessNotification("Sản phẩm đã được bỏ khỏi đơn hàng."); return(RedirectToAction("Create", "Order", new { area = "Administrator" })); } catch { this.SetErrorNotification("Sản phẩm này không thể xóa!"); } return(RedirectToAction("index", new { area = "Administrator" })); }
/// <summary> /// Save entities into database /// </summary> /// <param name="transactions">Transaction to import into database</param> /// <param name="details">Import details to log</param> private async Task SaveEntities(Transaction[] transactions, ImportDetails details) { var sw = Stopwatch.StartNew(); try { await this.repository.BulkInsertOrUpdate(transactions); } finally { sw.Stop(); details.SavingIntoRepositoryTime = sw.ElapsedMilliseconds; } }
private void LoadHeader() { ImportDetails impDetails = new ImportDetails(CurrentConnectionManager); impDetails.IdImport = IdImport; DataSet dsHeader = impDetails.SelectHeaderInformation(); if (dsHeader.Tables.Count != 3) { throw new IndException(ApplicationMessages.EXCEPTION_DATA_SET_CORRUPTED); } DataRow sourceRow = dsHeader.Tables[0].Rows[0]; txtCountry.Text = sourceRow["Country"].ToString(); txtFileName.Text = sourceRow["FileName"].ToString(); txtDate.Text = ((DateTime)sourceRow["Date"]).ToShortDateString(); txtUserName.Text = sourceRow["UserName"].ToString(); string TotalNoOfRows = sourceRow["Lines"].ToString(); txtLines.Text = TotalNoOfRows; //set IDSource to be used in new file name IdSource = Int32.Parse(sourceRow["IdSource"].ToString()); DataRow sourceRow1 = dsHeader.Tables[1].Rows[0]; string NoOfErrors = sourceRow1["NoOfErrors"].ToString(); txtNoOfErrors.Text = NoOfErrors; DataRow sourceRow2 = dsHeader.Tables[2].Rows[0]; string NoOfRowsOK = sourceRow2["NoOfRowsOk"].ToString(); txtNoOfRowsOK.Text = NoOfRowsOK; int NoOfRowsIgnored = int.Parse(TotalNoOfRows) - int.Parse(NoOfRowsOK); txtNoOfRowsIgnored.Text = NoOfRowsIgnored.ToString(); YearMonth yearMonth = new YearMonth(sourceRow["Period"].ToString()); if (yearMonth.Value == ApplicationConstants.YEAR_MONTH_SQL_MIN_VALUE) { txtPeriod.Text = ApplicationConstants.NOT_AVAILABLE; } else { txtPeriod.Text = yearMonth.GetMonthRepresentation() + " - " + yearMonth.Year; } }
public virtual ActionResult Save(ImportTrackModel model) { if (model.ImportTrackId <= 0) //Create News { if (!ModelState.IsValid) { var products = _productRepository.Search("").ToList(); var storages = _storageRepository.Search("").ToList(); model.Products = products; model.Storages = storages; return(View("Create", model)); } if (!ImportDetails.Any()) { SetErrorNotification(string.Format("Bạn chưa có sản phẩm nào.")); return(RedirectToAction("Create", new { area = "Administrator" })); } var entity = new ImportTrack { IsDeleted = false, CreateDate = model.CreateDate, CreateUserId = WorkContext.CurrentUserId, Note = model.Note, ToStorageId = model.StorageId, ImportDetails = new List <ImportDetail>() }; foreach (var orderDetailModel in ImportDetails) { entity.ImportDetails.Add(new ImportDetail { Amount = orderDetailModel.Amount, ProductId = orderDetailModel.ProductId, Note = orderDetailModel.Note, IsDeleted = false }); } using (UnitOfWork) { Repository.Insert(entity); } } ImportTrackSession = new ImportTrackModel(); //Save success this.SetSuccessNotification(string.Format("{0} đã được lưu thành công.", "Nhập kho")); return(RedirectToAction("Create", new { area = "Administrator" })); }
//ILog _logger = log4net.LogManager.GetLogger("Pooling"); public IReservationDBUpdateEntity getItem() { using (var db = new PoolingDataClassesDataContext()) { try { var lastReservation = db.ReservationTeradataControlLogs.Where(d => d.Processed).Max(d => d.TeradataTimeStamp); if (!lastReservation.HasValue) { lastReservation = DateTime.MinValue; } string centralZoneId = "Central Standard Time"; string gmtZoneId = "GMT Standard Time"; TimeZoneInfo centralZone = TimeZoneInfo.FindSystemTimeZoneById(centralZoneId); TimeZoneInfo gmtZone = TimeZoneInfo.FindSystemTimeZoneById(gmtZoneId); var convertedDate = TimeZoneInfo.ConvertTime(lastReservation.Value, centralZone, gmtZone); convertedDate = convertedDate.AddSeconds(-convertedDate.Second); var lastFleet = ImportDetails.GetLastDataImportTime((int)ImportDetails.ImportType.Availability); lastFleet = lastFleet.AddSeconds(-lastFleet.Second); var returned = new ReservationDBUpdateEntity { TeraDataMessage = string.Format("Reservations up to: {0} GMT", convertedDate) , FleetMessage = string.Format("Fleet Last Updated: {0} GMT", lastFleet) }; return(returned); //return (from p in db.ResControls // select new ReservationDBUpdateEntity // { // LastUpdate = p.TimeStamp // , Id = p.Id // }).OrderByDescending(p => p.Id).First(); } catch (SqlException ex) { //if (_logger != null) _logger.Error("Exception thrown in ReservationLogRepository, message : " + ex.Message); } return(new ReservationDBUpdateEntity()); } }
/// <summary> /// Loads the data /// </summary> private void LoadEditableGrid() { if (DsLogs == null) { ImportDetails impDetails = new ImportDetails(CurrentConnectionManager); DsLogs = impDetails.SelectImportDetailsWithErrors(IdImport, Request.ApplicationPath); //Accept changes so that all rows in the dataset have RowState Unchanged DsLogs.AcceptChanges(); grdImportDetails.DataSource = DsLogs; } else { grdImportDetails.DataSource = DsLogs; } DsLogs.Tables[0].PrimaryKey = new DataColumn[] { DsLogs.Tables[0].Columns["IdRow"] }; }
private void PopulateImportDetailsList(List <ImportDetails> imList) { DataView dw = DsLogs.Tables[0].DefaultView; dw.RowStateFilter = DataViewRowState.Deleted | DataViewRowState.ModifiedCurrent; //Traverse the unserlying datasource because the grid contains in its items collection only the items from the current page foreach (DataRowView row in dw) { ImportDetails importDetails = new ImportDetails(CurrentConnectionManager); switch (row.Row.RowState) { case DataRowState.Modified: importDetails.IdImport = (int)row.Row["IdImport"]; importDetails.IdRow = (int)row.Row["IdRow"]; importDetails.CostCenter = (row.Row["CostCenter"] == DBNull.Value) ? string.Empty : row.Row["CostCenter"].ToString(); importDetails.ProjectCode = (row.Row["ProjectCode"] == DBNull.Value) ? string.Empty : row.Row["ProjectCode"].ToString(); importDetails.WPCode = (row.Row["WPCode"] == DBNull.Value) ? string.Empty : row.Row["WPCode"].ToString(); importDetails.AccountNumber = (row.Row["AccountNumber"] == DBNull.Value) ? string.Empty : row.Row["AccountNumber"].ToString(); importDetails.AssociateNumber = (row.Row["AssociateNumber"] == DBNull.Value) ? string.Empty : row.Row["AssociateNumber"].ToString(); importDetails.Quantity = (row.Row["Quantity"] == DBNull.Value) ? ApplicationConstants.DECIMAL_NULL_VALUE : (decimal)row.Row["Quantity"]; importDetails.Value = (row.Row["Value"] == DBNull.Value) ? ApplicationConstants.DECIMAL_NULL_VALUE : (decimal)row.Row["Value"]; importDetails.CurrencyCode = (row.Row["CurrencyCode"] == DBNull.Value) ? string.Empty : row.Row["CurrencyCode"].ToString(); importDetails.SetModified(); imList.Add(importDetails); break; case DataRowState.Deleted: importDetails.IdImport = IdImport; importDetails.IdRow = (int)row.Row["IdRow", DataRowVersion.Original]; importDetails.SetDeleted(); imList.Add(importDetails); break; default: ShowError(new IndException("Unexpected row state")); break; } } }
/// <summary> /// Data the formatting and validations. /// </summary> /// <param name="uploadFile">The upload file.</param> /// <param name="excelReader">The excel reader.</param> /// <param name="visitorPresenter">The visitor presenter.</param> /// <returns> /// Import Details for Data provided. /// </returns> private static ImportDetails DataFormattingAndValidations(HttpPostedFileBase uploadFile, ref IExcelDataReader excelReader, VisitorPresenter visitorPresenter) { var importedFileData = new ImportDetails { FileName = uploadFile.FileName, FileModifiedDate = BaseController.GenerateLocalDateTime(DateTime.UtcNow) }; try { if (uploadFile.FileName.EndsWith(ExcelLatestExtension, StringComparison.OrdinalIgnoreCase)) { excelReader = ExcelReaderFactory.CreateOpenXmlReader(uploadFile.InputStream); } else if (uploadFile.FileName.EndsWith(ExcelNormalExtension, StringComparison.OrdinalIgnoreCase)) { excelReader = ExcelReaderFactory.CreateBinaryReader(uploadFile.InputStream); } using (var result = excelReader.AsDataSet()) { result.Locale = CultureInfo.CurrentCulture; importedFileData = ConvertToCSV(result, importedFileData); excelReader.Close(); } if (string.IsNullOrEmpty(importedFileData.VisitorDetail)) { visitorPresenter.IsImportFailed = true; visitorPresenter.ImportException = string.Format(CultureInfo.CurrentCulture, "{0}{1}.", Resource.ShipNameNotCorrect, SessionData.Instance.MasterData.Ship.Name); } } catch (Exception ex) { if (!string.IsNullOrEmpty(ex.Message)) { visitorPresenter.IsImportFailed = true; visitorPresenter.ImportException = Resource.VisitorImportException; } } importedFileData.RejectedReason = visitorPresenter.ImportException; return importedFileData; }
public DefaultImportImagesViewModel(ImportDetails model) { _model = model; }
/// <summary> /// Converts to CSV. /// </summary> /// <param name="result">The result.</param> /// <param name="importedFileData">The imported file data.</param> /// <returns>The Import Details.</returns> private static ImportDetails ConvertToCSV(DataSet result, ImportDetails importedFileData) { var importDetails = importedFileData; string data = string.Empty; int n = 5; var sheet = result.Tables[0]; if (sheet.Rows[1][1].ToString().Equals(SessionData.Instance.MasterData.Ship.Name, StringComparison.OrdinalIgnoreCase)) { while (n < sheet.Rows.Count) { if (sheet.Rows[n].ItemArray.Any(item => !string.IsNullOrEmpty(item.ToString()))) { data += sheet.Rows[0][0].ToString().Trim() + CommaSeparator; for (int i = 0; i < result.Tables[0].Columns.Count; i++) { data += sheet.Rows[n][i].ToString().Trim() + CommaSeparator; } data += NewLineSeparator; } n++; } importDetails.VisitorDetail = GenerateVisitorXML(data); importDetails.ShipId = SessionData.Instance.MasterData.Ship.ShipId; importDetails.NextEmbarkationDate = Convert.ToDateTime(sheet.Rows[1][4], CultureInfo.InvariantCulture); } else { importDetails.VisitorDetail = string.Empty; } return importDetails; }
static public bool AddShow(ImportDetails details) { return(true); }
/// <summary> /// Imports the visitors. /// </summary> /// <param name="data">The imported file details.</param> /// <returns> /// The List Result for Imported Excel /// </returns> public async Task<Collection<VisitorImport>> ImportVisitors(ImportDetails data) { var uri = string.Format(VisitorRelativeAddress, this.BaseAddress, VisitorResource, ImportResource); var visitors = await this.httpClientHelper.PostRequest(uri, SerializeObject(data), new CancellationToken(false)); return !string.IsNullOrEmpty(visitors) ? JsonConvert.DeserializeObject<Collection<VisitorImport>>(visitors) : default(Collection<VisitorImport>); }
/// <summary> /// Imports the in port manning. /// </summary> /// <param name="result">The result.</param> /// <param name="importedFileData">The imported file data.</param> /// <param name="shipId">The ship identifier.</param> /// <param name="crewDepartments">The crew departments.</param> /// <returns> /// The Collection of In Port Manning Details. /// </returns> public async Task<ListResult<PortManning>> ImportPortManning(DataSet result, ImportDetails importedFileData, string shipId, ICollection<CrewDepartment> crewDepartments) { var importDetails = importedFileData; string data = string.Empty; int n = 1; var sheet = result.Tables[0]; while (n < sheet.Rows.Count) { if (sheet.Rows[n].ItemArray.Any(item => !string.IsNullOrEmpty(item.ToString()))) { for (int i = 0; i < result.Tables[0].Columns.Count; i++) { data += sheet.Rows[n][i] + SemiColonSeparator; } data += NewLineSeparator; } n++; } data = data.TrimEnd('|'); importDetails.ImportPortManningDetail = GeneratePortManningXML(data); importDetails.ShipId = shipId; var rootXml = new XElement(DepartmentDetailRootNode); foreach (var crewDep in crewDepartments) { var childXml = new XElement(DepartmentDetailNode); childXml.Add(new XElement(DepartmentIdNode, crewDep.DepartmentId)); childXml.Add(new XElement(DepartmentNameNode, crewDep.Name)); rootXml.Add(childXml); } importDetails.DepartmentDetail = rootXml.ToString(); var inPortManningDetail = await this.repository.ImportPortManning(importDetails); return inPortManningDetail; }
public async Task ImportVisitorsTests() { var importDetails = new ImportDetails { FileModifiedDate = DateTime.Now, FileName = "Test", NextEmbarkationDate = DateTime.UtcNow, RejectedReason = "Test", ShipId = "<Firstname>John<Firstname>", VisitorDetail = "Test" }; await this.visitorRepository.ImportVisitors(importDetails); Assert.IsTrue(true); }
public static bool AddShow(ImportDetails details) { return true; }
/// <summary> /// Imports the visitors. /// </summary> /// <param name="data">The imported file details.</param> /// <returns> /// The List Result for Imported Excel /// </returns> public Task<Collection<VisitorImport>> ImportVisitors(ImportDetails data) { return this.visitorRepository.ImportVisitors(data); }
/// <summary> /// Data the formatting and validations. /// </summary> /// <param name="uploadFile">The upload file.</param> /// <param name="presenter">The presenter.</param> /// <returns> /// Import Details for Data provided. /// </returns> private async Task<PortManningPresenter> DataFormattingAndValidations(HttpPostedFileBase uploadFile, PortManningPresenter presenter) { IExcelDataReader excelReader = null; var importedFileData = new ImportDetails(); try { if (uploadFile.FileName.EndsWith(ExcelLatestExtension, StringComparison.OrdinalIgnoreCase)) { excelReader = ExcelReaderFactory.CreateOpenXmlReader(uploadFile.InputStream); } else if (uploadFile.FileName.EndsWith(ExcelNormalExtension, StringComparison.OrdinalIgnoreCase)) { excelReader = ExcelReaderFactory.CreateBinaryReader(uploadFile.InputStream); } if (excelReader != null) { using (var result = excelReader.AsDataSet()) { result.Locale = CultureInfo.CurrentCulture; var importManningDetail = await this.manager.ImportPortManning(result, importedFileData, SessionData.Instance.MasterData.Ship.ShipId, SessionData.Instance.MasterData.CrewDepartments); if (importManningDetail.Items.Count > 0) { presenter.AssignInPortManningList(importManningDetail); } else { presenter.IsImportFailed = true; presenter.ImportException = string.Format(CultureInfo.CurrentCulture, "{0}{1}.", Resource.ShipNameNotCorrect, SessionData.Instance.MasterData.Ship.Name); } excelReader.Close(); } } } catch (Exception ex) { if (!string.IsNullOrEmpty(ex.Message)) { presenter.IsImportFailed = true; presenter.ImportException = Resource.ImportSpreadsheetException; } } finally { if (excelReader != null) { excelReader.Dispose(); } } return presenter; }