private void OnChangedDirectory(object sender, FileSystemEventArgs e) { var fileName = e.FullPath; var userId = _dbContext.Users.FirstOrDefault(s => s.NormalizedUserName == "INTERNAL").Id; ILogger _logger = _loggerFactory.CreateLogger("Directory observer"); string error = ""; // filter file types if (Regex.IsMatch(fileName, @"\.xml|\.xlsx", RegexOptions.IgnoreCase)) { _logger.LogWarning($"Finded new file for inport: {fileName}"); try { if (fileName.ToLower().EndsWith(".xml")) { error = ImportFile.ImportXml(fileName, (new FileInfo(fileName)).Name, _dbContext, _logger, Configuration.GetSection("AppConfigurations").GetValue <string>("ImportedExcelArchive", ""), userId, null); } if (fileName.ToLower().EndsWith(".xlsx")) { error = ImportFile.ImportExcel(fileName, (new FileInfo(fileName)).Name, _dbContext, _logger, Configuration.GetSection("AppConfigurations").GetValue <string>("ImportedExcelArchive", ""), userId, null); } } catch (Exception ex) { _logger.LogError($"Import {fileName} failed. {ex.Message}. {ex.StackTrace}"); } } }
protected void btnImportFile_Click(object sender, EventArgs e) { try { string file = hdnFilePath.Value; if (!System.IO.File.Exists(Server.MapPath(string.Format("/Uploads/{0}", file)))) { throw new Exception(Language.GetString("FileDoesNotExist")); } string extension = file.Substring(file.LastIndexOf('.')).TrimStart('.'); bool firstRowHasColumnNames = chbHeaderRow.Checked; DataTable dtb = new DataTable(); switch (extension.ToLower()) { case "csv": dtb = ImportFile.ImportCSV(Server.MapPath(string.Format("/Uploads/{0}", file)), firstRowHasColumnNames, 5); break; case "xls": case "xlsx": dtb = ImportFile.ImportExcel(Server.MapPath(string.Format("/Uploads/{0}", file)), firstRowHasColumnNames, 5); break; } gridFile.DataSource = dtb; gridFile.DataBind(); } catch (Exception ex) { ClientSideScript = "saveResult('Error','" + ex.Message + "');"; } }
async public Task <IActionResult> TestImport() { var user = await _userManager.FindByNameAsync(User.Identity.Name); string error = ImportFile.ImportExcel(@"c:\temp\a1.xlsx", _db, _logger, user.Id); return(Json(new { error = error })); }
//#region InsertMethod //#endregion //#region UpdateMethod //#endregion //#region SelectMethod //public static DataTable GetCountNumberOfOperatorsForSendSmsFormat(Guid smsFormatGuid, string groupsGuid) //{ // Business.PhoneNumber phoneNumberController = new Business.PhoneNumber(); // return phoneNumberController.GetCountNumberOfOperatorsForSendSmsFormat(smsFormatGuid, groupsGuid); //} public static Dictionary <string, string> GetFileNumberInfo(string path, List <string> lstNumbers) { int correctNumber = 0; int duplicateNumber = 0; Dictionary <string, string> fileInfo = new Dictionary <string, string>(); try { if (!string.IsNullOrEmpty(path)) { DataTable dtb = new DataTable(); string fileExtention = path.Substring(path.LastIndexOf('.')); switch (fileExtention.Trim('.').ToLower()) { case "csv": dtb = ImportFile.ImportCSV(path, false); break; case "xls": case "xlsx": dtb = ImportFile.ImportExcel(path, false); break; } foreach (DataRow row in dtb.Rows) { if (Helper.IsCellPhone(row[0].ToString()) > 0) { correctNumber++; lstNumbers.Add(row[0].ToString()); } } duplicateNumber = dtb.Rows.Count - lstNumbers.GroupBy(number => number).Count(); fileInfo.Add("TotalNumberCount", dtb.Rows.Count.ToString()); fileInfo.Add("CorrectNumberCount", correctNumber.ToString()); fileInfo.Add("DuplicateNumberCount", duplicateNumber.ToString()); } return(fileInfo); } catch (Exception ex) { throw ex; } }
async public Task <IActionResult> Upload(List <IFormFile> files) { string error = ""; try { // full path to file in temp location var filePath = Path.GetTempFileName(); var user = await _userManager.FindByNameAsync(User.Identity.Name); foreach (var formFile in files) { if (formFile.Length > 0) { var stream = new FileStream(filePath, FileMode.Create); await formFile.CopyToAsync(stream); stream.Close(); if (formFile.FileName.ToLower().EndsWith(".xml")) { error = ImportFile.ImportXml(filePath, formFile.FileName, _db, _logger, _appConfig.Value.ImportedExcelArchive, user.Id); } else if (formFile.FileName.ToLower().EndsWith(".xlsx")) { error = ImportFile.ImportExcel(filePath, formFile.FileName, _db, _logger, _appConfig.Value.ImportedExcelArchive, user.Id); } else { error = "You can upoad only *.xml or *.xlsx files!!!"; } } } } catch (Exception ex) { _logger.LogError(Utils.GetFullError(ex)); error = "Internal server error"; } ViewBag.Error = error; ViewBag.PortletTitle = "Upload file result"; return(View()); }
protected void btnSave_Click(object sender, EventArgs e) { Common.PhoneNumber phoneNumber; List <Common.PhoneNumber> lstNumbers = new List <Common.PhoneNumber>(); string fieldId; string saveReport = string.Empty; try { string file = hdnFilePath.Value; if (!System.IO.File.Exists(Server.MapPath(string.Format("/Uploads/{0}", file)))) { throw new Exception(Language.GetString("FileDoesNotExist")); } string extension = file.Substring(file.LastIndexOf('.')).TrimStart('.'); bool firstRowHasColumnNames = chbHeaderRow.Checked; DataTable dtb = new DataTable(); switch (extension.ToLower()) { case "csv": dtb = ImportFile.ImportCSV(Server.MapPath(string.Format("/Uploads/{0}", file)), firstRowHasColumnNames); break; case "xls": case "xlsx": dtb = ImportFile.ImportExcel(Server.MapPath(string.Format("/Uploads/{0}", file)), firstRowHasColumnNames); break; } foreach (DataRow row in dtb.Rows) { phoneNumber = new Common.PhoneNumber(); phoneNumber.PhoneNumberGuid = Guid.NewGuid(); phoneNumber.PhoneBookGuid = PhoneBookGuid; phoneNumber.CreateDate = DateTime.Now; phoneNumber.FirstName = !string.IsNullOrEmpty(txtFirstName.Text) ? row[Helper.GetInt(txtFirstName.Text.Trim()) - 1].ToString() : string.Empty; phoneNumber.LastName = !string.IsNullOrEmpty(txtLastName.Text) ? row[Helper.GetInt(txtLastName.Text.Trim()) - 1].ToString() : string.Empty; if (!string.IsNullOrEmpty(txtBirthDate.Text)) { phoneNumber.BirthDate = DateManager.GetChristianDateForDB(row[Helper.GetInt(txtBirthDate.Text.Trim()) - 1].ToString()); } if (!string.IsNullOrEmpty(txtSex.Text)) { phoneNumber.Sex = GetSex(row[Helper.GetInt(txtSex.Text.Trim()) - 1].ToString()); } string mobile = !string.IsNullOrEmpty(txtCellPhone.Text) ? Helper.GetLocalMobileNumber(row[Helper.GetInt(txtCellPhone.Text.Trim()) - 1].ToString()) : string.Empty; string email = !string.IsNullOrEmpty(txtEmail.Text) ? row[Helper.GetInt(txtEmail.Text.Trim()) - 1].ToString() : string.Empty; if (!Helper.CheckDataConditions(email).IsEmail) { email = string.Empty; } //if (!Helper.CheckingCellPhone(ref mobile) && !Helper.CheckDataConditions(email).IsEmail) // continue; phoneNumber.Email = email; phoneNumber.CellPhone = mobile; phoneNumber.Job = !string.IsNullOrEmpty(txtJob.Text) ? row[Helper.GetInt(txtJob.Text.Trim()) - 1].ToString() : string.Empty; phoneNumber.Telephone = !string.IsNullOrEmpty(txtTelephone.Text) ? row[Helper.GetInt(txtTelephone.Text.Trim()) - 1].ToString() : string.Empty; phoneNumber.FaxNumber = !string.IsNullOrEmpty(txtFaxNumber.Text) ? row[Helper.GetInt(txtFaxNumber.Text.Trim()) - 1].ToString() : string.Empty; phoneNumber.Address = !string.IsNullOrEmpty(txtAddress.Text) ? row[Helper.GetInt(txtAddress.Text.Trim()) - 1].ToString() : string.Empty; fieldId = string.Empty; for (int customFieldCounter = 1; customFieldCounter <= 20; customFieldCounter++) { fieldId = "Field" + customFieldCounter.ToString(); TextBox customField = pnlUserField.FindControl(fieldId) as TextBox; if (customField != null && !string.IsNullOrEmpty(customField.Text)) { SetCustomFieldValue(phoneNumber, customFieldCounter, row[Helper.GetInt(customField.Text.Trim()) - 1].ToString(), (UserFieldTypes)Helper.GetInt(customField.Attributes["FieldType"])); } } lstNumbers.Add(phoneNumber); } if (!Facade.PhoneNumber.InsertBulkNumbers(lstNumbers, UserGuid)) { throw new Exception(Language.GetString("ErrorRecord")); } ClientSideScript = "saveResult('OK','" + Language.GetString("InsertRecord") + "');"; hdnFilePath.Value = string.Empty; } catch (Exception ex) { ClientSideScript = "saveResult('Error','" + ex.Message + "');"; } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/json"; context.Response.Expires = -1; var columns = new List <Column>(); var info = new Info(); try { string[] validExtension = { ".xls", ".xlsx" }; string responseValue = string.Empty; HttpPostedFile postedFile = context.Request.Files["upload"]; string fileName = postedFile.FileName; string fileExtention = Path.GetExtension(fileName).ToLower(); if (!validExtension.Contains(fileExtention)) { throw new Exception(Language.GetString("InvalidFileExtension")); } string savePath = string.Empty; string uploadFolder = @"~\Uploads\P2P\"; string newDirectoryName = new Random().Next(100, 99999).ToString(); savePath = context.Server.MapPath(uploadFolder + newDirectoryName); while (Directory.Exists(savePath)) { newDirectoryName = new Random().Next(100, 999999).ToString(); savePath = context.Server.MapPath(uploadFolder + newDirectoryName); } Directory.CreateDirectory(savePath); if (!savePath.EndsWith("\\")) { savePath += "\\"; } postedFile.SaveAs(savePath + fileName); DataTable dtb = ImportFile.ImportExcel((savePath + fileName), true, 5); foreach (DataColumn dc in dtb.Columns) { if (dc.DataType.Name.ToLower() != "string") { throw new Exception(Language.GetString("TextFileExtension")); } var c = new Column(); c.index = dc.Ordinal + 1; c.name = dc.ColumnName; columns.Add(c); } info.FileName = fileName; info.Path = string.Format(@"{0}{1}\{2}", uploadFolder.Substring(1), newDirectoryName, fileName); info.lstFileColumn = columns; context.Response.Write(JsonConvert.SerializeObject(info)); context.Response.StatusCode = 200; } catch (Exception ex) { context.Response.Write(ex.Message); } }
protected void btnSave_Click(object sender, EventArgs e) { DataTable dtContents = new DataTable(); dtContents.Columns.Add("Text", typeof(string)); try { string uploadTarget = Server.MapPath(string.Format("~/RegularContents/")); List <string> lstValidExtention = new List <string>() { ".xls", ".xlsx", ".csv" }; if (!Directory.Exists(uploadTarget)) { Directory.CreateDirectory(uploadTarget); } if (!fileUpload.HasFile) { throw new Exception(Language.GetString("ErrorSelectFile")); } string fileExtention = Path.GetExtension(fileUpload.PostedFile.FileName).ToLower(); if (!lstValidExtention.Contains(fileExtention)) { throw new Exception((Language.GetString("InvalidFileExtension"))); } string fileName = Path.GetFileName(fileUpload.PostedFile.FileName); fileUpload.SaveAs(uploadTarget + fileName); bool firstRowHasColumnNames = true; List <DataRow> lstContents = new List <DataRow>(); switch (fileExtention.TrimStart('.').ToLower()) { case "csv": lstContents = ImportFile.ImportCSV(Server.MapPath(string.Format("/RegularContents/{0}", fileName)), firstRowHasColumnNames).AsEnumerable().ToList(); break; case "xls": case "xlsx": lstContents = ImportFile.ImportExcel(Server.MapPath(string.Format("/RegularContents/{0}", fileName)), firstRowHasColumnNames).AsEnumerable().ToList(); break; } lstContents.RemoveAll(cnt => string.IsNullOrEmpty(cnt[0].ToString())); foreach (DataRow row in lstContents) { dtContents.Rows.Add(row[0].ToString()); } if (!Facade.Content.InsertContents(RegularContentGuid, dtContents)) { throw new Exception(Language.GetString("ErrorRecord")); } Response.Redirect(string.Format("/PageLoader.aspx?c={0}&RegularContentGuid={1}", Helper.Encrypt((int)Arad.SMS.Gateway.Business.UserControls.UI_RegularContents_Content, Session), RegularContentGuid)); } catch (Exception ex) { ShowMessageBox(ex.Message, string.Empty, "danger"); } }
protected void btnSave_Click(object sender, EventArgs e) { try { Dictionary <Common.DeliveryStatus, List <string> > messageStatus = new Dictionary <Common.DeliveryStatus, List <string> >(); List <int> lstValidStatus = new List <int>() { 1, 2, 4, 10, 14 }; string uploadTarget = Server.MapPath(string.Format("~/Uploads/{0}/", Helper.GetHostOfDomain(Request.Url.Host))); List <string> lstValidExtention = new List <string>(); lstValidExtention.Add("xlsx"); lstValidExtention.Add("xls"); if (!Directory.Exists(uploadTarget)) { Directory.CreateDirectory(uploadTarget); } if (!fileUpload.HasFile) { throw new Exception((Language.GetString("ErrorSelectFile"))); } string fileExtention = Path.GetExtension(fileUpload.PostedFile.FileName).TrimStart('.'); if (!lstValidExtention.Contains(fileExtention)) { throw new Exception((Language.GetString("InvalidFileExtension"))); } string file = Path.GetFileName(fileUpload.PostedFile.FileName); fileUpload.SaveAs(uploadTarget + file); bool firstRowHasColumnNames = true; DataTable dtb = new DataTable(); switch (fileExtention.ToLower()) { case "csv": dtb = ImportFile.ImportCSV(Server.MapPath(string.Format("/Uploads/{0}", file)), firstRowHasColumnNames); break; case "xls": case "xlsx": dtb = ImportFile.ImportExcel(Server.MapPath(string.Format("/Uploads/{0}", file)), firstRowHasColumnNames); break; } int status; string mobile; foreach (DataRow row in dtb.Rows) { mobile = Helper.GetLocalMobileNumber(Helper.GetString(row[0])); status = Helper.GetInt(row[1]); if (!lstValidStatus.Contains(status)) { continue; } if (!messageStatus.ContainsKey((Common.DeliveryStatus)status)) { messageStatus.Add((Common.DeliveryStatus)status, new List <string>()); } if (!messageStatus[(Common.DeliveryStatus)status].Contains(mobile)) { messageStatus[(Common.DeliveryStatus)status].Add(mobile); } } if (messageStatus.Count > 0) { Facade.OutboxNumber.UpdateDeliveryStatus(OutboxGuid, messageStatus); } Response.Redirect(string.Format("/PageLoader.aspx?c={0}", Helper.Encrypt((int)Arad.SMS.Gateway.Business.UserControls.UI_SmsReports_UserOutbox, Session))); } catch (Exception ex) { ShowMessageBox(ex.Message, string.Empty, "danger"); } }