public void saveMessage(Message msg) { IList <Message> msgToSave = new List <Message>(); msgToSave.Add(msg); FilesHandler.SaveMessages(msgToSave); }
private void HandleInspection(FileInfo file, Sensores sensor) { DateTime fecha = DateTime.Parse(sensor.last_date_saved); #region Lectura de las filas del archivo DataTable csv = null; try { controllerLog.debug("Leyendo: " + file.FullName); csv = FilesHandler.FileToTable(file.FullName, ','); } catch (Exception ex) { controllerLog.stack("No fue posible leer: " + file.FullName, this, ex); } #endregion if (csv != null) { if (csv.Rows.Count > 0) { int filas = 0; bool creado = true; foreach (DataRow Fila in csv.Rows) { humedad = Fila[0].ToString(); temperatura = Fila[1].ToString(); fecha_medicion = Convert.ToDateTime(Fila[4].ToString()); if (fecha_medicion > fecha) { filas++; creado = Mediciones.createMeasure(sensor.id_sensor, temperatura, humedad, fecha_medicion); if (!creado) { controllerLog.warning("La Fila con fecha " + fecha_medicion + " para sensor " + sensor.nombre + " NO se agregó a la BD"); } } else { //controllerLog.warning(file.FullName+"| la fila con fecha " + fecha_medicion + " NO se agregará a la BD"); } } if (filas > 0) { controllerLog.success("Registros Agregados: " + filas); } else { controllerLog.success("No se han registrado Nuevas Mediciones"); } //Actualizo la fecha de la última lectura de las mediciones controllerLog.info("---------------------------------------------"); controllerLog.info("Actualizando Ping de Sensor " + sensor.nombre); Sensores.UpdatePing(sensor.nombre, fecha_medicion); controllerLog.info("Ping Actualizado."); controllerLog.info("---------------------------------------------"); } } }
public void ProcessPendingServiceRequests(string templateFilePath) { try { string emailTemplateContent = FilesHandler.GetFileContent(templateFilePath); List <ServiceRequestDto> requests = requestService.GetAllEmailPendingRequests(); string emailClientIP = settingsService.GetSystemSettingValue("Email Proxy Server"); string ownerEmailID = settingsService.GetSystemSettingValue("Contractor Request Email Owner"); string bccEmailID = settingsService.GetSystemSettingValue("Contractor Request Email BCC Email IDs"); string outlookPwd = settingsService.GetSystemSettingValue("Owner's Outlook EMAIL Password"); string emailSubject = "New Contractor Request for Agilisium"; EmailHandler emailHandler = new EmailHandler(ownerEmailID, outlookPwd); foreach (var request in requests) { try { StringBuilder vendorEmail = new StringBuilder(emailTemplateContent); vendorEmail.Replace("__EMAIL_BODY__", request.EmailMessage); emailHandler.SendEmail(emailClientIP, request.VendorEmailID, emailSubject, vendorEmail.ToString(), bccEmailID); requestService.UpdateEmailSentStatus(request.ServiceRequestID); } catch (Exception) {} } } catch (Exception) { } }
/// <summary> /// Localiza las carpetas de InspectionResult del programa actual /// </summary> private void FindProgramFolders() { // Formateo la carpeta al tipo: "RVS-1234" y agrego al programa un comodin " * " string RVS_filter = panel.maquina.Replace("VT-RNS", "RVS"); // Se forza a obtener la inspeccion de inspectionResult en otra RVS if (RVS_filter.Equals("RVS-6112")) { RVS_filter = "RVS-6144"; } if (RVS_filter.Equals("RVS-6110")) { RVS_filter = "RVS6128"; } string InspectionPath = Directory.GetParent(rnsi.aoiConfig.inspectionCsvPath).Parent.FullName; string InspeccionResultFolder = Path.Combine(InspectionPath, RVS_filter, "InspectionResult"); if (panel.programa != null) { panel.rncInspectionProgramVersionName = SustractProgramFolderName(); panel.machine.LogBroadcast("debug", string.Format("+ Buscando carpetas de inspeccion para el programa: {0}", panel.rncInspectionProgramVersionName)); panel.rnsInspectionResultDirectory = FilesHandler.GetFolders(panel.rncInspectionProgramVersionName + "*" + "InspectionResult", InspeccionResultFolder).FirstOrDefault(); } else { panel.machine.LogBroadcast("warning", string.Format("+ No esta difinido el nombre del programa, no se pueden buscar las carpetas de inspeccion")); } }
public ActionResult AddPost(PostViewModel postViewModel) { var userId = User.Identity.GetUserId(); var path = FilesHandler.saveImage(postViewModel.picture, Server); if (postViewModel.picture == null || path != null) { PostViewModel.addPostFrom(userId, databaseEntities, path, postViewModel.content, postViewModel.albumID, postViewModel.group_id); } else { ModelState.AddModelError("imageError", "Something went wrong we were unable to save the photo"); } switch (postViewModel.appLocation) { case "Profile": return(RedirectToAction("ShowMyProfile", "Profile")); case "Newsfeed": return(RedirectToAction("Index", "NewsFeed")); case "Groups": return(RedirectToAction("Show", "Groups")); default: return(Index()); } }
public void retriveMessages(int number) { try { IList <IMessage> messages = Communication.Instance.GetTenMessages(this.url); List <Message> Nmessages = new List <Message>(); foreach (IMessage M in messages) { Message M2 = new Message(M); Nmessages.Add(M2); } foreach (Message mess in Nmessages.ToList()) { foreach (Message msg in this.messagesList.ToList()) { if (mess.Id.Equals(msg.Id)) { Nmessages.Remove(mess); } } } messagesList.AddRange(Nmessages); List <Message> SortedList = this.messagesList.OrderBy(o => o.Date).ToList(); this.messagesList = SortedList; FilesHandler.SaveMessages(this.messagesList); } catch (Exception e) { log.Error("error for reterive messeage", e); } log.Info("reterive messeages succesfully"); }
/// <summary> /// Update a computer by another one /// </summary> /// <param name="t">Computer to be replaced</param> /// <param name="u">Computer to replace</param> /// <returns>True if the computer is updated, false if not</returns> public static bool UpdateComputer(Computer t, Computer u) { try { for (int i = 0; i < computers.Count; i++) { if (computers[i] == t) { u.Date = t.Date; computers[i] = u; TextHandler textHandler = new TextHandler(); textHandler.SaveFile(u.Show(), "list_computers.txt"); FilesHandler <List <Computer> > fileHandler = new FilesHandler <List <Computer> >(); fileHandler.SaveFile(computers, "Computers.xml"); return(true); } } throw new ComputerException("Ha ocurrido un error al manipular la computadora"); } catch (ComputerException ex) { throw ex; } catch (Exception) { throw; } }
/// <summary> /// Update a computer by state /// </summary> /// <param name="t">Computer to be updated</param> /// <param name="state">State to put</param> /// <returns>True if the computer is updated, false if not</returns> public void UpdateState(Computer t, State state) { try { for (int i = 0; i < computers.Count; i++) { if (computers[i] == t) { computers[i].ComputerState = state; TextHandler textHandler = new TextHandler(); textHandler.SaveFile(t.Show(), "list_computers.txt"); FilesHandler <List <Computer> > fileHandler = new FilesHandler <List <Computer> >(); fileHandler.SaveFile(computers, "Computers.xml"); } } } catch (ComputerException ex) { throw ex; } catch (Exception) { throw new ComputerException("Error al manipular la computadora"); } }
public InspectionResult(RnsPanel panel, RnsInspection rnsi) { this.panel = panel; this.rnsi = rnsi; FindProgramFolders(); if (panel.rnsInspectionResultDirectory != null) { string filter = panel.maquina + "*" + panel.csvDateCreate.ToString("yyyyMMdd") + panel.csvDateCreate.ToString("HHmmss"); panel.rnsCurrentInspectionResultDirectory = FilesHandler.GetFolders(filter, panel.rnsInspectionResultDirectory.FullName).FirstOrDefault(); if (panel.rnsCurrentInspectionResultDirectory != null) { panel.machine.LogBroadcast("debug", string.Format("+ Ruta de InspectionResult localizada ({0}) | InspectionResult: {1}", panel.barcode, panel.rncInspectionProgramVersionName )); fileHeaders = ContentFileToObject(panel.rnsCurrentInspectionResultDirectory); located = true; } else { panel.machine.LogBroadcast("warning", string.Format("+ Ruta de InspectionResult no encontrada")); } } else { panel.machine.LogBroadcast("warning", string.Format("+ Ruta a InspectionResult no encontrada")); } }
//исполнение набора функций для получения и обработки данных //выполнять при изменении исходного набора данных private void GetData() { //исходный файл GeoJSON string mapPath = Server.MapPath("~/Map/geo.json"); //файл GeoJSON, записанный в переменную js string dataJSPath = Server.MapPath("~/Scripts/data.js"); //англоязычные названия регионов string regionEngNames = Server.MapPath("~/DataFiles/engRegions.data"); //сопоставление английских и русских названий регионов string regionRuNames = Server.MapPath("~/DataFiles/ruRegions.data"); //файл GeoJSON с русскими названиями регионов string ruMapPath = Server.MapPath("~/Map/geo_ru.json"); //CSV-файл данных string databasePath = Server.MapPath("~/Database/Database.csv"); //экселевский файл с показателями string xlsPath = Server.MapPath("~/DataFiles/Карта энергетики_02Апр2021.xlsx"); //получение английских имен регионов из исходного GeoJSON FilesHandler.GetEngRegions(mapPath, regionEngNames); //преобразовать англоязычные имена в русские FilesHandler.TranslateRegNames(regionRuNames, mapPath, ruMapPath); //наполнить файл данных названиями регионов FilesHandler.AddRegions(regionRuNames, databasePath); //парсинг Excel-файла с данными Parser.ParseData(xlsPath, databasePath); //внести показатели в файл GeoJSON FilesHandler.EditMapJSON(databasePath, ruMapPath); //создать data.js на основе GeoSJON FilesHandler.CreateGEOData(ruMapPath, dataJSPath); }
private async Task <ConcurrentBag <FileValue> > Calculate(ConcurrentBag <string> dirPaths) { return(await Task.Run(() => { try { fileReader = new FilesHandlerLittle(); fileReader.ProcessNotifier += Main_ProcessEventNotifier; fileReader.FileCompleteNotifier += Main_FileCompleteNotifier; var a = fileReader.CalculateParallel(dirPaths); return a.Result; } catch (Exception e) { if (e.InnerException is StopException) { throw e.InnerException; } throw e; } finally { fileReader.ProcessNotifier -= Main_ProcessEventNotifier; fileReader.FileCompleteNotifier -= Main_FileCompleteNotifier; fileReader = null; dirPaths = new ConcurrentBag <string>(); GC.Collect(); } })); }
/// <summary> /// Saves a user into a file /// </summary> /// <param name="user">User to save</param> /// <param name="fileName">File name</param> public void SaveFile(User user, string fileName) { try { FilesHandler <User> filesHandler = new FilesHandler <User>(); if (user is Receptionist) { filesHandler.SaveFile(user, "recepcionist.xml"); } else { if (user is Technician) { filesHandler.SaveFile(user, "technical.xml"); } else { throw new Exception("No se pudo guardar el usuario"); } } } catch (Exception ex) { throw ex; } }
//更新前备份文件 private void BackUpFiles() { var rootPath = GetAppRootPath(); _bkZipFilePath = rootPath + Guid.NewGuid().ToString() + ".zip"; FilesHandler.CompressFiles(_files, rootPath, _bkZipFilePath); }
internal void sendMessage(string message) { Message msg = loggedInUser.SendMessege(message, url); messagesList.Add(msg); FilesHandler.SaveMessages(this.messagesList); return; }
private void btnRunApp_Click(object sender, RoutedEventArgs e) { if (!string.IsNullOrEmpty(_bkZipFilePath) && File.Exists(_bkZipFilePath)) { FilesHandler.UnpackFiles(_bkZipFilePath, this.GetAppRootPath()); } ReStartMainApp(); }
public MonthData(int i_Year, int i_Month) { m_Year = i_Year; m_Month = i_Month; m_Summary = new Summary(this); m_AllDays = DayData.StringLstToDayDataLst(FilesHandler.GetFileLines(i_Year, i_Month)); subscribeToAllDaysEvents(); change_EventHandler(); }
public MonthData(FileInfo i_File) { m_Summary = new Summary(this); m_Year = FilesHandler.getFileYear(i_File.Name); m_Month = FilesHandler.getFileMonth(i_File.Name); m_AllDays = DayData.StringLstToDayDataLst(FilesHandler.GetFileLines(m_Year, m_Month)); subscribeToAllDaysEvents(); change_EventHandler(); }
private void StartInspection() { aoiLog.verbose("Localizando CSV de Inspeccion"); // Obtengo archivos CSV en InspectionFolder IOrderedEnumerable <FileInfo> csv = FilesHandler.GetFiles("*", aoiConfig.inspectionCsvPath); int totalCsv = csv.Count(); aoiWorker.SetProgressTotal(totalCsv); if (totalCsv > 0) { int file_count = 0; foreach (FileInfo file in csv) { file_count++; #region REDIS // Dato a enviar JObject json = new JObject(); json["mode"] = "runtime"; json["tipo"] = aoiConfig.machineType; json["current"] = file_count.ToString(); json["total"] = totalCsv.ToString(); // Enviar al canal Realtime.send(json.ToString()); #endregion aoiLog.info("---------------------------------------------"); aoiLog.info(" Procesando " + file_count + " / " + totalCsv); aoiLog.info("---------------------------------------------"); HandleInspection(file); aoiWorker.SetProgressWorking(file_count); } aoiLog.info("No hay mas CSV"); } else { #region REDIS // Dato a enviar JObject json = new JObject(); json["mode"] = "runtime"; json["tipo"] = aoiConfig.machineType; json["current"] = 0; json["total"] = 0; // Enviar al canal Realtime.send(json.ToString()); #endregion aoiLog.info("No se encontraron inspecciones."); } }
private void setYearsToggle() { List <string> years = FilesHandler.GetYears(); chooseYear.Items.Clear(); foreach (var hour in years) { chooseYear.Items.Add(hour); } }
public void GenerateManagementNotifications(string appTempDirectory, int reportingDay) { logger.Info("Reading system settings"); string emailClientIP = ProcessorHelper.GetSettingsValue(ProcessorHelper.EMAIL_PROXY_SERVER); string ownerEmailID = ProcessorHelper.GetSettingsValue(ProcessorHelper.CONTRACTOR_REQ_EMAIL_OWNER); string templateFilePath = ProcessorHelper.GetSettingsValue(ProcessorHelper.TEMPLATE_FOLDER_PATH) + "\\PODWiseEmployees.html"; string toEmailID = null; string outlookPwd = ProcessorHelper.GetSettingsValue(ProcessorHelper.EMAIL_OWNERS_PASSWORD); string emailSubject = "RMT Alert - Please Confirm, Employees Under your POD"; try { logger.Info("Deleting old files"); FilesHandler.RemoveAllFilesFromDirectory(appTempDirectory); } catch (Exception exp) { logger.Error(exp); } List <PracticeDto> pods = practiceRepository.GetAll().ToList(); logger.Info($"There are {pods.Count} PODs"); foreach (PracticeDto pod in pods) { logger.Info("Generating CSV file"); string attachmentFilePath = CreateFileAttachment(appTempDirectory, pod.PracticeID); logger.Info("Generating email content"); string emailContent = GenerateEmailBody(templateFilePath, pod.PracticeID, pod.PracticeName, pod.ManagerName, reportingDay); string managerEmailID = null; if (pod.ManagerID.HasValue) { managerEmailID = empService.GetByID(pod.ManagerID.Value)?.EmailID; } if (string.IsNullOrWhiteSpace(managerEmailID)) { managerEmailID = dmEmailID; } toEmailID = managerEmailID; logger.Info("Sending email with attachment to " + pod.ManagerName); EmailHandler emailHandler = new EmailHandler(ownerEmailID, outlookPwd); emailHandler.SendEmail(emailClientIP, toEmailID, emailSubject, emailContent, dmEmailID, attachmentFilePath, System.Net.Mail.MailPriority.High); WindowsServiceSettingsDto windowsService = new WindowsServiceSettingsDto { ExecutionInterval = "Monthly", ServiceID = (int)WindowsServices.ManagementNotifications, ServiceName = WindowsServices.ManagementNotifications.ToString(), }; settingRepository.UpdateWindowsServiceStatus(windowsService); } }
public override void treatResponse(Dictionary <string, object> response) { Console.Write(response); Object outVal; response.TryGetValue("projects", out outVal); String outString = outVal.ToString(); List <Folder> folders = FilesHandler.getInstance().initializeFolders(outString); FormsHandler.createProjectsTree(folders); }
public void registration(string nickName, string group_id) { User user = User.create(nickName, group_id); if (userNotExists(user)) { userList.Add(user); FilesHandler.SaveUsers(this.userList); return; } }
public override void treatResponse(Dictionary <string, object> response) { Object outVal; response.TryGetValue("changes", out outVal); String outString = outVal.ToString(); List <File> files = FilesHandler.getInstance().getFiles(outString); files.Reverse(); FormsHandler.addFilesToHistoryGrid(files); }
//выгрузка CSV-файла /*public FileResult GetFile() * { * string filePath = Server.MapPath("~/Database/database.csv"); * string fileType = "csv"; * string fileName = "data.csv"; * return File(filePath, fileType, fileName); * }*/ public FileResult GetFile() { string excelPath = Server.MapPath("~/DataFiles/data.xls"); string databasePath = Server.MapPath("~/Database/database.csv"); FilesHandler.CreateExcelFile(excelPath, databasePath); string fileType = "xls"; string fileName = "data.xls"; return(File(excelPath, fileType, fileName)); }
/// <summary> /// Saves computers list in a XML /// </summary> /// <param name="computer"></param> public static void SaveXML(object computer) { try { FilesHandler <List <Computer> > fileHandler = new FilesHandler <List <Computer> >(); fileHandler.SaveFile(computers, "Computers.xml"); } catch (Exception) { throw; } }
private void StartInspection() { //Actualizo los datos de los sensores Sensores.Actives(); controllerLog.verbose("Localizando CSV de Mediciones"); // Obtengo archivos CSV en carpeta de Mediciones para cada Sensor Activo foreach (Sensores sensor in Sensores.list) { controllerLog.info(""); controllerLog.info("Revisando mediciones de sensor " + sensor.nombre); string anioMes = DateTime.Today.ToString("yyyy-MM"); string fecha = DateTime.Today.ToString("yyyy-MM-dd"); IOrderedEnumerable <FileInfo> csv = FilesHandler.GetFiles(sensor.nombre + "_" + fecha + ".csv", controllerConfig.inspectionCsvPath + "\\" + sensor.nombre + "\\" + anioMes); int totalCsv = csv.Count(); worker.SetProgressTotal(totalCsv); if (totalCsv > 0) { int file_count = 0; foreach (FileInfo file in csv) { file_count++; //RedisRuntime(file_count.ToString(), totalCsv.ToString()); controllerLog.info("---------------------------------------------"); controllerLog.info(" Procesando " + file_count + " / " + totalCsv); controllerLog.info("---------------------------------------------"); HandleInspection(file, sensor); worker.SetProgressWorking(file_count); } controllerLog.info("No hay más datos a revisar"); controllerLog.info("++++++++++++++++++++++++++"); } else { //RedisRuntime(); controllerLog.info("No se encontraron Mediciones de el día de la fecha para el sensor " + sensor.nombre); } } }
/** * Handles the start migration button's functionality. */ public static void StartMigrationHandler() { string isStarted = SettingsHandler.GetSetting("started"); if (isStarted.Equals("1")) { if (HistoryHandler.RevertChanges()) { SettingsHandler.SetSetting("started", "0"); startMigrateButton.Text = START_MIGRATION_TEXT; EnableMigrationCombos(); StopSpecialAddonListeners(); } else { MessageBox.Show("An error has occured, please try again or contact the developer for support."); } } else { DisableMigrationCombos(); if (!FileListeners.InitStaticListeners()) { HistoryHandler.RevertChanges(); MessageBox.Show("An error has occured, please try again or contact the developer for support."); EnableMigrationCombos(); return; } if (!RegistryHandler.SetSourceAsTarget()) { FileListeners.RemoveListeners(); HistoryHandler.RevertChanges(); MessageBox.Show("An error has occured, please try again or contact the developer for support."); EnableMigrationCombos(); return; } StartSpecialAddonListeners(); FilesHandler.CreateFakeFsxExecutable(GetSelectedTargetSimulator().GetSimPath()); startMigrateButton.Text = STOP_MIGRATION_TEXT; SettingsHandler.SetSetting("started", "1"); } }
public int saveToDatabase(string administrator, HttpServerUtilityBase server) { var databaseEntities = new FacebookDatabaseEntities(); var relativePath = FilesHandler.saveImage(picture, server); var group = databaseEntities.Groups.Add(new Group { name = name, administrator = administrator, picture_path = relativePath }); var user = databaseEntities.AspNetUsers.Find(administrator); group.AspNetUsers.Add(user); databaseEntities.SaveChanges(); return(group.group_id); }
private string GenerateNewAllocationEmailContent(ProjectDto benchProject, EmployeeDto employee) { string templateFilePath = ProcessorHelper.GetSettingsValue(ProcessorHelper.TEMPLATE_FOLDER_PATH) + "\\NewAllocationEmailTemplate.html"; string emailTemplateContent = FilesHandler.GetFileContent(templateFilePath); StringBuilder emailBody = new StringBuilder(emailTemplateContent); CultureInfo ci = Thread.CurrentThread.CurrentUICulture; emailBody.Replace("__START_DATE__", $"{DateTime.Today.Day}/{ci.DateTimeFormat.GetAbbreviatedMonthName(DateTime.Today.Month)}/{DateTime.Today.Year}"); emailBody.Replace("__END_DATE__", $"{benchProject.EndDate.Day}/{ci.DateTimeFormat.GetAbbreviatedMonthName(benchProject.EndDate.Month)}/{benchProject.EndDate.Year}"); emailBody.Replace("__RESOURCE_NAME__", $"{employee.FirstName} {employee.LastName}"); emailBody.Replace("__PROJECT_NAME__", benchProject.ProjectName); emailBody.Replace("__RESOURCE_ID__", employee.EmployeeID.ToString()); return(emailBody.ToString()); }
private string GenerateAllocationFailureEmailContent(ProjectAllocationDto allocation) { string templateFilePath = ProcessorHelper.GetSettingsValue(ProcessorHelper.TEMPLATE_FOLDER_PATH) + "\\AllocationFailureEmailTemplate.html"; string emailTemplateContent = FilesHandler.GetFileContent(templateFilePath); StringBuilder emailBody = new StringBuilder(emailTemplateContent); CultureInfo ci = Thread.CurrentThread.CurrentUICulture; emailBody.Replace("__START_DATE__", $"{allocation.AllocationStartDate.Day}/{ci.DateTimeFormat.GetAbbreviatedMonthName(allocation.AllocationStartDate.Month)}/{allocation.AllocationStartDate.Year}"); emailBody.Replace("__END_DATE__", $"{allocation.AllocationEndDate.Day}/{ci.DateTimeFormat.GetAbbreviatedMonthName(allocation.AllocationEndDate.Month)}/{allocation.AllocationEndDate.Year}"); emailBody.Replace("__RESOURCE_NAME__", allocation.EmployeeName); emailBody.Replace("__PROJECT_NAME__", allocation.ProjectName); emailBody.Replace("__RESOURCE_ID__", allocation.EmployeeID.ToString()); return(emailBody.ToString()); }