using AutoMapper; using HRM.DA; using HRM.UI.DTOs.Auth; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; using System.Threading.Tasks; using HRM.BO; using Microsoft.AspNetCore.Authorization; using System.Net.Http; using Newtonsoft.Json; using System.Net; using System.Net.Http.Headers; using System.Collections; using Microsoft.AspNetCore.StaticFiles; using Novacode; using static HRM.BO.RecJobTracking; //using Xceed.Words.NET; //using Novacode; namespace HRM.UI.Controllers { [ApiController] [Route("api/filemanager")] [Authorize] public class FileManagerController : ControllerBase { private ISystemConfigaration _sysConfig; private readonly IInternalRecruitmentService _internalRecruitmentService; private readonly ICandidateService _candidateService; private readonly ICVService _cvService; private readonly IErCVService _ercvService; private readonly IErAppliedApplicantService _erAppliedApplicantService; private readonly IDepartmentService _departmentService; private readonly IConfiguration _config; private readonly IRecJobTrackingService _recJobTrackingService; //private static string _filePath = @"ClientApp\Documents\"; //private static string _offerLetterfilePath = @"ClientApp\Documents\OfferLetter\"; private static string _filePath = @"Documents\"; private static string _offerLetterfilePath = @"Documents\OfferLetter\"; private static String[] units = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; private static String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; // private static string _filePath = @"Documents\"; // private static string _offerLetterfilePath = @"Documents\OfferLetter\"; public FileManagerController(ISystemConfigaration sysConfig, IInternalRecruitmentService internalRecruitmentService, ICandidateService candidateService, ICVService cvService, IDepartmentService departmentService, IErCVService ercvService, IErAppliedApplicantService erAppliedApplicantService, IRecJobTrackingService recJobTrackingService, IConfiguration config) { this._sysConfig = sysConfig; _internalRecruitmentService = internalRecruitmentService; _candidateService = candidateService; _cvService = cvService; _departmentService = departmentService; _ercvService = ercvService; _config = config; _erAppliedApplicantService = erAppliedApplicantService; _recJobTrackingService = recJobTrackingService; } [HttpPost("uploadConfigurationfile"), DisableRequestSizeLimit] [AllowAnonymous] public async Task uploadConfigurationfile() { try { var files = Request.Form.Files; var uploadedFileNames = new List(); string result = string.Empty; int uploadID = Convert.ToInt32(Request.Form["fileTypeid"]); long size = files.Sum(f => f.Length); foreach (var formFile in files) { List configurations = this._sysConfig.LoadXMLtoObject((EnumConfigurationType)uploadID, formFile.OpenReadStream()); this._sysConfig.Save(configurations, (EnumConfigurationType)uploadID); break; } return Ok(); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpGet] [Route("getSysConfiguration/{fileType}")] public IActionResult getSysConfiguration(EnumConfigurationType fileType) { try { return Ok(this._sysConfig.Get(fileType)); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpGet] [Route("getConfigXmlFile/{fileType}")] public IActionResult getConfigXmlFile(EnumConfigurationType fileType) { try { string stream = this._sysConfig.GetXMLFile(fileType); return Ok(stream); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpPost("uploadExcelfile")] [AllowAnonymous] public async Task uploadExcelfile() { try { var files = Request.Form.Files; List uploadedList = new List(); int i = 0; int cntSuccess = 0; var uploadedFileNames = new List(); string result = string.Empty; long size = files.Sum(f => f.Length); foreach (var formFile in files) { var fileSize = formFile.Length; var originalFile = formFile.FileName; var generatedFile = Guid.NewGuid().ToString().Replace("-", ""); var uploaderItem = new UploaderItems(); uploaderItem.OriginalFileName = originalFile; // uploaderItem.GeneratedFileName = generatedFile; //var supportedTypes = new[] { "jpg", "png", "jpeg", "pdf" }; var fileExt = System.IO.Path.GetExtension(originalFile).Substring(1); uploaderItem.GeneratedFileName = generatedFile + "." + fileExt; //if (supportedTypes.Contains(fileExt)) //{ // if (fileSize > (500 * 1024)) // { // result = "Maximum file size permitted is 500KB"; // throw new System.ArgumentException(result); // } //} var fileName = _filePath + uploaderItem.OriginalFileName; string fullPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, fileName); uploaderItem.Path = fullPath; try { if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } using (var stream = new FileStream(fullPath, FileMode.Create)) { formFile.CopyTo(stream); } uploadedFileNames.Add(formFile.FileName); uploadedList.Add(uploaderItem); cntSuccess++; } catch (Exception ex) { throw ex; } i++; } result = cntSuccess.ToString() + " files uploaded succesfully.
"; result += "
    "; foreach (var f in uploadedFileNames) { result += "
  • " + f + "
  • "; } result += "
"; return Ok(uploadedList); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpPost("removeExcelfile")] [AllowAnonymous] public async Task removeExcelfile() { try { var files = Request.Form.Files; List uploadedList = new List(); int i = 0; int cntSuccess = 0; var uploadedFileNames = new List(); string result = string.Empty; long size = files.Sum(f => f.Length); foreach (var formFile in files) { var fileSize = formFile.Length; var originalFile = formFile.FileName; var fileExt = System.IO.Path.GetExtension(originalFile).Substring(1); var fileName = _filePath + originalFile; string fullPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, fileName); try { if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } cntSuccess++; } catch (Exception ex) { throw ex; } i++; } result = cntSuccess.ToString() + " files downloaded succesfully.
"; result += "
    "; foreach (var f in uploadedFileNames) { result += "
  • " + f + "
  • "; } result += "
"; return Ok(uploadedList); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpPost("uploadFiles")] [AllowAnonymous] public async Task UploadFiles() { try { var files = Request.Form.Files; List uploadedList = new List(); int i = 0; int cntSuccess = 0; var uploadedFileNames = new List(); string result = string.Empty; long size = files.Sum(f => f.Length); foreach (var formFile in files) { var fileSize = formFile.Length; var originalFile = formFile.FileName; var uploaderItem = new UploaderItems(); uploaderItem.OriginalFileName = originalFile; var fileExt = System.IO.Path.GetExtension(originalFile).Substring(1); var fileName = _filePath + uploaderItem.OriginalFileName; string fullPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, fileName); uploaderItem.Path = fullPath; try { if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } using (var stream = new FileStream(fullPath, FileMode.Create)) { formFile.CopyTo(stream); } uploadedFileNames.Add(formFile.FileName); uploadedList.Add(uploaderItem); cntSuccess++; } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); // throw ex; } i++; } result = cntSuccess.ToString() + " files uploaded succesfully.
"; result += "
    "; foreach (var f in uploadedFileNames) { result += "
  • " + f + "
  • "; } result += "
"; return Ok(uploadedList); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpPost] [Route("get-word-file")] public async Task GetWordFile(dynamic data) { CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); List departments = new List(); departments = new DepartmentService().Get(EnumStatus.Regardless, (int)currentUser.PayrollTypeID); EnumAgreementLetterStatus lettertype = EnumAgreementLetterStatus.None; string contentType = ""; var newFilePath = ""; var existingFilePath = ""; var newfileName = ""; var fileName = ""; var originalFileName = ""; //var fileName = _offerLetterfilePath + "ContractualEmploymentAgreement.docx"; //var newfileName = _offerLetterfilePath + "ContractualEmploymentAgreementNew.docx"; //var existingFilePath = System.IO.Path.Combine(System.Environment.CurrentDirectory, fileName); //var newFilePath = System.IO.Path.Combine(System.Environment.CurrentDirectory, newfileName); string departmentName = ""; string parentDepartmentName = ""; string candidateAddress = ""; string candidateName = ""; string jobLocation = ""; string basicSalary = ""; string issueDate = ""; string joiningDate = ""; string fathersName = ""; string mothersName = ""; string gender = ""; string lineManagerDesignation = ""; string candidateDesignation = ""; string salaryInWords = ""; HttpResponseMessage response = null; ErApplicantDoc erApplicantDoc = null; try { if (data != null) { var tempdata = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); RecruitmentLetters item = new RecruitmentLetters(); item = (RecruitmentLetters)tempdata["data"].ToObject(); lettertype = (EnumAgreementLetterStatus)Convert.ToInt16(tempdata["letterType"].ToObject()); fileName = _offerLetterfilePath + (string)tempdata["existingFileName"].ToObject(); originalFileName = (string)tempdata["existingFileName"].ToObject(); newfileName = _offerLetterfilePath + (string)tempdata["newFileName"].ToObject(); existingFilePath = System.IO.Path.Combine(System.Environment.CurrentDirectory, fileName); newFilePath = System.IO.Path.Combine(System.Environment.CurrentDirectory, newfileName); if (item != null) { InternalRecruitment recruitment = _internalRecruitmentService.Get(item.RequisitionID); List candidates = new CandidateService().GetCanditates(item.RequisitionID); if (lettertype == EnumAgreementLetterStatus.IssueLetter) { if (recruitment.DepartmentId > 0) { var department = departments?.Find(x => x.ID == recruitment.DepartmentId); departmentName = department.Name; if(department.ParentID != null) parentDepartmentName = departments?.Find(x => x.ID == department.ParentID).Name; var candidate = candidates?.Find(x => x.ID == item.CandidateID); CV cv = _cvService.Get(candidate.CvID); candidateAddress = cv.PresentAddress; candidateName = cv.Name; jobLocation = item.JobLocation; basicSalary = String.Format("{0:0.##}", item.BasicSalary); salaryInWords = ConvertAmount(double.Parse(basicSalary)); issueDate = item.IssueOfferDate != null ? Convert.ToDateTime(item.IssueOfferDate).ToString("dd-MM-yy") : null; joiningDate = item.JoiningDate != null ? Convert.ToDateTime(item.JoiningDate).ToString("dd-MM-yy") : null; //for eecruitment ErCV ercv = _ercvService.Get((int)cv.ErCvID); if(ercv != null) { erApplicantDoc = new ErApplicantDoc(); erApplicantDoc.UserID = ercv.UserID; erApplicantDoc.DocType = EnumFileType.Word; erApplicantDoc.UpdatedBy = EnumActorType.Admin; erApplicantDoc.CreatedBy = currentUser.UserID; ErAppliedApplicant erAppliedApplicant = _erAppliedApplicantService.GetApplicantInfoByUserID(item.RequisitionID, ercv.UserID); erApplicantDoc.AppliedApplicantID = erAppliedApplicant.ID; erApplicantDoc.Remarks = "File"; erApplicantDoc.JobID = erAppliedApplicant.JobID; } _recJobTrackingService.UpdateActualDate(item.RequisitionID, item.JoiningDate); } } else if (lettertype == EnumAgreementLetterStatus.AcceptanceLetter) { var candidate = candidates?.Find(x => x.ID == item.CandidateID); CV cv = _cvService.Get(candidate.CvID); candidateAddress = cv.PresentAddress; candidateName = cv.Name; fathersName = item.FathersName; mothersName = item.MothersName; candidateDesignation = recruitment.DesignationName; if (cv.Gender == EnumGender.Male) { gender = "son"; } else if (cv.Gender == EnumGender.Female) { gender = "daughter"; } lineManagerDesignation = item.LineManagerDesignation; basicSalary = String.Format("{0:0.##}", item.BasicSalary); salaryInWords = ConvertAmount(double.Parse(basicSalary)); issueDate = item.IssueOfferDate != null ? Convert.ToDateTime(item.IssueOfferDate).ToString("dd-MM-yy") : null; joiningDate = item.JoiningDate != null ? Convert.ToDateTime(item.JoiningDate).ToString("dd-MM-yy") : null; } } } else { throw new Exception("No Data found"); } FileInfo ossInfo = null; string FindText = ""; string ReplaceText = ""; ossInfo = new FileInfo(newFilePath); if (ossInfo.Exists) { ossInfo.Delete(); } System.IO.File.Copy(existingFilePath, newFilePath, true); var table = new Dictionary(); //Hashtable table = new Hashtable(); //table.Clear(); if (lettertype == EnumAgreementLetterStatus.IssueLetter) { table.Add(TagOutputConstant.CandidateAddress, candidateAddress); table.Add(TagOutputConstant.CandidateName, candidateName); table.Add(TagOutputConstant.IssueDate, issueDate); table.Add(TagOutputConstant.BasicSalary, basicSalary); table.Add(TagOutputConstant.JobLocation, jobLocation); table.Add(TagOutputConstant.ParentDeptName, parentDepartmentName); table.Add(TagOutputConstant.DeptName, departmentName); table.Add(TagOutputConstant.JoiningDate, joiningDate); table.Add(TagOutputConstant.SalaryInWords, salaryInWords); } else if (lettertype == EnumAgreementLetterStatus.AcceptanceLetter) { table.Add(TagOutputConstant.CandidateAddress, candidateAddress); table.Add(TagOutputConstant.CandidateName, candidateName); table.Add(TagOutputConstant.FathersName, fathersName); table.Add(TagOutputConstant.MothersName, mothersName); table.Add(TagOutputConstant.LineManagerDesignation, lineManagerDesignation); table.Add(TagOutputConstant.IssueDate, issueDate== null ? "": issueDate); table.Add(TagOutputConstant.BasicSalary, basicSalary); table.Add(TagOutputConstant.JoiningDate, joiningDate == null ? "": joiningDate); table.Add(TagOutputConstant.Gender, gender); table.Add(TagOutputConstant.CandidateDesig, candidateDesignation == null ? "" : candidateDesignation); table.Add(TagOutputConstant.SalaryInWords, salaryInWords); } this.ReplaceWords(newFilePath, table); Stream memory = new MemoryStream(); byte[] buffer = new byte[16 * 1024]; contentType = GetFileType(newfileName); buffer = System.IO.File.ReadAllBytes(newFilePath); var name = newfileName; string connectionString = _config.GetSection("dbSettings").GetSection("SqlCommandConnection").Value; if(erApplicantDoc != null) { erApplicantDoc.FileData = buffer; erApplicantDoc.OriginalFileName = originalFileName; _erAppliedApplicantService.Save(erApplicantDoc, connectionString); } return File(buffer, contentType, name); } catch (Exception ex) { //response = new HttpResponseMessage //{ // StatusCode = HttpStatusCode.InternalServerError, // Content = new StringContent(ex.Message) //}; return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } // return response; } [HttpGet] [Route("GetAllChildrenByParentNode/{fileType}/{parentNode}")] public IActionResult GetAllChildrenByParentNode(EnumConfigurationType fileType, string parentNode) { try { return Ok(this._sysConfig.GetAllChildrenByParentNode(fileType, parentNode)); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpGet] [Route("GetConpanyInfo")] public IActionResult GetConpanyInfo() { try { return Ok(Convert.ToString(this._sysConfig.GetconfigValue(EnumConfigurationType.Logic, "system", "company"))); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpPost] [Route("get-file-type")] [AllowAnonymous] [IgnoreAntiforgeryToken] [ProducesResponseType(StatusCodes.Status200OK)] public string GetFileType(string originalFileName) { //var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); //string fileName = (string)item["fileName"].ToObject(); string fileName = originalFileName; string contentType; new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType); return contentType ?? "application/octet-stream"; } [HttpGet] [Route("GetLogicValue/{parent}/{child}")] public IActionResult GetLogicValue(string parent, string child) { try { return Ok(Convert.ToString(this._sysConfig.GetconfigValue(EnumConfigurationType.Logic, parent, child))); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } public void ReplaceWords(string destFileName, Dictionary tagValueHashTable) { object SaveChanges = true; // if (_wordapp == null) OpenWordApplication(); object Missing = System.Reflection.Missing.Value; try { object FileName = destFileName; object ReadOnly = false; object TrueBool = true; object FalseBool = false; object IsVisible = false; string FindText = ""; string ReplaceText = ""; DocX docTemp = DocX.Load(destFileName); var _Pair = (tagValueHashTable != null) ? tagValueHashTable : new Dictionary(); foreach (string sKey in _Pair.Keys) { FindText = sKey; ReplaceText = _Pair[sKey]; docTemp.ReplaceText(FindText, ReplaceText); } docTemp.Save(); } catch (Exception ex) { throw new Exception("Error: Could not read file from disk. Original error: " + ex.Message); } } public static String ConvertAmount(double amount) { try { Int64 amount_int = (Int64)amount; Int64 amount_dec = (Int64)Math.Round((amount - (double)(amount_int)) * 100); if (amount_dec == 0) { return ConvertAccurate(amount_int) + " Only."; } else { return ConvertAccurate(amount_int) + " Point " + ConvertAccurate(amount_dec) + " Only."; } } catch (Exception e) { // TODO: handle exception } return ""; } public static String ConvertAccurate(Int64 i) { if (i < 20) { return units[i]; } if (i < 100) { return tens[i / 10] + ((i % 10 > 0) ? " " + ConvertAccurate(i % 10) : ""); } if (i < 1000) { return units[i / 100] + " Hundred" + ((i % 100 > 0) ? " And " + ConvertAccurate(i % 100) : ""); } if (i < 100000) { return ConvertAccurate(i / 1000) + " Thousand " + ((i % 1000 > 0) ? " " + ConvertAccurate(i % 1000) : ""); } if (i < 10000000) { return ConvertAccurate(i / 100000) + " Lakh " + ((i % 100000 > 0) ? " " + ConvertAccurate(i % 100000) : ""); } if (i < 1000000000) { return ConvertAccurate(i / 10000000) + " Crore " + ((i % 10000000 > 0) ? " " + ConvertAccurate(i % 10000000) : ""); } return ConvertAccurate(i / 1000000000) + " Arab " + ((i % 1000000000 > 0) ? " " + ConvertAccurate(i % 1000000000) : ""); } } public class UploaderItems { public string OriginalFileName { get; set; } public string GeneratedFileName { get; set; } public string Path { get; set; } public bool IsNew { get; set; } public int UploaderModule { get { return 1; } } } }