/// <summary> /// Execute every time cron worked /// </summary> /// <param name="context"></param> async void IJob.Execute(IJobExecutionContext context) { logger.Log("Executing job..."); // Get job data JobDataMap dataMap = context.JobDetail.JobDataMap; try { int JobId = dataMap.GetInt("JobId"); // Get base url string url = System.Configuration.ConfigurationManager.AppSettings["baseUrl"]; // Get scheduled job data var response = await client.GetAsync(url + "/umbraco/surface/schedulesurface/getscheduledjob?JobId=" + JobId); response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); ScheduleJob scheduleJob = JsonConvert.DeserializeObject <ScheduleJob>(content); // Send mail with returned data MailServiceController.MailService.SendMail(scheduleJob); } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); } }
/// <summary> /// Schedule a job with cron expression /// </summary> /// <param name="WorkUntil"></param> /// <param name="CronExpression"></param> /// <param name="JobId"></param> public void ScheduleJob(DateTime WorkUntil, string CronExpression, int JobId) { logger.Log("Scheduling job..."); try { // Get scheduler factory IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler(); scheduler.Start(); // Create job and pass data as job id IJobDetail job = JobBuilder.Create <JobClass>() .WithIdentity(JobId.ToString()) .WithDescription(JobId.ToString()) .UsingJobData("JobId", JobId) .Build(); // Create trigger with Job id and cron expression and make it work workuntil ITrigger trigger = TriggerBuilder.Create() .WithIdentity(JobId.ToString(), "group1") .StartNow() .WithCronSchedule(CronExpression) .EndAt(WorkUntil) .Build(); // Schedule job scheduler.ScheduleJob(job, trigger); logger.Log("Job has been scheduled."); } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); } }
public ActionResult Delete(int contentId) { CustomLogHelper logger = CustomLogHelper.logHelper; try { IContent parentContent = Services.ContentService.GetById(contentId); parentContent.Name = Guid.NewGuid().ToString(); string fileFullName = parentContent.GetValue("attachmentUrl").ToString(); var path = Server.MapPath("~" + fileFullName); if (System.IO.File.Exists(path) && Services.ContentService.UnPublish(parentContent)) { System.IO.File.Delete(path); return(Json(new { status = "Success", message = "Attachment succesfuly deleted" })); } else { return(Json(new { status = "Error", message = "Attachment could not be deleted" })); } } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); return(Json(new { status = "Error", message = "Attachment(s) could not be deleted" })); } }
/// <summary> /// Schedule a job for sending mail /// </summary> /// <param name="scheduleJob"></param> public void ScheduleJob(ScheduleJob scheduleJob) { if (ModelState.IsValid) { logger.Log("Creating new scheduled job..."); try { // Create job content var service = Services.ContentService; IContent job = service.CreateContent(scheduleJob.JobName, -1, "scheduleJob"); job.SetValue("jobName", scheduleJob.JobName); job.SetValue("workUntil", scheduleJob.WorkUntil); job.SetValue("cronExpression", scheduleJob.CronExpression); job.SetValue("senderName", scheduleJob.SenderName); job.SetValue("subject", scheduleJob.Subject); job.SetValue("body", scheduleJob.Body); job.SetValue("templateFile", scheduleJob.TemplateFile); job.SetValue("cC", scheduleJob.CC); job.SetValue("bCC", scheduleJob.BCC); job.SetValue("attachments", scheduleJob.Attachments); job.SetValue("to", scheduleJob.To); if (service.SaveAndPublishWithStatus(job).Success) { // If job content created successfully schedule job logger.Log("Job created successfully. Scheduling it now..."); ScheduleServiceController.ScheduleService.ScheduleJob(scheduleJob.WorkUntil, scheduleJob.CronExpression, job.Id); } else { logger.Log("Job couldn't created."); } } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); } } }
public void SendMail(ScheduleJob scheduleJob) { logger.Log("Sending mail..."); try { using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587)) { smtp.Credentials = new NetworkCredential("*****@*****.**", "tk2QQCZky8Ug"); smtp.EnableSsl = true; //string sender = scheduleJob.SenderName.ToLower().Replace("ü", "ue").Replace('ş', 's').Replace('ı', 'i').Replace("ö", "oe").Replace("ç", "c").Replace('ğ', 'g'); string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Views\\Templates\\" + scheduleJob.TemplateFile + ".cshtml"); string decodedHtml = WebUtility.HtmlDecode(scheduleJob.Body); MailMessage message = new MailMessage { From = new MailAddress("*****@*****.**", scheduleJob.SenderName, Encoding.UTF8), IsBodyHtml = true, BodyEncoding = Encoding.UTF8, SubjectEncoding = Encoding.UTF8, Body = System.IO.File.ReadAllText(path).Replace("{%body%}", decodedHtml), Subject = scheduleJob.Subject }; if (!string.IsNullOrEmpty(scheduleJob.To)) { message.To.Add(scheduleJob.To); } if (!string.IsNullOrEmpty(scheduleJob.CC)) { message.CC.Add(scheduleJob.CC); } if (!string.IsNullOrEmpty(scheduleJob.BCC)) { message.Bcc.Add(scheduleJob.BCC); } if (!string.IsNullOrEmpty(scheduleJob.Attachments)) { foreach (string attachment in scheduleJob.Attachments.Split(',')) { // Attachment is physical file path, can be edited to be relative path later // Create the file attachment for this e-mail message. System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(attachment); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(attachment); disposition.ModificationDate = System.IO.File.GetLastWriteTime(attachment); disposition.ReadDate = System.IO.File.GetLastAccessTime(attachment); // Add the file attachment to this e-mail message. message.Attachments.Add(data); } } try { smtp.Send(message); logger.Log("Mail has been sent."); } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); } } } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); } }
public ActionResult Create(IEnumerable <HttpPostedFileBase> filesToUpload) { CustomLogHelper logger = CustomLogHelper.logHelper; //Taking request parameters from request parentId = Int32.Parse(Request["parentId"]); bool willExistedFileOverwrited = Convert.ToBoolean(Request["willExistedFileOverwrited"]); bool isThereExistedFile = Convert.ToBoolean(Request["isThereExistedFile"]); //Iterating through files for (int i = 0; i < Request.Files.Count; i++) { // Individual file file = Request.Files[i]; fileName = Path.GetFileName(file.FileName); bool isFileValid = true; //File Size Validation if (file.ContentLength > 6000000) { isFileValid = false; failedFiles.Add(fileName, "Individual file size must be under 6MB !! "); } //File Type Validation if (!allowedFileTypes.Contains(file.ContentType)) { isFileValid = false; failedFiles.Add(fileName, "File type is not supported, supported types: pdf, text, excel, csv, jpeg, png "); } //If folder does not exist for parentId then create it folder = Server.MapPath("~/App_Data/uploads/" + parentId); bool isFolderExists = Directory.Exists(folder); if (!isFolderExists) { Directory.CreateDirectory(folder); } string path = Path.Combine(folder, fileName); if (isFileValid) { try { //If there is existed attachment and the attachment exist in the path if (isThereExistedFile && System.IO.File.Exists(path)) { //attachment is going to be overwrited if (willExistedFileOverwrited) { //Overwrite attachment OverwriteAttachment(); } else //Keeping existed attachment and creating new attachment { //Creating new attachment while keeping old attachment KeepExistedAttachmentAddNew(); } } else //If attachment doesn't existed before { //Cretaing new attachment AddNewAttachment(); } } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); string json = JsonConvert.SerializeObject(failedFiles, Formatting.Indented); return(Json(new { status = "Error", message = "file(s) could not be uploaded", files = failedFiles })); } } } if (failedFiles.Count > 0) { string json = JsonConvert.SerializeObject(failedFiles, Formatting.Indented); return(Json(new { status = "Error", message = "file(s) could not be uploaded", files = failedFiles })); } return(Json(new { status = "Success", message = "file(s) successfully uploaded" })); }