private void SendClaimApprovalNotification() { try { Log.ErrorFileWrite(moduleName, "2001", "IN - SPAR MAPPER Email Notification Start"); List <EmailAlert> emailAlertList = EmailAlert.GetAccountClaimApprovalNotificationList(); foreach (EmailAlert emailAlert in emailAlertList) { MailMessage mailMessage = new MailMessage(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), emailAlert.EmailAddress /*"*****@*****.**"*/); mailMessage.Subject = emailAlert.EmailSubject; mailMessage.Body = emailAlert.EmailBody; mailMessage.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["mailRelay"].ToString()); smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), ConfigurationManager.AppSettings["password"].ToString()); smtpClient.EnableSsl = true; smtpClient.Send(mailMessage); } //Utility.WriteLog(2001, 5, "IN - SPAR MAPPER Email Notification End", "Information", TraceEventType.Information, moduleName); Log.ErrorFileWrite(moduleName, "2002", "IN - SPAR MAPPER Email Notification End"); Application.Exit(); } catch (Exception ex) { //Utility.WriteLog(2002, 5, ex.Message, "Exception", TraceEventType.Error, moduleName); Log.ErrorFileWrite(moduleName, "2003", ex.Message, ex.StackTrace); Application.Exit(); } }
public async Task <int> UpdateAsync(EmailAlert entity) { entity.DateCreated = DateTime.Now; entity.DateProcessed = DateTime.Now; entity.CreatedBy = "System"; using (var connection = new SqlConnection(connString)) { connection.Open(); var result = await connection.ExecuteAsync("Sp_EmailAlert_Update", new { entity.Id, entity.Email, entity.Reeson, entity.Status, entity.Message, entity.Subject, entity.UserType, entity.IsActive, entity.Sendtries, entity.CreatedBy, entity.DateCreated, entity.ReceiverName, entity.DateProcessed, entity.BackOfficeUser_SubscriberUser, } , commandType : CommandType.StoredProcedure); return(result); } }
public async static Task <string> SendEmailAlert(List <LastContactedDTO> companies) { var emailConfig = ConfigDictionary.EmailConfig(); string alertCompanies = string.Empty; foreach (LastContactedDTO company in companies) { alertCompanies += $"<li><b>{ company.CompanyName }</b>: last contacted over <span style='color:red;font-weight:bold;'>{ Math.Floor(company.DaysSinceLastContact) }</span> days ago</li>"; } string messageBody = "<html><body>" + $"<span style='display:inline-block;'><img src='https://cdn.shopify.com/s/files/applications/75204543d0fec5bbf9e7f1db609e8804_512x512.png?1594118407' style='width:50%;'/><h2>Client Communication Alert</h2></span>" + $"<p>It has been over 7 days since the following clients were last contacted:</p><br/>" + $"<ul>{ alertCompanies }</ul>" + "</body></html>"; try { await EmailAlert.SendEmailAlert(new EmailAddress(emailConfig["LastContactedRecipientAddress"]), $"Client Communication Alert.", messageBody); return("Email sent!"); } catch (Exception exception) { Console.WriteLine(exception.ToString()); return("Email failed to send."); } }
protected void bnReturn_Click(object sender, System.EventArgs e) { try { int code; MyContent content = new MyContent(appEnv.GetConnection()); Account account = new Account(appEnv.GetConnection()); content.Insert(cid, Convert.ToInt32(dr["Version"]) + 1, 0, dr["Headline"].ToString(), dr["Source"].ToString(), Convert.ToInt32(dr["Byline"]), dr["Teaser"].ToString(), dr["Body"].ToString(), dr["TagLine"].ToString(), Convert.ToInt32(dr["Editor"]), 0, account.GetAccountID(User.Identity.Name), (code = StatusCodes.RequiresEditing)); new Distribution(appEnv.GetConnection()).Remove(cid, ver); EmailAlert ea = new EmailAlert(Context, code, Convert.ToInt32(dr["Editor"])); ea.Send(); } catch (Exception err) { Page_Error("The following error occured: " + err.Message); } Response.Redirect("DeployList.aspx"); }
private void SendEmployeeLeaveDeletionNotificationList() { try { List <EmailAlert> emailAlertList = EmailAlert.GetEmployeeLeaveDeletionNotificationList(Convert.ToDateTime(TextBoxStartDate.Text), Convert.ToDateTime(TextBoxEndDate.Text), this.employeeId, DropDownListLeaveType.SelectedItem.Text); foreach (EmailAlert emailAlert in emailAlertList) { MailMessage mailMessage = new MailMessage(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), emailAlert.EmailAddress /*"*****@*****.**"*/); mailMessage.Subject = emailAlert.EmailSubject; mailMessage.Body = emailAlert.EmailBody; mailMessage.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["mailRelay"].ToString()); smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), ConfigurationManager.AppSettings["password"].ToString()); smtpClient.EnableSsl = true; smtpClient.Send(mailMessage); } } catch (Exception ex) { LabelError.Text = ""; LabelError.Text += ex.Message; PanelError.Visible = true; } }
private void bnWithdraw_Click(object sender, System.EventArgs e) { try { int code; Content content = new Content(appEnv.GetConnection()); Account account = new Account(appEnv.GetConnection()); DataRow dr = dt.Rows[0]; content.Insert(cid, Convert.ToInt32(dr["Version"]) + 1, 0, dr["Headline"].ToString(), dr["Source"].ToString(), Convert.ToInt32(dr["Byline"]), dr["Teaser"].ToString(), dr["Body"].ToString(), dr["TagLine"].ToString(), 0, Convert.ToInt32(dr["Approver"]), account.GetAccountID(User.Identity.Name), (code = StatusCodes.AwaitingEdit)); EmailAlert ea = new EmailAlert(Context, code, 0); ea.Send(); } catch (Exception err) { Page_Error("The following error occured: " + err.Message); } Response.Redirect("EdList.aspx"); }
public Mainform() { InitializeComponent(); emailalertclient = new EmailAlert(); notificationTimer.Tick += new EventHandler(notificationTimer_Tick); notificationTimer.Interval = 2000; }
private void sendReceipt() { var message = new StringBuilder(); email.RenderControl(new HtmlTextWriter(new StringWriter(message))); string s = message.ToString(); EmailAlert alerter = new EmailAlert(); alerter.sendEmail(GenericQuery.getUserEmail(User.Identity.Name), "Web Shop Receipt", s); }
public SettingsController() { this.pdata = new ProfileData(); this.ealert = new EmailAlert(); this.sellerData = new SellerData(); this.dashboardData = new DashboardData(); _version = ConfigurationManager.AppSettings["ApiVersion"]; _api = ConfigurationManager.AppSettings["Url"]; _redirecturi = ConfigurationManager.AppSettings["LwaRedirectUrl"]; _clientkey = ConfigurationManager.AppSettings["ClientKey"]; _clientSecretkey = ConfigurationManager.AppSettings["ClientSecretKey"]; }
protected void Page_Load(object sender, EventArgs e) { EmailAlert instance = new EmailAlert(); bool test = instance.sendEmail("*****@*****.**", "Very Important thing", "DO IT NOW"); if (test == true) { ShowPopUpMsg("True"); } else { ShowPopUpMsg("False"); } }
public void ClearLists() { Hunt.Clear(); Caution.Clear(); Danger.Clear(); Alert.Clear(); GlobalHunt.Clear(); GlobalCaution.Clear(); GlobalDanger.Clear(); GlobalAlert.Clear(); EmailAlert.Clear(); WieldedItems.Clear(); }
private void bnSubmit_Click(object sender, System.EventArgs e) { int code; content.SetStatus(Convert.ToInt32(dt.Rows[0]["ContentID"]), Convert.ToInt32(dt.Rows[0]["Version"]), (code = StatusCodes.AwaitingApproval)); EmailAlert ea = new EmailAlert(Context, code, 0); ea.Send(); Response.Redirect("EdList.aspx"); }
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } _context.Ticket.Add(Ticket); await _context.SaveChangesAsync(); EmailAlert.Send("ticket created " + Ticket.TicketId, "ticket created " + Ticket.TicketId, "Chris Peck", "*****@*****.**"); return(RedirectToPage("./Index")); }
protected void bnApprove_Click(object sender, System.EventArgs e) { Account account = new Account(appEnv.GetConnection()); content.SetApproval(Convert.ToInt32(dt.Rows[0]["ContentID"]), Convert.ToInt32(dt.Rows[0]["Version"]), account.GetAccountID(User.Identity.Name)); EmailAlert ea = new EmailAlert(Context, StatusCodes.Approved, 0); ea.Send(); Response.Redirect("AppList.aspx"); }
protected void bnReturn_Click(object sender, System.EventArgs e) { int code; content.SetStatus(Convert.ToInt32(dt.Rows[0]["ContentID"]), Convert.ToInt32(dt.Rows[0]["Version"]), (code = StatusCodes.RequiresEditing)); EmailAlert ea = new EmailAlert(Context, code, Convert.ToInt32(dt.Rows[0]["Editor"])); ea.Send(); Response.Redirect("AppList.aspx"); }
protected void bnSubmit_Click(object sender, System.EventArgs e) { int code; content = new MyContent(appEnv.GetConnection()); content.SetStatus(Convert.ToInt32(dt.Rows[0]["ContentID"]), Convert.ToInt32(dt.Rows[0]["Version"]), (code = StatusCodes.RequiresUpdate)); EmailAlert ea = new EmailAlert(Context, code, Convert.ToInt32(dt.Rows[0]["ByLine"])); ea.Send(); Response.Redirect("EdList.aspx"); }
public void ClearArrays() { Hunt.Clear(); Caution.Clear(); Danger.Clear(); Alert.Clear(); GlobalHunt.Clear(); GlobalCaution.Clear(); GlobalDanger.Clear(); GlobalAlert.Clear(); EmailAlert.Clear(); WieldedItems.Clear(); // OffhandItem.Clear(); }
protected void bnSubmit_Click(object sender, System.EventArgs e) { int code; content.SetStatus(Convert.ToInt32(dt.Rows[0]["ContentID"]), Convert.ToInt32(dt.Rows[0]["Version"]), (code = (Convert.ToInt32(dt.Rows[0]["Editor"]) == 0)? StatusCodes.AwaitingEdit : StatusCodes.Editing)); // Any Editor or Specific Editor EmailAlert ea = new EmailAlert(Context, code, Convert.ToInt32(dt.Rows[0]["Editor"])); ea.Send(); Response.Redirect("AutList.aspx"); }
private bool CreateJob(SPWebApplication site) { bool jobCreated = false; try { EmailAlert job = new EmailAlert(JobName, site); SPMinuteSchedule schedule = new SPMinuteSchedule(); schedule.BeginSecond = 0; schedule.EndSecond = 59; schedule.Interval = 10; job.Schedule = schedule; job.Update(); } catch (Exception) { return(jobCreated); } return(jobCreated); }
public async Task <HttpStatusCode> Execute(object properties) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } EmailAlert props = (EmailAlert)properties; var apiKey = Environment.GetEnvironmentVariable(this.config.EnvApiKey, EnvironmentVariableTarget.User); var client = new SendGridClient(apiKey); var from = new EmailAddress(this.config.SenderEmail, this.config.SenderName); var to = new EmailAddress(props.ReceiverEmail, props.ReceiverName); var msg = MailHelper.CreateSingleEmail(from, to, props.Subject, props.TextContent, props.HtmlContent); var response = await client.SendEmailAsync(msg); Console.WriteLine(response.Body.ReadAsStringAsync().Result); return(response.StatusCode); }
private void SendEmployeeLeaveApprovalNotificationList(string attachmentPath) { try { List <EmailAlert> emailAlertList = EmailAlert.GetEmployeeLeaveApprovalNotificationList(Convert.ToInt32(DropDownListFinancialPeriod.SelectedValue), Convert.ToDateTime(TextBoxStartDate.Text), Convert.ToDateTime(TextBoxEndDate.Text), this.employeeId, DropDownListLeaveType.SelectedItem.Text); Attachment attachment = null; if (attachmentPath.Length > 0) { attachment = new Attachment(attachmentPath); } foreach (EmailAlert emailAlert in emailAlertList) { MailMessage mailMessage = new MailMessage(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), emailAlert.EmailAddress /*"*****@*****.**"*/); mailMessage.Subject = emailAlert.EmailSubject; mailMessage.Body = emailAlert.EmailBody; mailMessage.IsBodyHtml = true; if (attachmentPath.Length > 0) { mailMessage.Attachments.Add(attachment); } SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["mailRelay"].ToString()); smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), ConfigurationManager.AppSettings["password"].ToString()); smtpClient.EnableSsl = true; smtpClient.Send(mailMessage); } } catch (Exception ex) { LabelError.Text = ""; LabelError.Text += ex.Message /* + " - " + ex.InnerException.ToString()*/; PanelError.Visible = true; } }
public async Task <int> AddAsync(EmailAlert entity) { int result = 0; try { using (var connection = new SqlConnection(connString)) { entity.DateCreated = DateTime.Now; entity.DateProcessed = DateTime.Now; connection.Open(); result = await connection.ExecuteAsync("Sp_EmailAlert_Insert", new { entity.Email, entity.Reeson, entity.Status, entity.Message, entity.Subject, entity.UserType, entity.IsActive, entity.Sendtries, entity.CreatedBy, entity.DateCreated, entity.ReceiverName, entity.DateProcessed, entity.BackOfficeUser_SubscriberUser, }, commandType : CommandType.StoredProcedure); return(result); } } catch (Exception ex) { ex.Message.ToString(); return(result); } }
public async static Task <string> SendEmailAlert(DailyImpressionsDTO dailyImpressionsSummary) { Dictionary <string, string> emailConfig = ConfigDictionary.EmailConfig(); string companies = string.Empty; foreach (CompanyDailyImpressionsSummary company in dailyImpressionsSummary.DailyImpressionsSummary) { string failingCampaigns = string.Empty; foreach (CampaignDailyImpressionsSummary campaign in company.Campaigns) { failingCampaigns += $"<li>{ campaign.Name }: <span style='color:red;font-weight:bold;'>{ campaign.Impressions }</span> impressions</li>"; } companies += $"<li><b>{ company.Name }</b>: <ul>{ failingCampaigns }</ul></li>"; } string messageBody = "<html><body>" + $"<span style='display:inline-block;'><img src='https://cdn.shopify.com/s/files/applications/75204543d0fec5bbf9e7f1db609e8804_512x512.png?1594118407' style='width:50%;'/><h2>Google Ads Campaign Alert</h2></span>" + $"<p>The following campaigns achieved fewer than 100 impressions yesterday:</p><br/>" + $"<ul>{ companies }</ul>" + "</body></html>"; try { await EmailAlert.SendEmailAlert(new EmailAddress(emailConfig["GoogleAdsRecipientAddress"]), $"Google Ads Campaign Alert", messageBody); return("Email sent!"); } catch (Exception exception) { Console.WriteLine(exception.ToString()); return("Email failed to send."); } }
private void bnReturn_Click(object sender, System.EventArgs e) { int code; Account account = new Account(appEnv.GetConnection()); content.SetApproval(Convert.ToInt32(dt.Rows[0]["ContentID"]), Convert.ToInt32(dt.Rows[0]["Version"]), account.GetAccountID(User.Identity.Name)); content.SetStatus(Convert.ToInt32(dt.Rows[0]["ContentID"]), Convert.ToInt32(dt.Rows[0]["Version"]), (code = StatusCodes.Discontinued)); EmailAlert ea = new EmailAlert(Context, code, Convert.ToInt32(dt.Rows[0]["Editor"])); ea.Body = tbEdReason.Text; ea.Send(); ea = new EmailAlert(Context, code, Convert.ToInt32(dt.Rows[0]["ByLine"])); ea.Body = tbAutReason.Text; ea.Send(); Response.Redirect("AppList.aspx"); }
public SellerController() { this.adata = new AdminData(); this.emailalert = new EmailAlert(); this.optimizeData = new OptimizeData(); }
private IMonitor PopulateConfigurationDataFromServerInfo(AddServer addServerForm) { List<CAlert> alerts = new List<CAlert>(2); //Boolean alertsExist = addServerForm.GetAlerts(out alerts); //alerts = if (addServerForm.addServerAlertEmailOption.CheckState == CheckState.Checked) { EmailAlert ealert = new EmailAlert { Info = addServerForm.addServerAlertEmailTextBox.Text }; if (!configurationData.Settings.IsDefaultAlert(ealert)) alerts.Add(ealert); } if (addServerForm.addServerAlertSmsOption.CheckState == CheckState.Checked) { SmsAlert salert = new SmsAlert { Info = addServerForm.addServerAlertSmsTextBox.Text }; if (!configurationData.Settings.IsDefaultAlert(salert)) alerts.Add(salert); } Boolean alertsExist = alerts.Count > 0 && (addServerForm.addServerAlertEmailOption.Checked | addServerForm.addServerAlertSmsOption.Checked); try { switch (addServerForm.ReturnValue) { case FullMonitorType.Basic: #region Basic BasicMonitor basicMonitor = addServerForm.GetBasicMonitor(); if (alertsExist) { foreach (CAlert alert in alerts) { //if (!configurationData.Settings.IsDefaultAlert(alert)) //{ basicMonitor.AlertInfo.Add(alert); //} } } //else //{ // basicMonitor.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} if (addServerForm.Tag == null) configurationData.BasicMonitors.Add(basicMonitor); else { configurationData.BasicMonitors.Remove(addServerForm.Tag.ToString()); configurationData.BasicMonitors.Add(basicMonitor); } configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return basicMonitor; #endregion case FullMonitorType.Common: #region Common /* * - Hard Drive Usage (dropdown list of C:\, D:\, etc) * - Memory Usage * - Swap/page file usage * - CPU Usage * - Process State (e.g. explorer.exe) * - Service State (e.g. Intelligent Background Transfer Service) */ List<CAlert> validAlerts = new List<CAlert>(2); if (alertsExist) { foreach (CAlert alert in alerts) { //if (!configurationData.Settings.IsDefaultAlert(alert)) //{ validAlerts.Add(alert); //} } } switch (addServerForm.CommonType) { case CommonMonitorType.HddUsage: //Pfc PfcMonitor hddUsage = (PfcMonitor) addServerForm.GetCommonMonitor(); hddUsage.AlertInfo.AddRange(validAlerts); if (addServerForm.Tag == null) configurationData.PfcMonitors.Add(hddUsage); else { configurationData.PfcMonitors.Remove(addServerForm.Tag.ToString()); configurationData.PfcMonitors.Add(hddUsage); } //if (!alertsExist) //{ // hddUsage.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return hddUsage; case CommonMonitorType.CpuUsage: //Pfc PfcMonitor cpuUsage = (PfcMonitor) addServerForm.GetCommonMonitor(); cpuUsage.AlertInfo.AddRange(validAlerts); if (addServerForm.Tag == null) configurationData.PfcMonitors.Add(cpuUsage); else { configurationData.PfcMonitors.Remove(addServerForm.Tag.ToString()); configurationData.PfcMonitors.Add(cpuUsage); } //if (!alertsExist) //{ // cpuUsage.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return cpuUsage; case CommonMonitorType.MemoryUsage: //Wmi WmiMonitor memoryUsage = (WmiMonitor) addServerForm.GetCommonMonitor(); memoryUsage.AlertInfo.AddRange(validAlerts); if (addServerForm.Tag == null) configurationData.WmiMonitors.Add(memoryUsage); else { configurationData.WmiMonitors.Remove(addServerForm.Tag.ToString()); configurationData.WmiMonitors.Add(memoryUsage); } //if (!alertsExist) //{ // memoryUsage.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return memoryUsage; case CommonMonitorType.ProcessState: //Pfc PfcMonitor processState = (PfcMonitor) addServerForm.GetCommonMonitor(); processState.AlertInfo.AddRange(validAlerts); if (addServerForm.Tag == null) configurationData.PfcMonitors.Add(processState); else { configurationData.PfcMonitors.Remove(addServerForm.Tag.ToString()); configurationData.PfcMonitors.Add(processState); } //if (!alertsExist) //{ // processState.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return processState; case CommonMonitorType.ServiceState: //Service ServiceMonitor serviceState = (ServiceMonitor) addServerForm.GetCommonMonitor(); serviceState.AlertInfo.AddRange(validAlerts); if (addServerForm.Tag == null) configurationData.ServiceMonitors.Add(serviceState); else { configurationData.ServiceMonitors.Remove(addServerForm.Tag.ToString()); configurationData.ServiceMonitors.Add(serviceState); } //if (!alertsExist) //{ // serviceState.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return serviceState; case CommonMonitorType.SwapFileUsage: //Pfc PfcMonitor swapFileUsage = (PfcMonitor) addServerForm.GetCommonMonitor(); swapFileUsage.AlertInfo.AddRange(validAlerts); if (addServerForm.Tag == null) configurationData.PfcMonitors.Add(swapFileUsage); else { configurationData.PfcMonitors.Remove(addServerForm.Tag.ToString()); configurationData.PfcMonitors.Add(swapFileUsage); } //if (!alertsExist) //{ // swapFileUsage.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return swapFileUsage; case CommonMonitorType.None: default: Logger.Instance.Log(this.GetType(), LogType.Info, "CommonType had an invalid value: unable to populate a Monitor correctly"); break; } return null; #endregion case FullMonitorType.EventLog: #region Events EventMonitor eventMonitor = addServerForm.GetEventMonitor(); if (alertsExist) { foreach (CAlert alert in alerts) { //if (!configurationData.Settings.IsDefaultAlert(alert)) //{ eventMonitor.AlertInfo.Add(alert); //} } } //else //{ // eventMonitor.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} if (addServerForm.Tag == null) configurationData.EventMonitors.Add(eventMonitor); else { configurationData.EventMonitors.Remove(addServerForm.Tag.ToString()); configurationData.EventMonitors.Add(eventMonitor); } configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return eventMonitor; #endregion case FullMonitorType.PerformanceCounter: #region PerfCounters PfcMonitor pfcMonitor = addServerForm.GetPfcMonitor(); if (alertsExist) { foreach (CAlert alert in alerts) { //if (!configurationData.Settings.IsDefaultAlert(alert)) //{ pfcMonitor.AlertInfo.Add(alert); //} } } //else //{ // pfcMonitor.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} if (addServerForm.Tag == null) configurationData.PfcMonitors.Add(pfcMonitor); else { configurationData.PfcMonitors.Remove(addServerForm.Tag.ToString()); configurationData.PfcMonitors.Add(pfcMonitor); } configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return pfcMonitor; #endregion case FullMonitorType.Service: #region Services ServiceMonitor serviceMonitor = addServerForm.GetServiceMonitor(); if (alertsExist) { foreach (CAlert alert in alerts) { //if (!configurationData.Settings.IsDefaultAlert(alert)) //{ serviceMonitor.AlertInfo.Add(alert); //} } } //else //{ // serviceMonitor.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} if (addServerForm.Tag == null) configurationData.ServiceMonitors.Add(serviceMonitor); else { configurationData.ServiceMonitors.Remove(addServerForm.Tag.ToString()); configurationData.ServiceMonitors.Add(serviceMonitor); } configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return serviceMonitor; #endregion case FullMonitorType.Wmi: #region Wmi (For future use) WmiMonitor wmiMonitor = (WmiMonitor)addServerForm.GetCommonMonitor(); //NOTE: need a GetWmiMonitor() later on, potentially if (alertsExist) { foreach (CAlert alert in alerts) { //if (!configurationData.Settings.IsDefaultAlert(alert)) //{ wmiMonitor.AlertInfo.Add(alert); //} } } //else //{ // wmiMonitor.AlertInfo.AddRange(configurationData.Settings.DefaultAlerts); //} if (addServerForm.Tag == null) configurationData.WmiMonitors.Add(wmiMonitor); else { configurationData.WmiMonitors.Remove(addServerForm.Tag.ToString()); configurationData.WmiMonitors.Add(wmiMonitor); } configurationData.ExportToXml(_configPath); MonitorScheduler.Scheduler.SetMonitors(configurationData); return wmiMonitor; #endregion case FullMonitorType.None: default: return null; } } catch (Exception ex) { Logger.Instance.LogException(this.GetType(), ex); MessageBox.Show(this, "Unable to save the Monitor, please check the log for details.", "Error Saving Monitor", MessageBoxButtons.OK); return null; } }
/// <summary> /// Email����������Ϣ��ȡ�� /// </summary> /// <param name="AccessInformation"></param> /// <param name="AlertIndex"></param> /// <returns></returns> public GetEmailAlertResult GetEmailAlert(AccessControl AccessInformation, string AlertIndex) { GetEmailAlertResult Result = new GetEmailAlertResult(); EmailAlert email = new EmailAlert(); string estr = ""; bool ret = true; ret = GetAccessControlInformation(AccessInformation); if (!ret) { estr = keytext[ErrorInfo.AccessControlError.ToString()]; } string strServer = "localhost"; string strUser = "******"; if (AccessInformation.LimitServer) { strServer = AccessInformation.SVDBServer; } if (AccessInformation.LimitUser) { strUser = AccessInformation.UserID; } while (ret) { if (this.iniFile == null) { this.iniFile = new IniFileDaoImpl(); } IDictionary<string, NameValueCollection> sectionlists = this.iniFile.GetIniFileBySection("alert.ini", AlertIndex); email.BaseInfo = GetIniBaseAlertInfo(AlertIndex, sectionlists); email.EmailAddresss = sectionlists[AlertIndex]["EmailAdress"]; email.OtherAddress = sectionlists[AlertIndex]["OtherAdress"]; email.EmailTemplate = sectionlists[AlertIndex]["EmailTemplate"]; email.UpgradeTimes = sectionlists[AlertIndex]["Upgrade"]; email.ReceiverAddress = sectionlists[AlertIndex]["UpgradeTo"]; email.StopTimes = sectionlists[AlertIndex]["Stop"]; email.WatchSheet = sectionlists[AlertIndex]["WatchSheet"]; break; } Result.ErrorInformation = estr; Result.GetEmailAlertOK = ret; Result.ResponseData = email; return Result; }
public ActionResult AddUser(AddUser newUser) { using (mmpEntities mP = new mmpEntities()) { ViewBag.roles = mP.roles.ToList <role>(); ViewBag.regions = mP.regions.ToList <region>(); ViewBag.supervisors = mP.users.Where(a => a.role_id == mP.roles.FirstOrDefault(x => x.role_name == "supervisor").role_id).ToList <user>(); ViewBag.departments = mP.category_type_details.Where(x => x.category_id == (mP.categories.FirstOrDefault(z => z.category_name == "departments").category_id)).ToList <category_type_details>(); ViewBag.projects = mP.category_type_details.Where(x => x.category_id == (mP.categories.FirstOrDefault(z => z.category_name == "projects").category_id)).ToList <category_type_details>(); ViewBag.supervisorsl = mP.users.Where(a => a.role_id == mP.roles.FirstOrDefault(x => x.role_name == "supervisor").role_id&& a.user_status == "active").Select(p => new SelectListItem() { Text = p.employee_id + " " + p.user_name, Value = p.user_id.ToString() }).ToList(); #region Employee ID Already Exists var isEmployeeIDExists = isEmployeeIDExist(newUser.employee_id); if (isEmployeeIDExists) { ModelState.AddModelError("EmployeeExist", "Employee already exists"); return(View(newUser)); } #endregion /*#region User Already Exists * var isUserExists = isUserExist(newUser.user_name); * if (isUserExists) * { * ModelState.AddModelError("UserExist", "User already exists"); * return View(newUser); * } #endregion*/ #region Email Already exists var isEmailExists = IsEmailExist(newUser.user_email); if (isEmailExists) { ModelState.AddModelError("EmailExist", "Email already exists"); newUser.user_name = "Enter New Name"; return(View(newUser)); } #endregion if (ModelState.IsValid) { ModelState.AddModelError("UserExist", "User already exists"); #region Password Hashing newUser.user_password = Crypto.Hash(newUser.user_password); newUser.confirmPassword = Crypto.Hash(newUser.confirmPassword); #endregion user user = new user() { role_id = newUser.role_id, employee_id = newUser.employee_id, user_name = newUser.user_name, user_email = newUser.user_email, designation = newUser.designation, user_password = newUser.user_password, created_at = DateTime.Now, supervisor = newUser.supervisor, region_id = newUser.region_id, user_primary_department = newUser.user_primary_department, user_primary_project = newUser.user_primary_project, user_status = "active", join_date = newUser.joining_date }; mP.users.Add(user); //var timesheet = mP.timesheet_mr.Where(x => x.tsmr_valid_till > DateTime.Now && x.tsmr_start_date < DateTime.Now).FirstOrDefault<timesheet_mr>(); var timesheets = mP.timesheet_mr.Where(x => x.tsmr_valid_till > user.join_date).ToList <timesheet_mr>(); foreach (timesheet_mr timesheet in timesheets) { string body; if (timesheet != null) { timesheet ts = new timesheet() { timesheet_user = user.user_id, time_my = DateTime.Now, timesheet_status = "saved", timesheet_caller = timesheet.tsmr_id, tsmr_extension = timesheet.tsmr_valid_till > DateTime.Now ? timesheet.tsmr_valid_till : DateTime.Now.AddDays(-1) }; mP.timesheets.Add(ts); foreach (DateTime day in EachDay(timesheet.tsmr_start_date, timesheet.tsmr_valid_till)) { presence ps = new presence() { p_date = day, total_hours = 0, leave_status = "", user_id = user.user_id }; mP.presences.Add(ps); } body = "<br></br>" + user.user_name + ", New TimeSheet is assigned to you. TimeSheet is valid Till " + timesheet.tsmr_valid_till + ". Visit the following website to access timeSheet<br></br>" + "<a href='http://magcom-001-site3.etempurl.com'>http://magcom-001-site3.etempurl.com</a>"; Task.Run(() => EmailAlert.SendEmail(user.user_email, body)); } } #region Save to Database mP.SaveChanges(); #endregion return(Json(new { success = true, message = "Saved Successfully" })); } else { return(Json(new { success = true, message = "Invalid Request" })); } } }
/// <summary> /// /// </summary> /// <param name="AccessInformation"></param> /// <param name="AlertInformation"></param> /// <returns></returns> public UpdateAlertResult UpdateEmailAlert(AccessControl AccessInformation, EmailAlert AlertInformation,bool checkname) { UpdateAlertResult Result = new UpdateAlertResult(); string estr = ""; bool ret = true; string strServer = ""; string strUser = ""; while (ret) { ret = GetAccessControlInformation(AccessInformation); if (!ret) { estr = keytext[ErrorInfo.AccessControlError.ToString()]; } strServer = "localhost"; strUser = "******"; if (AccessInformation.LimitServer) { strServer = AccessInformation.SVDBServer; } if (AccessInformation.LimitUser) { strUser = AccessInformation.UserID; } if (checkname) { if (IsAlertNameExist(AccessInformation, AlertInformation.BaseInfo.Name)) { ret = false; estr = keytext[ErrorInfo.AlertNameError.ToString()]; break; } } //email���� //if (string.IsNullOrEmpty(AlertInformation.EmailAddresss)) //{ // ret = false; // estr = keytext[ErrorInfo.EmailAddresssError.ToString()]; // break; //} //if (!string.IsNullOrEmpty(AlertInformation.EmailAddresss)) //{ // if (!CheckEmail(AlertInformation.OtherAddress)) // { // ret = false; // estr = keytext[ErrorInfo.EmailAddresssError.ToString()]; // break; // } //} if (!string.IsNullOrEmpty(AlertInformation.UpgradeTimes)) { if (!IsAlphaNumber(AlertInformation.UpgradeTimes)) { ret = false; estr = keytext[ErrorInfo.AlertTimesError.ToString()]; break; } } if (!string.IsNullOrEmpty(AlertInformation.StopTimes)) { if (!IsAlphaNumber(AlertInformation.StopTimes)) { ret = false; estr = keytext[ErrorInfo.AlertTimesError.ToString()]; break; } } break; } string strAlertIndex = ""; while (ret) { strAlertIndex = AlertInformation.BaseInfo.ID; //���ݴ洢���� ret = SetIniBaseAlertInfo(AccessInformation, AlertInformation.BaseInfo, estr); if (!ret) { break; } //email���� if (this.iniFile == null) { this.iniFile = new IniFileDaoImpl(); } this.iniFile.WriteIniFileString("alert.ini", strAlertIndex, "EmailAdress", AlertInformation.EmailAddresss); this.iniFile.WriteIniFileString("alert.ini", strAlertIndex, "OtherAdress", AlertInformation.OtherAddress); this.iniFile.WriteIniFileString("alert.ini", strAlertIndex, "EmailTemplate", AlertInformation.EmailTemplate); this.iniFile.WriteIniFileString("alert.ini", strAlertIndex, "WatchSheet", AlertInformation.WatchSheet); this.iniFile.WriteIniFileString("alert.ini", strAlertIndex, "Upgrade", AlertInformation.UpgradeTimes); this.iniFile.WriteIniFileString("alert.ini", strAlertIndex, "UpgradeTo", AlertInformation.ReceiverAddress); this.iniFile.WriteIniFileString("alert.ini", strAlertIndex, "Stop", AlertInformation.StopTimes); if (queue == null) { this.queue = new QueueDaoImpl(); } //send message to service bool meseagebool = this.queue.PushStringMessage("SiteView70-Alert", "IniChange", "alert.ini," + strAlertIndex + ",EDIT"); if (!meseagebool) { estr = keytext[ErrorInfo.PushMessageError.ToString()]; } break; } Result.ErrorInformation = estr; Result.UpdateAlertOK = ret; return Result; }
public void Run_Test(int radiobutton , int addons) { driver.Navigate().GoToUrl("https://secure.safebytes.com/driverassist/14/register/?an=DRIV&ec=0&os=%D0%9C%D0%B0%D0%B9%D0%BA%D1%80%D0%BE%D1%81%D0%BE%D1%84%D1%82%20Windows%208.1%20%D0%9A%D0%BE%D1%80%D0%BF%D0%BE%D1%80%D0%B0%D1%82%D0%B8%D0%B2%D0%BD%D0%B0%D1%8F&osb=64bit&pr=AMD%20FX(tm)-8320%20Eight-Core%20Processor%20&mb=ASUSTeK%20Computer%20INC.%20&vc=NVIDIA%20GeForce%20GT%20630%20%20&ram=15%2C98%20GB&hd=232%2C88%20GB"); IWebElement query = driver.FindElement(By.CssSelector("button.activate-now")); query.SendKeys(Keys.Enter); System.Threading.Thread.Sleep(5000); switch (radiobutton) { // Select 2 years plan ( left ) case 1: driver.FindElement(By.Id("donev")).Click(); break; // Select 6 months ( center) case 2: driver.FindElement(By.Id("twov")).Click(); break; // Select 1 year ( right) case 3: driver.FindElement(By.Id("dthreev")).Click(); break; // do nothing leave all as is ( preselected both addons ) case 0: break; } System.Threading.Thread.Sleep(5000); switch (addons) { case 1: // here we UNselect SAF driver.FindElement(By.XPath("//form[@id='select_form']/div/div[2]/div[3]/div[2]/div[7]/span")).Click(); break; case 2: // here we UNselect TSC driver.FindElement(By.XPath("//form[@id='select_form']/div/div[2]/div[3]/div[2]/div[7]/div[2]/span")).Click(); break; // here we UNselect SAF + TSC case 12: // here we UNselect SAF driver.FindElement(By.XPath("//form[@id='select_form']/div/div[2]/div[3]/div[2]/div[7]/span")).Click(); // here we UNselect TSC driver.FindElement(By.XPath("//form[@id='select_form']/div/div[2]/div[3]/div[2]/div[7]/div[2]/span")).Click(); break; // do nothing leave preselected 6 months case 0: break; } //driver.FindElement(By.Id("dthreev")).Click(); // here we UNselect TSC driver.FindElement(By.XPath("//form[@id='select_form']/div/div[2]/div[3]/div[2]/div[7]/div[2]/span")).Click(); // here we UNselect SAF driver.FindElement(By.XPath("//form[@id='select_form']/div/div[2]/div[3]/div[2]/div[7]/span")).Click(); //query.SendKeys(Keys.Space); //driver.FindElement(By.Name("include-driver-updates")).Click(); // end of selection Addons query = driver.FindElement(By.XPath("(//input[@value=' '])[4]")); query.SendKeys(Keys.Enter); driver.FindElement(By.Id("form_name")).Clear(); driver.FindElement(By.Id("form_name")).SendKeys("max qa"); driver.FindElement(By.Id("form_email")).Clear(); driver.FindElement(By.Id("form_email")).SendKeys("*****@*****.**"); driver.FindElement(By.Id("form_postal_zip")).Clear(); driver.FindElement(By.Id("form_postal_zip")).SendKeys("V8V1J9"); driver.FindElement(By.Id("cc_num")).Clear(); driver.FindElement(By.Id("cc_num")).SendKeys("4111111111111111"); new SelectElement(driver.FindElement(By.Id("cc_month"))).SelectByText("04"); driver.FindElement(By.CssSelector("option[value=\"04\"]")).Click(); new SelectElement(driver.FindElement(By.Id("cc_year"))).SelectByText("2016"); driver.FindElement(By.Id("cc")).Clear(); driver.FindElement(By.Id("cc")).SendKeys("123"); driver.FindElement(By.Id("submit-button")).Click(); // ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.] // ERROR: Caught exception [ERROR: Unsupported command [waitForFrameToLoad | receipt_body | 25000]] // ERROR: Caught exception [ERROR: Unsupported command [selectFrame | name=receipt_body | ]] // Making sure there is "Thank you " line in receipt try { //make sure it is in the main document right now driver.SwitchTo().DefaultContent(); //find the outer frame, and use switch to frame method IWebElement Receipt_iFrame = driver.FindElement(By.Id("receipt_body")); driver.SwitchTo().Frame(Receipt_iFrame); string thanks_purchase_css_text = driver.FindElement(By.ClassName("thanks-purchase")).Text; Assert.IsTrue(Regex.IsMatch(thanks_purchase_css_text, "Thank.You.for.Your.Purchase!")); } catch (AssertionException e) { EmailAlert EA = new EmailAlert(); EA.send_email_alert("Text not found :Thank You for Your Purchase" + e.Message); verificationErrors.Append("Text not found :Thank You for Your Purchase"); } // Making sure we got a license on receipt try { //make sure it is in the main document right now driver.SwitchTo().DefaultContent(); //find the outer frame, and use switch to frame method IWebElement Receipt_iFrame = driver.FindElement(By.Id("receipt_body")); driver.SwitchTo().Frame(Receipt_iFrame); Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.CssSelector("body")).Text, ".*[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}.*")); } catch (AssertionException e) { EmailAlert EA = new EmailAlert(); EA.send_email_alert("License Key Not found!" + e.Message); verificationErrors.Append("License Key Not found!"); } }
public async Task CheckAlerts(Message message) { var sensorId = this.dbContext.Sensors.First(s => s.Label == message.Sensor).Id; var deviceSensor = this.dbContext.Devices .Include(d => d.DeviceSensors) .Include(d => d.User) .First(d => d.Id == new Guid(message.DeviceId)) .DeviceSensors .FirstOrDefault(ds => ds.SensorId == sensorId && ds.DeviceId == new Guid(message.DeviceId)); if (deviceSensor.IsNotificationOn == false) { return; } double?min = deviceSensor?.MinValue; double?max = deviceSensor?.MaxValue; if (!min.HasValue && !max.HasValue) { //Console.WriteLine($"No alerts for {message.DeviceId} / {message.Sensor}"); return; } if (max.HasValue) { var lastAlert = this.dbContext.Alerts .OrderByDescending(a => a.AlertStarted) .FirstOrDefault(a => a.DeviceId == new Guid(message.DeviceId) && a.SensorId == sensorId && a.AlertClosed == null); if (max.Value < Convert.ToDouble(message.Value)) { if (lastAlert == null) { var newAlert = new Alert() { Id = Guid.NewGuid(), AlertStarted = message.Time, AlertType = AlertTypeEnum.Above_Max_Value, DeviceId = new Guid(message.DeviceId), SensorId = this.dbContext.Sensors.First(s => s.Label == message.Sensor).Id, TriggeringValue = message.Value.ToString(), ValueType = Enum.Parse <ValueTypeEnum>(message.ValueType) }; this.dbContext.Alerts.Add(newAlert); this.dbContext.SaveChanges(); Console.WriteLine($" - !!! Alert {newAlert.AlertType} / {newAlert.TriggeringValue} !!!"); // send email var emailProps = new EmailAlert() { ReceiverEmail = deviceSensor.Device.User.Email, ReceiverName = deviceSensor.Device.User.FirstName, Subject = $"[Alert] {message.Sensor} {newAlert.AlertType}", HtmlContent = $"<strong>[{message.Time}]:</strong> <br>Hello {deviceSensor.Device.User.FirstName},<br><br>" + $" <strong>DeivceId :</strong>{message.DeviceId} <br> <strong>Sensor: </strong> {message.Sensor} <br>" + $" Sensor's value <strong>{message.Value}</strong> triggered <i>{newAlert.AlertType} - {(newAlert.AlertType == AlertTypeEnum.Above_Max_Value ? max : min)}</i>" }; await this.alertNotifier.Execute(emailProps); Console.WriteLine($" == Email sent to {emailProps.ReceiverEmail}"); } } else { if (lastAlert != null) { lastAlert.AlertClosed = message.Time; this.dbContext.Alerts.Update(lastAlert); this.dbContext.SaveChanges(); Console.WriteLine($" - Alert {lastAlert.AlertType} closed w/ value {message.Value}"); } } } }
public async Task <dynamic> Get() { if (CheckClientSecret()) { Entities db = new Entities(); Dictionary <string, string> emailConfig = ConfigDictionary.EmailConfig(); var storesRequiringUpdate = new List <StoreCustomData>(); foreach (StoreCustomData store in db.StoreCustomDatas) { DateTime lastUpdate = db.SalesTargetHistories .Where(x => x.StoreID == store.StoreID) .OrderByDescending(x => x.DateUpdated) .FirstOrDefault() .DateUpdated; if ((DateTime.Now - lastUpdate).TotalDays > 30) { storesRequiringUpdate.Add(store); } } if (storesRequiringUpdate.Any()) { string storeNames = string.Empty; foreach (StoreCustomData store in storesRequiringUpdate) { storeNames += $"<li><b>{ store.StoreName }</b> - Current Sales Target: £{ store.SalesTarget }</li>"; } string messageBody = "<html><body>" + $"<span style='display:inline-block;'><img src='https://cdn.shopify.com/s/files/applications/75204543d0fec5bbf9e7f1db609e8804_512x512.png?1594118407' style='width:50%;'/><h2>Sales Target Update Alert</h2></span>" + $"<p>It has been more than 30 days since Sales Targets were updated for the following stores:</p><br/>" + $"<ul>{ storeNames }</ul>" + "</body></html>"; try { await EmailAlert.SendEmailAlert(new EmailAddress(emailConfig["SalesTargetRecipientAddress"]), "Sales Target Update Alert", messageBody); return("Email sent!"); } catch (Exception exception) { Console.WriteLine(exception.ToString()); return("Email failed to send."); } } else { return("No updates required."); } } else { return(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)); } }
protected void EnableButton_Click(object sender, EventArgs e) { MembershipUser user = Membership.GetUser(UserName.Text.Trim()); if (user != null) { user.IsApproved = true; Membership.UpdateUser(user); string connectionString = "AsiaWebShopDBConnectionString"; string query = "UPDATE [Member]"+ "SET [active]="+ 1 +"WHERE ([username] =N'" + UserName.Text.Trim() + "')"; // Create the connection and the SQL command. using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionString].ConnectionString)) using (SqlCommand command = new SqlCommand(query, connection)) { // Open the connection, execute the INSERT query and close the connection. command.Connection.Open(); command.ExecuteNonQuery(); command.Connection.Close(); } MemberGridView.DataBind(); using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AsiaWebShopDBConnectionString"].ConnectionString)) { // start to connect sql server connection.Open(); Int32 count = 0; int emailSentNum = 0; do { SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM [WishListItem] WHERE (([userName]= N'" + UserName.Text.Trim() + "') AND ([emailSent] = N'" + false + "') AND ([isAlert] = N'" + true + "') AND ([userName] in (SELECT userName FROM [member] WHERE [active] = N'" + true + "')))", connection); count = (Int32)command.ExecuteScalar(); if (count != 0) { SqlCommand test = new SqlCommand("SELECT upc FROM [WishListItem] WHERE (([userName]= N'" + UserName.Text.Trim() + "') AND ([emailSent] = N'" + false + "') AND ([isAlert] = N'" + true + "') AND ([userName] in (SELECT userName FROM [member] WHERE [active] = N'" + true + "')))", connection); String upcNum = test.ExecuteScalar().ToString().Trim(); SqlCommand name = new SqlCommand("SELECT name FROM [Item] WHERE (([upc] = N'" + upcNum + "'))", connection); String itemName = name.ExecuteScalar().ToString().Trim(); SqlCommand userEmail = new SqlCommand("SELECT email FROM [member] WHERE (([userName] = N'" + UserName.Text.Trim() + "'))", connection); String email = userEmail.ExecuteScalar().ToString().Trim(); EmailAlert instance = new EmailAlert(); bool isEmailSent = instance.sendEmail(email, itemName + " is now availiable. Come to AisaWebShop.", "Dear customer " + UserName.Text.Trim() + ":\n\n " + itemName + " is now on stock. Visit our website and You will find products you want are all in our shop.\n\nBest wishes, \nASiaWebShop"); if (isEmailSent == true) { SqlCommand alertEmailSent = new SqlCommand("UPDATE [WishListItem] SET [isAlert]=N'" + false + "', [emailSent]= N'" + true + "' WHERE (([upc] = N'" + upcNum + "') AND ([userName] = N'" + UserName.Text.Trim() + "'))", connection); alertEmailSent.ExecuteScalar(); emailSentNum++; } else { ShowPopUpMsg("Email can't be sent"); } } } while (count != 0); if (emailSentNum != 0) ShowPopUpMsg(emailSentNum + " email(s) are sent"); connection.Close(); } } }
public HttpStatusCode WebHook() { try { var paymentAlertStatus = 0; string secret = MppUtility.ReadConfig("MS_WebHookReceiverSecret_Custom"); var postdata = new StreamReader(HttpContext.Request.InputStream).ReadToEnd(); var emailboday = ""; var signature = Request.Headers["Stripe-Signature"]; var stripeEvent = StripeEventUtility.ConstructEvent(postdata, signature, secret); var eventid = stripeEvent.Id; var eventdata = StripeHelper.GetStripeEvent(eventid); var data = JObject.Parse(postdata); var custid = data["data"].First().First["customer"].ToString(); var msg = ""; if (eventdata != null && (eventdata.Type == "invoice.payment_succeeded" || eventdata.Type == "invoice.payment_failed")) { String coupon_id = null; var list = data["data"].First().First["lines"]; var Amount = ((double)list["data"].First["amount"]) / 100; var Amount_off = ((double)data["data"].First().First["amount_due"]) / 100; var Discount = data["data"].First().First["discount"]; var start = (double)list["data"].First["period"]["start"]; var end = (double)list["data"].First["period"]["end"]; var startperiod = MppUtility.UnixTimeStampToDateTime(start); var endperiod = MppUtility.UnixTimeStampToDateTime(end); var discount = Math.Round(Amount - Amount_off, 2, MidpointRounding.AwayFromZero); var customerdata = StripeHelper.GetStripeCustomer(custid); var email = customerdata.Email; var last4 = ""; var carddetails = StripeHelper.GetCard(custid); foreach (var card in carddetails) { last4 = card.Last4; } if (Discount.Count() > 0) { coupon_id = Discount["coupon"]["id"].ToString(); } switch (eventdata.Type) { case "invoice.payment_succeeded": msg = AccountData.UpdatePaymentStatus(custid, Amount, Amount_off, coupon_id, discount, startperiod, endperiod, 1); emailboday = "A payment of $" + Amount_off + " was made using your card on file ending with <b> " + last4 + " </b>"; paymentAlertStatus = 1; break; case "invoice.payment_failed": msg = AccountData.UpdatePaymentStatus(custid, Amount, Amount_off, coupon_id, discount, startperiod, endperiod, 0); upData.UpdatePlanData(custid, 0); StripeHelper.UnSubscribe(custid); emailboday = @"A payment $" + Amount_off + " failed from your card ending with <b> " + last4 + " </b>" + "Please check your card details or add new card."; paymentAlertStatus = 2; break; } if (msg == "" && Amount_off != 0) { var respo = EmailAlert.PaymentAlertMail(email, emailboday); if (respo == "success") { sellerData.UpdatePaymentAlert(paymentAlertStatus, custid); } } } else if (stripeEvent.Type == "charge.failed") { var Amount = ((double)data["data"].First().First["amount"]) / 100; var failure_message = data["data"].First().First["failure_message"].ToString(); // msg = AccountData.UpdatePaymentStatus(custid, Amount, Amount, 0, 0.00, startperiod, endperiod, 0); if (Amount > 1)//Card verification charge { upData.UpdatePlanData(custid, 0); StripeHelper.UnSubscribe(custid); } var last4 = ""; var carddetails = StripeHelper.GetCard(custid); var customerdata = StripeHelper.GetStripeCustomer(custid); var email = customerdata.Email; foreach (var card in carddetails) { last4 = card.Last4; } emailboday = @"A payment $" + Amount + " failed from your card ending with <b> " + last4 + " </b>" + "Please check your card details or add new card.</b>Possible reason:" + failure_message; var respo = EmailAlert.PaymentAlertMail(email, emailboday); if (respo == "success" && Amount > 1) { sellerData.UpdatePaymentAlert(2, custid); } } } catch (Exception ex) { String msg = ex.Message; LogFile.WriteLog(msg); } return(HttpStatusCode.OK); }
private void SendEmployeeLeaveReportsToDecisionNotification(int employeeLeaveDaysId) { try { MailMessage mailMessage = new MailMessage(); string emailAddress = ""; string subject = ""; string body = ""; List <EmailAlert> emailAlertList = EmailAlert.GetEmployeeLeaveReportsToDecisionNotification(employeeLeaveDaysId); foreach (EmailAlert emailAlert in emailAlertList) { emailAddress = emailAlert.EmailAddress; mailMessage.CC.Add(emailAlert.EmailAddressReportsTo); subject = emailAlert.EmailSubject; body = emailAlert.EmailBody;; } MailMessage fromToMailMessage = new MailMessage(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), emailAddress /*"*****@*****.**"*/); mailMessage.From = fromToMailMessage.From; mailMessage.To.Add(emailAddress); mailMessage.Subject = subject; mailMessage.Body = body; mailMessage.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["mailRelay"].ToString()); smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), ConfigurationManager.AppSettings["password"].ToString()); smtpClient.EnableSsl = true; smtpClient.Send(mailMessage); } catch (Exception ex) { //LabelError.Text = ""; //LabelError.Text += ex.Message; //PanelError.Visible = true; } //try //{ // List<EmailAlert> emailAlertList = EmailAlert.GetEmployeeLeaveReportsToDecisionNotification(employeeLeaveDaysId); // foreach (EmailAlert emailAlert in emailAlertList) // { // MailMessage mailMessage = new MailMessage(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), emailAlert.EmailAddress /*"*****@*****.**"*/); // mailMessage.CC.Add(emailAlert.EmailAddressReportsTo); // mailMessage.Subject = emailAlert.EmailSubject; // mailMessage.Body = emailAlert.EmailBody; // mailMessage.IsBodyHtml = true; // SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["mailRelay"].ToString()); // smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); // smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), ConfigurationManager.AppSettings["password"].ToString()); // smtpClient.EnableSsl = true; // smtpClient.Send(mailMessage); // } //} //catch (Exception ex) //{ // //LabelError.Text = ""; // //LabelError.Text += ex.Message; // //PanelError.Visible = true; //} }
public override Alert CreateAlert(string title, string msg, string recipient) { EmailAlert alert = new EmailAlert(recipient, title, msg, true); return(alert); }
public void WebHook() { try { var paymentAlertStatus = 0; var postdata = new StreamReader(HttpContext.Request.InputStream).ReadToEnd(); var data = JObject.Parse(postdata); var signature = Request.Headers["Stripe-Signature"]; var eventid = data["id"].ToString(); var custid = data["data"].First().First["customer"].ToString(); var msg = ""; var emailboday = ""; var eventdata = StripeHelper.GetStripeEvent(eventid); if (eventdata != null && (eventdata.Type == "invoice.payment_succeeded" || eventdata.Type == "invoice.payment_failed")) { String coupon_id = null; var list = data["data"].First().First["lines"]; var Amount = ((double)list["data"].First["amount"]) / 100; var Amount_off = ((double)data["data"].First().First["amount_due"]) / 100; var Discount = data["data"].First().First["discount"]; var start = (double)list["data"].First["period"]["start"]; var end = (double)list["data"].First["period"]["end"]; var startperiod = MppUtility.UnixTimeStampToDateTime(start); var endperiod = MppUtility.UnixTimeStampToDateTime(end); var discount = Math.Round(Amount - Amount_off, 2, MidpointRounding.AwayFromZero); var customerdata = StripeHelper.GetStripeCustomer(custid); var email = customerdata.Email; var last4 = ""; var carddetails = StripeHelper.GetCard(custid); foreach (var card in carddetails) { last4 = card.Last4; } if (Discount.Count() > 0) { coupon_id = Discount["coupon"]["id"].ToString(); } switch (eventdata.Type) { case "invoice.payment_succeeded": msg = AccountData.UpdatePaymentStatus(custid, Amount, Amount_off, coupon_id, discount, startperiod, endperiod, 1); emailboday = "Payment Success. A payment of $" + Amount_off + " was made using your card on file ending with <b> " + last4 + " </b>"; paymentAlertStatus = 1; break; case "invoice.payment_failed": msg = AccountData.UpdatePaymentStatus(custid, Amount, Amount_off, coupon_id, discount, startperiod, endperiod, 0); emailboday = "Payment failed.Payment $" + Amount_off + " failed from your card ending with <b> " + last4 + " </b> "; paymentAlertStatus = 2; break; } if (msg == "" && Amount_off != 0) { var respo = EmailAlert.PaymentAlertMail(email, emailboday); if (respo == "success") { sellerData.UpdatePaymentAlert(paymentAlertStatus, custid); } } } } catch (Exception ex) { String msg = ex.Message; } }
protected bool sendEmail(string upc) { using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AsiaWebShopDBConnectionString"].ConnectionString)) { // start to connect sql server connection.Open(); Int32 count = 0; int emailSentNum = 0; do { SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM [WishListItem] WHERE (([upc] = N'" + upc + "') AND ([emailSent] = N'" + false + "') AND ([isAlert] = N'" + true + "') AND ([userName] in (SELECT userName FROM [member] WHERE [active] = N'" + true + "')))", connection); count = (Int32)command.ExecuteScalar(); if (count != 0) { SqlCommand test = new SqlCommand("SELECT userName FROM [WishListItem] WHERE (([upc] = N'" + upc + "') AND ([emailSent] = N'" + false + "') AND ([isAlert] = N'" + true + "') AND ([userName] in (SELECT userName FROM [member] WHERE [active] = N'" + true + "')))", connection); String customerName = test.ExecuteScalar().ToString().Trim(); SqlCommand name = new SqlCommand("SELECT name FROM [Item] WHERE (([upc] = N'" + upc + "'))", connection); String itemName = name.ExecuteScalar().ToString().Trim(); SqlCommand userEmail = new SqlCommand("SELECT email FROM [member] WHERE (([userName] = N'" + customerName + "'))", connection); String email = userEmail.ExecuteScalar().ToString().Trim(); EmailAlert instance = new EmailAlert(); bool isEmailSent = instance.sendEmail(email, itemName + " is now availiable. Come to AisaWebShop.", "Dear customer " + customerName + ":\n\n " + itemName + " is now on stock. Visit our website and You will find products you want are all in our shop.\n\nBest wishes, \nASiaWebShop"); if (isEmailSent == true) { SqlCommand alertEmailSent = new SqlCommand("UPDATE [WishListItem] SET [isAlert]= N'" + false + "', [emailSent]= N'" + true + "' WHERE (([upc] = N'" + upc + "') AND ([userName] = N'" + customerName + "'))", connection); alertEmailSent.ExecuteScalar(); emailSentNum++; } else { ShowPopUpMsg("Email can't be sent"); } } } while (count != 0); if (emailSentNum != 0) ShowPopUpMsg(emailSentNum + " email(s) are sent"); connection.Close(); } return true; }