private async Task <string> ProcessFile(string tempFile, string tempDirectory, CancellationToken ct) { try { var compressed = await _compressionService.Compress(tempFile, tempDirectory, ct); var compressedFilePath = Path.Combine(tempDirectory, compressed); var uploadedFilePath = _uploadService.UploadFile(tempDirectory, compressedFilePath); return(uploadedFilePath); } catch (Exception) { CleanUp(tempDirectory); throw; } }
public ValueDataResponse <SiteInfo> InsertSite(SiteInfo sites) { ValueDataResponse <SiteInfo> response = new ValueDataResponse <SiteInfo>(); try { var siteExists = _appContext.SiteInfos.Where(x => x.SiteReference == sites.SiteReference).FirstOrDefault(); if (siteExists == null) { // if (sites.Address != null) // { // coordinates LatLong = GetLatLngByAddress(sites.Address.ToString()); // if (LatLong != null) // { // sites.Latitude = (float)(LatLong.Latitude); // sites.Longitude = (float)LatLong.Longitude; // } // } var result = _appContext.SiteInfos.Add(sites); if (sites.FileName != null) { string ModuleName = "Site"; var now = DateTime.Now; var yearName = now.ToString("yyyy"); var monthName = now.Month.ToString("d2"); var dayName = now.ToString("dd"); FileUploadService repo = new FileUploadService(); //string FolderLocation = _config.Value.FileRepositoryFolder; string FolderLocation = "FileRepository"; string ServerRootPath = _config.Value.ServerRootPath; string Location = ServerRootPath + @"\" + FolderLocation + @"\" + yearName + @"\" + monthName + @"\" + dayName + @"\" + ModuleName; // string Location = Path.Combine(ServerRootPath, FolderLocation, yearName, monthName, dayName, ModuleName); byte[] FileBytes = Convert.FromBase64String(sites.FileName); sites.FileName = repo.UploadFile(FileBytes, sites.FileExtention, Location); sites.FileLocation = Path.Combine(yearName, monthName, dayName, ModuleName); } _appContext.SaveChanges(); if (result != null) { response.Result = sites; response.IsSuccess = true; response.AffectedRecords = 1; response.EndUserMessage = "Site Added Successfully"; } else { response.IsSuccess = true; response.AffectedRecords = 0; response.EndUserMessage = "Site Added Failed"; } } else { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = "Site Reference Already Exists"; } } catch (Exception ex) { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = ex.InnerException == null ? ex.Message : ex.InnerException.Message; response.Exception = ex; } return(response); }
public ActionResult UploadBarCodeLogImport(HttpPostedFileBase fileBase) { HttpPostedFileBase file = Request.Files["files"]; #region 【参数初始化】 string uploadFileName = ""; string uploadFileAddress = ""; string failFileName = ""; string failFileAddress = ""; string ext = ""; string noFileName = ""; string uploadDomain = "/TireLog/BarCode"; string barCodeBatchNum = DateTime.Now.ToString("yyyyMMddHHmmss"); #endregion #region 【导入文件预判断】 if (file == null || file.ContentLength <= 0) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件不能为空" })); } var filesize = file.ContentLength; //获取上传文件的大小单位为字节byte ext = System.IO.Path.GetExtension(file.FileName); //获取上传文件的扩展名 noFileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName); //获取无扩展名的文件名 const string fileType = ".xls,.xlsx"; //定义上传文件的类型字符串 if (string.IsNullOrWhiteSpace(ext)) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件扩展名不能为空" })); } if (!fileType.Contains(ext)) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件类型不对,只能导入xls和xlsx格式的文件" })); } #endregion #region 【源文件上传】 var stream = file.InputStream; var buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); uploadFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + noFileName + ext; var result = FileUploadService.UploadFile(buffer, ext, uploadFileName, uploadDomain); if (!string.IsNullOrWhiteSpace(result)) { uploadFileAddress = "https://img1.tuhu.org" + result; } else { return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } UploadBarCodeLog barLog = new UploadBarCodeLog { UploadFileName = uploadFileName, UploadFileAddress = uploadFileAddress, Operator = ThreadIdentity.Operator.Name }; #endregion #region 【检查数据缺失】 stream.Position = 0; var excel = new Controls.ExcelHelper(stream, file.FileName); var dt = excel.ExcelToDataTable("sheet1", true); if (buffer.Length > 0 && (dt == null || dt.Rows == null || dt.Rows.Count < 1)) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } StringBuilder failSB = new StringBuilder(); List <InputBarCode> congifList = new List <InputBarCode>(); for (int i = 0; i < dt.Rows.Count; i++) { if (null == dt.Rows[i]["条码"] || string.IsNullOrWhiteSpace(dt.Rows[i]["条码"].ToString()) || null == dt.Rows[i]["防伪码"] || string.IsNullOrWhiteSpace(dt.Rows[i]["防伪码"].ToString())) { failSB.AppendLine("第" + (i + 2) + "行:条码或防伪码数据不完整."); } else { congifList.Add(new InputBarCode { BarCode = dt.Rows[i]["条码"].ToString(), SecurityCode = dt.Rows[i]["防伪码"].ToString(), BarCodeBatchNum = barCodeBatchNum }); } } if (failSB.Length > 0) { byte[] arrayFail_Params = Encoding.GetEncoding("gb2312").GetBytes(failSB.ToString()); failFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + noFileName + "_Error" + ".txt"; result = FileUploadService.UploadFile(arrayFail_Params, ".txt", failFileName, uploadDomain); if (!string.IsNullOrWhiteSpace(result)) { failFileAddress = "https://img1.tuhu.org" + result; } else { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } barLog.FailFileName = failFileName; barLog.FailFileAddress = failFileAddress; barLog.CreateTime = DateTime.Now; barLog.LastUpdateDataTime = DateTime.Now; var insertLog_Params = TireSecurityCodeConfigManager.InsertUploadBarCodeLog(barLog); if (insertLog_Params) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "数据有缺失,请检查错误日志,整理数据后重新上传." })); } else { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } } #endregion #region 【检查数据重复】 var checkSCodeDup = congifList .GroupBy(item => item.SecurityCode) .Select(item => item.First()) .ToList <InputBarCode>().Count; if (checkSCodeDup < congifList.Count) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "防伪码数据有重复,请Excel排查后重新上传." })); } var checkBarCodeDup = congifList .GroupBy(item => item.BarCode) .Select(item => item.First()) .ToList <InputBarCode>().Count; if (checkBarCodeDup < congifList.Count) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "条码数据有重复,请Excel排查后重新上传." })); } #endregion #region 【批量更新数据】 congifList = congifList .GroupBy(item => item.SecurityCode) .Select(item => item.First()) .ToList <InputBarCode>(); var updateBarCode = TireSecurityCodeConfigManager.InsertBarCodeConfig(congifList); List <InputBarCode> errorInputList = new List <InputBarCode>(); switch (updateBarCode) { case -2: errorInputList = TireSecurityCodeConfigManager.QueryInputBarCodeByError("ItemNotExist", congifList); failSB.AppendLine("以下防伪码还没上传过,请检查数据."); failSB.AppendLine("防伪码,条码"); foreach (var error in errorInputList) { failSB.AppendLine(error.SecurityCode + "," + error.BarCode); } byte[] arrayFail_ItemNotExist = Encoding.GetEncoding("gb2312").GetBytes(failSB.ToString()); failFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + noFileName + "_Error" + ".txt"; result = FileUploadService.UploadFile(arrayFail_ItemNotExist, ".txt", failFileName, uploadDomain); if (!string.IsNullOrWhiteSpace(result)) { failFileAddress = "https://img1.tuhu.org" + result; } else { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } barLog.FailFileName = failFileName; barLog.FailFileAddress = failFileAddress; barLog.CreateTime = DateTime.Now; barLog.LastUpdateDataTime = DateTime.Now; var insertLog_ItemNotExist = TireSecurityCodeConfigManager.InsertUploadBarCodeLog(barLog); if (insertLog_ItemNotExist) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "数据里有不存在的防伪码,请检查错误日志,整理数据后重新上传." })); } else { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } case -3: return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "本次上传数据均存在,不做更新." })); case -4: errorInputList = TireSecurityCodeConfigManager.QueryInputBarCodeByError("Difference", congifList); failSB.AppendLine("以下防伪码或条码已经存在过,请删除已存在数据后重新上传."); failSB.AppendLine("防伪码,条码"); foreach (var error in errorInputList) { failSB.AppendLine(error.SecurityCode + "," + error.BarCode); } byte[] arrayFail_Difference = Encoding.GetEncoding("gb2312").GetBytes(failSB.ToString()); failFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + noFileName + "_Error" + ".txt"; result = FileUploadService.UploadFile(arrayFail_Difference, ".txt", failFileName, uploadDomain); if (!string.IsNullOrWhiteSpace(result)) { failFileAddress = "https://img1.tuhu.org" + result; } else { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } barLog.FailFileName = failFileName; barLog.FailFileAddress = failFileAddress; barLog.CreateTime = DateTime.Now; barLog.LastUpdateDataTime = DateTime.Now; var insertLog_Difference = TireSecurityCodeConfigManager.InsertUploadBarCodeLog(barLog); if (insertLog_Difference) { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "部分数据已存在,请检查错误日志,整理数据后重新上传." })); } else { return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } case -1: return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "上传失败,刷新页面重试." })); } #endregion #region 【记录上传文件日志】 barLog.FailFileName = failFileName; barLog.FailFileAddress = failFileAddress; barLog.CreateTime = DateTime.Now; barLog.LastUpdateDataTime = DateTime.Now; var insertLog = TireSecurityCodeConfigManager.InsertUploadBarCodeLog(barLog); if (!insertLog) { TireSecurityCodeConfigManager.DeleleBarCodeByBatchNum(barCodeBatchNum); return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } #endregion return(RedirectToAction("UploadBarCodeLog", "TireSecurityCode", new { msg = "导入成功" })); }
public ActionResult UploadSecurityCodeLogImport(HttpPostedFileBase fileBase) { HttpPostedFileBase file = Request.Files["files"]; #region 【参数初始化】 string uploadFileName = ""; string uploadFileAddress = ""; string successFileName = ""; string successFileAddress = ""; string failFileName = ""; string failFileAddress = ""; string ext = ""; string noFileName = ""; string uploadDomain = "/TireLog/SecurityCode"; string batchNum = DateTime.Now.ToString("yyyyMMddHHmmss"); #endregion #region 【导入文件预判断】 if (file == null || file.ContentLength <= 0) { return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "文件不能为空" })); } var filesize = file.ContentLength; //获取上传文件的大小单位为字节byte ext = System.IO.Path.GetExtension(file.FileName); //获取上传文件的扩展名 noFileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName); //获取无扩展名的文件名 const string fileType = ".txt"; //定义上传文件的类型字符串 if (string.IsNullOrWhiteSpace(ext)) { return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "文件扩展名不能为空" })); } if (!fileType.Contains(ext)) { return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "文件类型不对,只能导入txt格式的文件" })); } #endregion #region 【源文件上传】 var stream = file.InputStream; var buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); uploadFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + noFileName + ext; var result = FileUploadService.UploadFile(buffer, ext, uploadFileName, uploadDomain); if (!string.IsNullOrWhiteSpace(result)) { uploadFileAddress = "https://img1.tuhu.org" + result; } else { return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } #endregion #region 【拆分异常数据、去重】 stream.Position = 0; StreamReader sr = new StreamReader(stream, System.Text.Encoding.GetEncoding("gb2312")); StringBuilder successSB = new StringBuilder(); StringBuilder failSB = new StringBuilder(); string line; List <TireSecurityCodeConfig> congifList = new List <TireSecurityCodeConfig>(); while ((line = sr.ReadLine()) != null) { if (line.Contains("二") && line.Contains("维")) { } else { string uCode = ""; string fCode = ""; string securityCode = ""; try { uCode = line.Substring(line.IndexOf("?u=") + 3, line.IndexOf("&f") - line.IndexOf("?u=") - 3); fCode = line.Substring(line.IndexOf("&f=") + 3, line.LastIndexOf(",") - line.IndexOf("&f=") - 3); securityCode = line.Substring(line.LastIndexOf(",") + 1, line.Length - line.LastIndexOf(",") - 1).Trim(); } catch (Exception ex) { failSB.AppendLine(line + ":参数错误"); continue; } if (uCode == "" || !IsNumeric(uCode) || fCode == "" || !IsNumeric(fCode) || securityCode == "" || !IsNumeric(securityCode)) { failSB.AppendLine(line + ":参数错误"); continue; } else { TireSecurityCodeConfig config = new TireSecurityCodeConfig { CodeID = Guid.NewGuid(), CreateTime = DateTime.Now, LastUpdateDataTime = DateTime.Now, UCode = uCode, FCode = fCode, SecurityCode = securityCode, DataIntegrity = false, BatchNum = batchNum }; congifList.Add(config); continue; } } } congifList = congifList .GroupBy(item => item.SecurityCode) .Select(item => item.First()) .ToList <TireSecurityCodeConfig>(); #endregion #region 【批量插入数据】 var insertResult = TireSecurityCodeConfigManager.InsertTireSecurityCodeConfig(congifList); if (insertResult) { var insertList = TireSecurityCodeConfigManager.QuerySecurityCodeConfigModelByBatchNum(batchNum); if (insertList == null || insertList.Count == 0) { return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "本次上传数据均存在,不做更新." })); } foreach (var insert in insertList) { string lineSuccees = "https://wx.tuhu.cn/vue/antifake/pages/home/select?guid=" + insert.CodeID.ToString("D") + "," + insert.SecurityCode; successSB.AppendLine(lineSuccees); } } else { failSB.AppendLine("数据失败,刷新页面重试."); } #endregion #region 【生成成功\失败文件地址】 if (successSB.Length > 0) { byte[] arraySuccess = Encoding.GetEncoding("gb2312").GetBytes(successSB.ToString()); successFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + noFileName + "_二维码" + ext; result = FileUploadService.UploadFile(arraySuccess, ext, successFileName, uploadDomain); if (!string.IsNullOrWhiteSpace(result)) { successFileAddress = "https://img1.tuhu.org" + result; } else { TireSecurityCodeConfigManager.DeleleSecurityCodeConfigModelByBatchNum(batchNum); return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } } if (failSB.Length > 0) { byte[] arrayFail = Encoding.GetEncoding("gb2312").GetBytes(failSB.ToString()); failFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + noFileName + "_Error" + ext; result = FileUploadService.UploadFile(arrayFail, ext, failFileName, uploadDomain); if (!string.IsNullOrWhiteSpace(result)) { failFileAddress = "https://img1.tuhu.org" + result; } else { TireSecurityCodeConfigManager.DeleleSecurityCodeConfigModelByBatchNum(batchNum); return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "文件上传失败" })); } } #endregion #region 【记录上传文件日志】 UploadSecurityCodeLog scLog = new UploadSecurityCodeLog { UploadFileName = uploadFileName, UploadFileAddress = uploadFileAddress, SuccessFileName = successFileName, SuccessFileAddress = successFileAddress, FailFileName = failFileName, FailFileAddress = failFileAddress, CreateTime = DateTime.Now, LastUpdateDataTime = DateTime.Now, Operator = ThreadIdentity.Operator.Name, }; var insertLog = TireSecurityCodeConfigManager.InsertUploadSecurityCodeLog(scLog); #endregion return(RedirectToAction("UploadSecurityCodeLog", "TireSecurityCode", new { msg = "导入成功" })); }
public async Task <IActionResult> Register([FromBody] UserFileViewModel user) { if (!(await _authorizationService.AuthorizeAsync(this.User, (user.Roles, new string[] { }), Authorization.Policies.AssignAllowedRolesPolicy)).Succeeded) { return(new ChallengeResult()); } if (ModelState.IsValid) { if (user == null) { return(BadRequest($"{nameof(user)} cannot be null")); } ApplicationUser appUser = _mapper.Map <ApplicationUser>(user); var result = await _accountManager.CreateUserAsync(appUser, user.Roles, user.NewPassword); foreach (var up in user.ProjectIds) { _appcontext.UserProjectXrefs.Add(new UserProjectXref { UserId = appUser.Id, ProjectId = up, }); } if (result.Succeeded) { foreach (var req in user.FileRepositories) { if (req.FileName != null) { string ModuleName = "Users"; var now = DateTime.Now; var yearName = now.ToString("yyyy"); var monthName = now.Month.ToString("d2"); var dayName = now.ToString("dd"); FileUploadService repo = new FileUploadService(); string FolderLocation = _config.Value.FileRepositoryFolder; string ServerRootPath = _config.Value.ServerRootPath; string Location = ServerRootPath + @"\" + FolderLocation + @"\" + yearName + @"\" + monthName + @"\" + dayName + @"\" + ModuleName; byte[] FileBytes = Convert.FromBase64String(req.FileName); req.FileName = repo.UploadFile(FileBytes, req.FileExtention, Location); req.FileLocation = Path.Combine(yearName, monthName, dayName, ModuleName); FileRepository file = new FileRepository(); { file.UserId = appUser.Id; file.FileName = req.FileName; file.FileLocation = req.FileLocation; file.FileExtention = req.FileExtention; file.DocumentType = req.DocumentTypeId; file.CreatedBy = req.CreatedBy; file.CreatedDate = DateTime.Now; file.UpdatedBy = req.UpdatedBy; file.UpdatedDate = DateTime.Now; } _appcontext.FileRepositories.Add(file); } } _appcontext.SaveChanges(); await SendVerificationEmail(appUser); UserViewModel userVM = await GetUserViewModelHelper(appUser.Id); return(CreatedAtAction(GetUserByIdActionName, new { id = userVM.Id }, userVM)); } AddError(result.Errors); } return(BadRequest(ModelState)); }
public ValueDataResponse <Project> UpdateProject(UpsertProject project) { ValueDataResponse <Project> response = new ValueDataResponse <Project>(); try { var projectsExists = _appContext.Projects.Where(x => x.Id != project.Id && x.ProjectReference == project.ProjectReference).FirstOrDefault(); if (projectsExists == null) { Project pro = _mapper.Map <Project>(project); var result = _appContext.Projects.Where(x => x.Id == project.Id).FirstOrDefault(); var projectList = _appContext.LookUpProjectXrefs.Where(x => x.ProjectId == project.Id).ToList(); _appContext.LookUpProjectXrefs.RemoveRange(projectList); _appContext.SaveChanges(); foreach (var sId in project.StoreIds) { _appContext.LookUpProjectXrefs.Add(new LookUpProjectXref { StoreId = sId, ProjectId = pro.Id }); } if (result != null) { result.SiteId = project.SiteId; result.ProjectReference = project.ProjectReference; result.Name1 = project.Name1; result.Name2 = project.Name2; result.ProjectDetails = project.ProjectDetails; result.IsActive = project.IsActive; result.CreatedBy = project.CreatedBy; result.CreatedDate = project.CreatedDate; result.UpdatedBy = project.UpdatedBy; result.UpdatedDate = project.UpdatedDate; foreach (var req in project.ProjectRepositories) { if (req.FileName != null) { string ModuleName = "Project"; var now = DateTime.Now; var yearName = now.ToString("yyyy"); var monthName = now.Month.ToString("d2"); var dayName = now.ToString("dd"); FileUploadService repo = new FileUploadService(); string FolderLocation = "FileRepository"; string ServerRootPath = _config.Value.ServerRootPath; string Location = ServerRootPath + @"\" + FolderLocation + @"\" + yearName + @"\" + monthName + @"\" + dayName + @"\" + ModuleName; byte[] FileBytes = Convert.FromBase64String(req.FileName); req.FileName = repo.UploadFile(FileBytes, req.FileExtention, Location); req.FileLocation = Path.Combine(yearName, monthName, dayName, ModuleName); ProjectRepository pros = new ProjectRepository(); { pros.ProjectId = pro.Id; pros.FileName = req.FileName; pros.FileLocation = req.FileLocation; pros.FileExtention = req.FileExtention; pros.DocumentType = req.DocumentTypeId; pros.CreatedBy = req.CreatedBy; pros.CreatedDate = DateTime.Now; pros.UpdatedBy = req.UpdatedBy; pros.UpdatedDate = DateTime.Now; } _appContext.ProjectRepositories.Add(pros); } } _appContext.SaveChanges(); if (pro != null) { response.Result = pro; response.IsSuccess = true; response.AffectedRecords = 1; response.EndUserMessage = "Project Updated Successfully"; } else { response.IsSuccess = true; response.AffectedRecords = 0; response.EndUserMessage = "Project Update Failed"; } } } else { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = "Project Reference is Already Exists"; } } catch (Exception ex) { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = ex.InnerException == null ? ex.Message : ex.InnerException.Message; response.Exception = ex; } return(response); }
public async Task <IActionResult> UpdateUsers(string id, [FromBody] UserFileViewModel user) { ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id); string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null; var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AccountManagementOperations.Update); var assignRolePolicy = _authorizationService.AuthorizeAsync(this.User, (user.Roles, currentRoles), Authorization.Policies.AssignAllowedRolesPolicy); if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded)) { return(new ChallengeResult()); } if (ModelState.IsValid) { if (user == null) { return(BadRequest($"{nameof(user)} cannot be null")); } if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id) { return(BadRequest("Conflicting user id in parameter and model data")); } if (appUser == null) { return(NotFound(id)); } bool isPasswordChanged = !string.IsNullOrWhiteSpace(user.NewPassword); bool isUserNameChanged = !appUser.UserName.Equals(user.UserName, StringComparison.OrdinalIgnoreCase); bool isConfirmedEmailChanged = !appUser.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase) && appUser.EmailConfirmed; if (Utilities.GetUserId(this.User) == id) { if (string.IsNullOrWhiteSpace(user.CurrentPassword)) { if (isPasswordChanged) { AddError("Current password is required when changing your own password", "Password"); } if (isUserNameChanged) { AddError("Current password is required when changing your own username", "Username"); } if (isConfirmedEmailChanged) { AddError("Current password is required when changing your own email address", "Email"); } } else if (isPasswordChanged || isUserNameChanged || isConfirmedEmailChanged) { if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword)) { AddError("The username/password couple is invalid."); } } } if (ModelState.IsValid) { _mapper.Map <UserFileViewModel, ApplicationUser>(user, appUser); appUser.EmailConfirmed = isConfirmedEmailChanged ? false : appUser.EmailConfirmed; var result = await _accountManager.UpdateUserAsync(appUser, user.Roles); var projectList = _appcontext.UserProjectXrefs.Where(x => x.UserId == appUser.Id).ToList(); _appcontext.UserProjectXrefs.RemoveRange(projectList); _appcontext.SaveChanges(); foreach (var up in user.ProjectIds) { _appcontext.UserProjectXrefs.Add(new UserProjectXref { UserId = appUser.Id, ProjectId = up, }); } if (result.Succeeded) { foreach (var req in user.FileRepositories) { if (req.FileName != null) { string ModuleName = "Users"; var now = DateTime.Now; var yearName = now.ToString("yyyy"); var monthName = now.Month.ToString("d2"); var dayName = now.ToString("dd"); FileUploadService repo = new FileUploadService(); // string FolderLocation = _config.Value.FileRepositoryFolder; string FolderLocation = "FileRepository"; string ServerRootPath = _config.Value.ServerRootPath; string Location = ServerRootPath + @"\" + FolderLocation + @"\" + yearName + @"\" + monthName + @"\" + dayName + @"\" + ModuleName; byte[] FileBytes = Convert.FromBase64String(req.FileName); req.FileName = repo.UploadFile(FileBytes, req.FileExtention, Location); req.FileLocation = Path.Combine(yearName, monthName, dayName, ModuleName); FileRepository file = new FileRepository(); { file.UserId = appUser.Id; file.FileName = req.FileName; file.FileLocation = req.FileLocation; file.FileExtention = req.FileExtention; file.DocumentType = req.DocumentTypeId; file.CreatedBy = req.CreatedBy; file.CreatedDate = DateTime.Now; file.UpdatedBy = req.UpdatedBy; file.UpdatedDate = DateTime.Now; } _appcontext.FileRepositories.Add(file); } } _appcontext.SaveChanges(); if (isConfirmedEmailChanged) { await SendVerificationEmail(appUser); } if (isPasswordChanged) { if (!string.IsNullOrWhiteSpace(user.CurrentPassword)) { result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword); } else { result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword); } } if (result.Succeeded) { return(NoContent()); } } AddError(result.Errors); } } return(BadRequest(ModelState)); }
public ValueDataResponse <AssetLocation> UpdateAssetLocation(UpsertAssetLocation asset) { ValueDataResponse <AssetLocation> response = new ValueDataResponse <AssetLocation>(); try { AssetLocation assetInfo = _mapper.Map <AssetLocation>(asset); var assetExists = _appContext.AssetLocations.Where(x => x.Id != asset.Id && x.AssetRef == asset.AssetRef).FirstOrDefault(); if (assetExists == null) { var result = _appContext.AssetLocations.Where(x => x.Id == asset.Id).FirstOrDefault(); if (result != null) { //result.SiteId = asset.SiteId; //result.ProjectId = asset.ProjectId; result.LocationId = asset.LocationId; result.AstGroupId = asset.AstGroupId; result.AstTradeId = asset.AstTradeId; result.Name1 = asset.Name1; result.Name2 = asset.Name2; result.AssetRef = asset.AssetRef; result.AstCounter = asset.AstCounter; result.AstFixedDate = asset.AstFixedDate; result.AssetSize = asset.AssetSize; result.AssetMake = asset.AssetMake; result.AssetModel = asset.AssetModel; result.AssetType = asset.AssetType; result.AssetCapacity = asset.AssetCapacity; result.IsActive = asset.IsActive; result.CreatedBy = asset.CreatedBy; result.CreatedDate = asset.CreatedDate; result.UpdatedBy = asset.UpdatedBy; result.UpdatedDate = asset.UpdatedDate; result.DaysApplicable = asset.DaysApplicable; foreach (var req in asset.AssetRepositories) { if (req.FileName != null) { string ModuleName = "Assets"; var now = DateTime.Now; var yearName = now.ToString("yyyy"); var monthName = now.Month.ToString("d2"); var dayName = now.ToString("dd"); FileUploadService repo = new FileUploadService(); string FolderLocation = "FileRepository"; string ServerRootPath = _config.Value.ServerRootPath; string Location = ServerRootPath + @"\" + FolderLocation + @"\" + yearName + @"\" + monthName + @"\" + dayName + @"\" + ModuleName; byte[] FileBytes = Convert.FromBase64String(req.FileName); req.FileName = repo.UploadFile(FileBytes, req.FileExtention, Location); req.FileLocation = Path.Combine(yearName, monthName, dayName, ModuleName); AssetFileRepository pros = new AssetFileRepository(); { pros.AssetId = assetInfo.Id; pros.FileName = req.FileName; pros.FileLocation = req.FileLocation; pros.FileExtention = req.FileExtention; pros.DocumentType = req.DocumentTypeId; pros.CreatedBy = req.CreatedBy; pros.CreatedDate = DateTime.Now; pros.UpdatedBy = req.UpdatedBy; pros.UpdatedDate = DateTime.Now; } _appContext.AssetFileRepositories.Add(pros); } } _appContext.SaveChanges(); response.Result = result; response.IsSuccess = true; response.AffectedRecords = 1; response.EndUserMessage = "Asset Updated Successfully"; } else { response.IsSuccess = true; response.AffectedRecords = 0; response.EndUserMessage = "Asset Updation Failed"; } } else { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = "Asset Reference Already Exists"; } } catch (Exception ex) { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = ex.InnerException == null ? ex.Message : ex.InnerException.Message; response.Exception = ex; } return(response); }
public ValueDataResponse <string> InsertPurchaseOrder(UpsertPurchaseOrder purchages) { ValueDataResponse <string> response = new ValueDataResponse <string>(); byte[] byteArray = null; var FileRepoBaseUrl = _config.Value.FileRepositoryUrl; try { var purchaseExists = _appContext.PurchageOrders.Where(x => x.PurchaseReference == purchages.PurchaseReference).FirstOrDefault(); if (purchaseExists == null) { PurchageOrder pro = _mapper.Map <PurchageOrder>(purchages); var result = _appContext.PurchageOrders.Add(pro); _appContext.SaveChanges(); foreach (var it in purchages.PurchaseItems) { _appContext.PurchageItemXrefs.Add(new PurchageItemXref { ItemId = it.ItemId, PurchageId = pro.Id, Quantity = it.Quantity, ExpectdCost = it.ExpectdCost, Comments = it.Comments }); } _appContext.SaveChanges(); var supplier = _appContext.Suppliers.Where(x => x.Id == pro.SupplierId).FirstOrDefault(); var project = _appContext.Projects.Where(x => x.Id == pro.ProjectId).FirstOrDefault(); var store = _appContext.LookUps.Where(x => x.Id == pro.StoreId).FirstOrDefault(); var items = (from pi in _appContext.PurchageItemXrefs join i in _appContext.Items on pi.ItemId equals i.Id join p in _appContext.PurchageOrders on pi.PurchageId equals p.Id select new GetItemsResponse { Id = pi.Id, PurchaseId = pi.PurchageId, PurchaseReference = p.PurchaseReference, ItemReference = i.ItemReference, ItemId = pi.ItemId, ItemName = i.Name1, Quantity = pi.Quantity, Comments = pi.Comments, ExpectedCost = pi.ExpectdCost, }).Where(x => x.PurchaseId == pro.Id).ToList(); DateTime Date = pro.ArrivingDate; // string message = EmailTemplates.GetPurchaseOrder(pro.PurchaseReference, pro.ArrivingDate, project.Name1, supplier.Name1, supplier.Address, store.Name1, pro.BillingAddress, pro.ShippingAddress, items, null); // string message = EmailTemplates.GetPurchaseOrder(pro.PurchaseReference, pro.ArrivingDate, project.Name1, supplier.Name1, supplier.Address, store.Name1, pro.BillingAddress, pro.ShippingAddress, items.ItemName, items.Quantity, items.ExpectedCost, items.Comments, null); byteArray = GeneratePurchaseOrderPdf(pro, supplier, items, project, store); if (byteArray != null) { string ModuleName = "PurchaseOrder"; var now = DateTime.Now; var yearName = now.ToString("yyyy"); var monthName = now.Month.ToString("d2"); var dayName = now.ToString("dd"); FileUploadService repo = new FileUploadService(); string FolderLocation = "FileRepository"; string ServerRootPath = _config.Value.ServerRootPath; string Location = ServerRootPath + @"\" + FolderLocation + @"\" + yearName + @"\" + monthName + @"\" + dayName + @"\" + ModuleName; pro.FileName = repo.UploadFile(byteArray, pro.FileExtention, Location); pro.FileLocation = Path.Combine(yearName, monthName, dayName, ModuleName); _appContext.SaveChanges(); //var converter = new HtmlConverter(); //var html = message; //Byte[] bytes = converter.FromHtmlString(html); //string base64String = Convert.ToBase64String(bytes, 0, bytes.Length); //string ImageUrl = "data:image/png;base64," + base64String; //byte[] FileBytes = Convert.FromBase64String(base64String); //pro.FileName = repo.UploadFile(FileBytes, pro.FileExtention, Location); //pro.FileLocation = Path.Combine(yearName, monthName, dayName, ModuleName); //_appContext.SaveChanges(); } if (pro != null) { response.Result = string.Format("{0}/{1}/{2}{3}", FileRepoBaseUrl, pro.FileLocation, pro.FileName, pro.FileExtention); response.IsSuccess = true; response.AffectedRecords = 1; response.EndUserMessage = "Purchage Order Added Successfully"; } else { response.IsSuccess = true; response.AffectedRecords = 0; response.EndUserMessage = "Purchage Order Added Failed"; } } else { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = "Purchage Order Reference Already Exists"; } } catch (Exception ex) { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = ex.InnerException == null ? ex.Message : ex.InnerException.Message; response.Exception = ex; } return(response); }
public void ProcessRequest(HttpContext context) { if (context.Session["FileRequests"] != null && context.Request.HttpMethod.ToUpper() == HttpMethods.GET) { context.Session["FileRequests"] = null; } if (context.Request.HttpMethod.ToUpper() == HttpMethods.POST && context.Session["FileRequests"] == null && context.Request.Files != null && context.Request.Files.Count > 0) { var serializer = new JavaScriptSerializer(); List <FileUploadInformation> lstFiles = serializer.Deserialize <List <FileUploadInformation> >(Convert.ToString(context.Request.Form["FileLists"])); foreach (var f in lstFiles) { f.LoopCounter = getLoopCounter(f.FileSize); f.CurrentLoopCount = f.LoopCounter; f.FileId = Guid.NewGuid(); f.IsUploaded = false; } context.Session["FileRequests"] = lstFiles; } if (context.Request.HttpMethod.ToUpper() == HttpMethods.GET) { List <FileResponse> FileResponseList = new List <FileResponse>(); string[] FileNames = null; //In this POC we have not used GET requests if (FileNames != null) { foreach (string FileName in FileNames) { FileResponseList.Add(CreateFileResponse(FileName, new FileInfo(FileName).Length, String.Empty, context)); } } SerializeUploaderResponse(FileResponseList, context); } else if (context.Request.HttpMethod.ToUpper() == HttpMethods.POST) { List <FileResponse> FileResponseList = new List <FileResponse>(); for (int FileIndex = 0; FileIndex < context.Request.Files.Count; FileIndex++) { HttpPostedFile File = context.Request.Files[FileIndex]; long fileLength = 0; string tt = string.Empty; string ErrorMessage = String.Empty; for (int Attempts = 0; Attempts < ATTEMPTS_TO_WRITE; Attempts++) { ErrorMessage = String.Empty; try { List <FileUploadInformation> lstFiles = (List <FileUploadInformation>)context.Session["FileRequests"]; for (int i = 0; i < lstFiles.Count; i++) { if (lstFiles[i].FileName.Equals(File.FileName)) { lstFiles[i] = FileUploadService.UploadFile(lstFiles[i], File); fileLength = lstFiles[i].FileSize; break; } } context.Session["FileRequests"] = lstFiles; } catch (Exception exception) { ErrorMessage = exception.Message; System.Threading.Thread.Sleep(ATTEMPT_WAIT); continue; } break; } FileResponseList.Add(CreateFileResponse(File.FileName, fileLength, ErrorMessage, context)); } SerializeUploaderResponse(FileResponseList, context); } else if (context.Request.HttpMethod.ToUpper() == HttpMethods.DELETE) { bool SuccessfullyDeleted = true; try { //In this POC DELETE call has not been implemented and not used anywhere } catch { SuccessfullyDeleted = false; } context.Response.Write(String.Format("{{\"{0}\":{1}}}", "file", SuccessfullyDeleted.ToString().ToLower())); } else { context.Response.StatusCode = 405; context.Response.StatusDescription = "Method not allowed"; context.Response.End(); return; } context.Response.End(); }
public ValueDataResponse <Supplier> AddSupplierDetials(Supplier suppliers) { ValueDataResponse <Supplier> response = new ValueDataResponse <Supplier>(); try { var suppliersExists = _appContext.Suppliers.Where(x => x.SupplierReference == suppliers.SupplierReference).FirstOrDefault(); if (suppliersExists == null) { var result = _appContext.Suppliers.Add(suppliers); if (suppliers.FileName != null) { string ModuleName = "Supplier"; var now = DateTime.Now; var yearName = now.ToString("yyyy"); var monthName = now.Month.ToString("d2"); var dayName = now.ToString("dd"); FileUploadService repo = new FileUploadService(); //string FolderLocation = _config.Value.FileRepositoryFolder; string FolderLocation = "FileRepository"; string ServerRootPath = _config.Value.ServerRootPath; string Location = ServerRootPath + @"\" + FolderLocation + @"\" + yearName + @"\" + monthName + @"\" + dayName + @"\" + ModuleName; byte[] FileBytes = Convert.FromBase64String(suppliers.FileName); suppliers.FileName = repo.UploadFile(FileBytes, suppliers.FileExtention, Location); suppliers.FileLocation = Path.Combine(yearName, monthName, dayName, ModuleName); } _appContext.SaveChanges(); if (result != null) { response.Result = suppliers; response.IsSuccess = true; response.AffectedRecords = 1; response.EndUserMessage = "Supplier Added Successfully"; } else { response.IsSuccess = true; response.AffectedRecords = 0; response.EndUserMessage = "Supplier Added Failed"; } } else { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = "Supplier Reference Already Exists"; } } catch (Exception ex) { response.IsSuccess = false; response.AffectedRecords = 0; response.EndUserMessage = ex.InnerException == null ? ex.Message : ex.InnerException.Message; response.Exception = ex; } return(response); }