private void SendEmails(Emails email, string type) { try { Emails.SendEmail(email, type); } catch (Exception ex) { new SqlLog().InsertSqlLog(0, "ViewUsers.aspx SendEmails", ex); } }
partial void SendMail_Execute() { this.FindControl("SendingMessage").ControlAvailable += PostsListDetail_ControlAvailable; Email = new Emails(); Email.ReceiverMail = this.Partner.SelectedItem.Email; Email.Receiver = this.Partner.SelectedItem.FirstName + " " + this.Partner.SelectedItem.LastName; Email.Sender = "me"; //Email.Subject = ""; //Email.Message = ""; this.OpenModalWindow("SendingMessage"); }
protected void gvUserAdmin_RowCommand(object sender, GridViewCommandEventArgs e) { try { if (e.CommandName == "Approve") { UserInfo user = new UserInfo(Convert.ToInt32(e.CommandArgument)); if (!user.IsApproved) { Emails email = new Emails(); email.To = user.Login; email.URL = ConfigurationManager.AppSettings["EmailUrl"].ToString() + "ChangePassword.aspx?userId=" + Encryption.Encrypt(user.UserId.ToString()); email.From = "*****@*****.**"; email.Subject = "Registration Approval Email"; Thread Email_Thread = new Thread(() => SendEmails(email, Emails.EmailType.ApplicationApprovedEmail.ToString())); Email_Thread.Start(); } UserInfo.ApproveAdminUser(Convert.ToInt32(e.CommandArgument)); SearchAdminUsers(1); } else if (e.CommandName == "DeleteUser") { UserInfo.DeleteAdminUser(Convert.ToInt32(e.CommandArgument)); SearchAdminUsers(1); } else if (e.CommandName == "DisApprove") { UserInfo.DisApproveAdminUser(Convert.ToInt32(e.CommandArgument)); SearchAdminUsers(1); } } catch (Exception ex) { new SqlLog().InsertSqlLog(0, "ViewUsers.aspx.gvUserAdmin_RowCommand", ex); } }
public virtual int FillByWhereClause(Emails.CustomerEmailsDataTable dataTable, string whereClause, System.Data.OleDb.OleDbParameter[] parameters) { System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(); command.Connection = this.Connection; this._commandCollection[0].CommandText = @"SELECT ID, Email, CustomerID, CreateID, CreateUser, ModifyID, ModifyUser FROM CustomerEmails " + whereClause + ";"; command.CommandType = System.Data.CommandType.Text; if (null != parameters) command.Parameters.AddRange(parameters); this.Adapter.SelectCommand = command; if ((this.ClearBeforeFill == true)) { dataTable.Clear(); } int returnValue = this.Adapter.Fill(dataTable); return returnValue; }
void RetrieveEmail(int id) { var objEmail = new Emails().GetEmail(id); lblSubject.Text = (string.IsNullOrEmpty(objEmail.Subject) ? "<i>No Subject</i>" : objEmail.Subject); lblFrom.Text = objEmail.FromAddress; lblTo.Text = String.Join(",", objEmail.ToAddress); lblDate.Text = objEmail.SentDate.ToString("dd MMM yyyy HH:mm"); if (!string.IsNullOrEmpty(objEmail.ExchangeUniqueId) && objEmail.Synced == 1) { //load the email using exchange details var result = ProcessMailItem(objEmail); if (result) { objEmail = new Emails().GetEmail(id); BindAdvanceDetails(objEmail); } } else { BindAdvanceDetails(objEmail); } }
private void LoadInfo() { try { int SSID = Conversion.ParseInt( Request.QueryString["SSID"] ); int orgId = OrganizationInfo.getOrganizationIdByEmail(eMail.Text.Trim(), SSID); if (orgId > 0) { Emails email = new Emails(); email.To = eMail.Text.Trim(); string userId = new UserInfo(eMail.Text.Trim()).UserId.ToString(); email.URL = ConfigurationManager.AppSettings["EmailUrl"].ToString() + "ChangePassword.aspx?userId=" + Encryption.Encrypt(new UserInfo(eMail.Text.Trim()).UserId.ToString()); email.From = "*****@*****.**"; email.Subject = "EPRTS Forget Password Email"; //Thread Email_Thread = new Thread(() => SendEmails(email, Emails.EmailType.ForgetPassordEmail.ToString())); //Email_Thread.Start(); SendEmails(email, Emails.EmailType.ForgetPassordEmail.ToString()); dvthankyou.Visible = true; dvforgotpassword.Visible = false; eMail.Visible = false; submit.Visible = false; //lblTitleAddress.Visible = false; // Response.Redirect("/", false); } else { lblError.Text = "Email not matched with primary email."; lblError.Visible = true; } } catch (Exception ex) { new SqlLog().InsertSqlLog(0, "ForgotPassword.aspx LoadInfo", ex); } }
// A method that accepts a subscriber method that must follow the InformationSender delegate // It also takes the email of the subscriber // This subscriber expects to get only relevant information each time the market sends one // This is used just as an example that we can have multiple events with different delegates for different business logic public void SubscribeForInformation(InformationSender subscriber, string email) { InformationEvent += subscriber; Emails.Add(email); }
public UserDevices(Context ctxt, Emails email) { _context = ctxt; _mailDevices = email; }
private void createMail(Orders new_order) { string strSubject = "התקבלה הזמנה חדשה - אל-עמי"; string strMessage = "<html><body dir=\"rtl\">"; strMessage = strMessage + String.Format("התקבלה הזמנה חדשה") + Environment.NewLine + Environment.NewLine + "<br><br>"; strMessage = strMessage + String.Format("פרטי ההזמנה:") + Environment.NewLine + "<br><br>"; string tab = " "; strMessage = strMessage + tab + String.Format("בית הספר המזמין: {0}", new_order.SchoolPart.FullName) + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("נושא הפעילות: {0}", new_order.Topic.Title) + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("קהל: {0}", new_order.Audience.Title) + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("מספר כיתות: {0}", new_order.OrderClassesAndCounslers.ClassesNumber) + Environment.NewLine + Environment.NewLine + "<br>"; //strMessage = strMessage + String.Format("מספר סבבים: {0}", // new_order.RoundsNumber) + Environment.NewLine + Environment.NewLine + "<br><br>"; strMessage = strMessage + tab + String.Format("מספר מדריכים: {0}", new_order.OrderClassesAndCounslers.CounslerNumber) + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("מחיר: {0}", new_order.OrderClassesAndCounslers.Price) + Environment.NewLine + Environment.NewLine + "<br>"; if (null != new_order.DT1) { strMessage = strMessage + tab + String.Format("התאריכים:") + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("{0}", new_order.DT1) + Environment.NewLine + Environment.NewLine + "<br>"; } if (null != new_order.DT2) { strMessage = strMessage + tab + String.Format("{0}", new_order.DT2) + Environment.NewLine + Environment.NewLine + "<br>"; } if (null != new_order.DT3) { strMessage = strMessage + tab + String.Format("{0}", new_order.DT3) + Environment.NewLine + Environment.NewLine + "<br>"; } strMessage = strMessage +"<br>"; strMessage = strMessage + String.Format("פרטי המזמין:") + Environment.NewLine + "<br><br>"; strMessage = strMessage + tab + String.Format("{0}", new_order.Contact) + Environment.NewLine + Environment.NewLine + "<br>"; if (null != new_order.Email && !new_order.Email.Equals("")) { strMessage = strMessage + tab + String.Format("אימייל: {0}", new_order.Email) + Environment.NewLine + Environment.NewLine + "<br>"; } if (null != new_order.Phone && !new_order.Phone.Equals("")) { strMessage = strMessage + tab + String.Format("מספר טלפון: {0}", new_order.Phone) + Environment.NewLine + Environment.NewLine + "<br>"; } strMessage = strMessage + "<br>"; string website = "http://binyamin.info/binyamin"; strMessage = strMessage + String.Format("על-מנת לטפל בהזמנה כנס ל- {0}", website) + Environment.NewLine + "<br>"; strMessage = strMessage + "</body></html>"; UserPrefs latest = null; foreach (UserPrefs prefs in this.DataWorkspace.ApplicationData.UserPrefs) { if (null == prefs) { continue; } if (latest == null) latest = prefs; else if (latest.CreatedDate < prefs.CreatedDate) latest = prefs; } if (latest == null) { return; } else if (latest.MailAddress == null || latest.Password == null || latest.DisaplayName == null) { return; } // Create the MailHelper class created in the Server project. Emails new_entry = new Emails(); new_entry.Sender = latest.MailAddress; new_entry.Receiver = latest.DisaplayName; new_entry.Subject = strSubject; new_entry.Message = strMessage; new_entry.ReceiverMail = latest.MailAddress; }
protected void lnkbtnApprove_Click(object sender, EventArgs e) { lblinfo.Visible = false; standardstewardshipIds = System.Configuration.ConfigurationManager.AppSettings["StewardshipStandardIDs"]; OrganizationInfo o = new OrganizationInfo(OrganizationID); OrganizationInfo.SetStatus(OrganizationStatus.Accepted, OrganizationID, txtNotes.Text, o.OrganizationTypeId, standardstewardshipIds); DataSet ds = UserInfo.getDefaultUsers(OrganizationID); if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count>0) { UserInfo user = new UserInfo(Convert.ToInt32(ds.Tables[0].Rows[0]["UserId"].ToString())); if (!user.IsApproved) { Emails email = new Emails(); email.To = user.Login; email.URL = ConfigurationManager.AppSettings["EmailUrl"].ToString() + "ChangePassword.aspx?userId=" + Encryption.Encrypt(user.UserId.ToString()); email.From = "*****@*****.**"; email.Subject = "Registration Approval Email"; Thread Email_Thread = new Thread(() => SendEmails(email, Emails.EmailType.ApplicationApprovedEmail.ToString())); Email_Thread.Start(); } } Response.Redirect(pageId); lblinfo.Text = "Successfully Approved"; lblinfo.Visible = true; }
public int ValidateUpdateAccount(DtoAccount dto) { var id = dto.id; if (id == 17579) { } // validate first, starting from fastest checks, and only after the validation create an account if (id < 0 || id >= MAX_ACCOUNTS) { return(404); } // phone (if provided) contains area code if (dto.flags.HasFlag(DtoFlags.Phone) && dto.phone != null) { var openBrace = dto.phone.IndexOf('('); var closeBrace = dto.phone.IndexOf(')'); if (openBrace < 0 || closeBrace != openBrace + 4) { return(400); } } // joined within range if (dto.flags.HasFlag(DtoFlags.Joined) && (Utils.TimestampToDate(dto.joined) < MinJoined || Utils.TimestampToDate(dto.joined) > MaxJoined)) { return(400); } // premium if (dto.flags.HasFlag(DtoFlags.Premium)) { if (dto.premium.start > 0 && Utils.TimestampToDate(dto.premium.start) < MinPremium || dto.premium.finish > 0 && Utils.TimestampToDate(dto.premium.finish) < MinPremium) { return(400); } } // the rest requires locking bool lockTaken = false; try { updateLock.Enter(ref lockTaken); // check if the account exists if (!All[id]) { return(404); } // likes if (dto.flags.HasFlag(DtoFlags.Likes)) { if (!verifyLikes(dto.likes)) { return(400); } } var acct = Accounts[id]; // update email and domain if (dto.flags.HasFlag(DtoFlags.Email)) { if (dto.email.IsEmpty || dto.email.Length > 100) { return(400); } if (!bufferFromEmail(dto.email, out var intEmail)) { return(400); } // check for duplicates if (Emails.Contains(intEmail) && !ByteArrayComparer.Instance.Equals(acct.Email, intEmail)) { return(400); // such email exists and it's not ours } // unregister old email Domains[acct.GetDomainIdx()].Exclude(id); Emails.Remove(acct.Email); // store and register new email acct.Email = intEmail; Emails.Add(acct.Email); Domains[acct.GetDomainIdx()].Include(id); } // store new account info Accounts[id] = acct; } finally { if (lockTaken) { updateLock.Exit(); } } return(202); }
public void DeleteEmailById(Guid id) { Emails.Remove(this.SearchEmailById(id)); }
public virtual int FillBy(Emails.CustomerEmailsDataTable dataTable, int ID) { this.Adapter.SelectCommand = this.CommandCollection[1]; this.Adapter.SelectCommand.Parameters[0].Value = ((int)(ID)); if ((this.ClearBeforeFill == true)) { dataTable.Clear(); } int returnValue = this.Adapter.Fill(dataTable); return returnValue; }
public virtual int Fill(Emails.CustomerEmailsDataTable dataTable) { this.Adapter.SelectCommand = this.CommandCollection[0]; if ((this.ClearBeforeFill == true)) { dataTable.Clear(); } int returnValue = this.Adapter.Fill(dataTable); return returnValue; }
public override string ToString() { return($"{FirstName} {LastName} {MiddleName} {Emails.FirstOrDefault()} {Company}"); }
/// <summary> /// 发送更新邮箱确认邮件 /// </summary> public ActionResult SendUpdateEmail() { string v = WebHelper.GetQueryString("v"); //解密字符串 string realV = ShopUtils.AESDecrypt(v); //数组第一项为uid,第二项为动作,第三项为验证时间,第四项为随机值 string[] result = StringHelper.SplitString(realV); if (result.Length != 4) { return(AjaxResult("noauth", "您的权限不足")); } int uid = TypeHelper.StringToInt(result[0]); string action = result[1]; DateTime time = TypeHelper.StringToDateTime(result[2]); //判断当前用户是否为验证用户 if (uid != WorkContext.Uid) { return(AjaxResult("noauth", "您的权限不足")); } //判断验证时间是否过时 if (DateTime.Now.AddMinutes(-30) > time) { return(AjaxResult("expired", "密钥已过期,请重新验证")); } string email = WebHelper.GetFormString("email"); string verifyCode = WebHelper.GetFormString("verifyCode"); //检查验证码 if (string.IsNullOrWhiteSpace(verifyCode)) { return(AjaxResult("verifycode", "验证码不能为空")); } if (verifyCode.ToLower() != Sessions.GetValueString(WorkContext.Sid, "verifyCode")) { return(AjaxResult("verifycode", "验证码不正确")); } //检查邮箱 if (string.IsNullOrWhiteSpace(email)) { return(AjaxResult("email", "邮箱不能为空")); } if (!ValidateHelper.IsEmail(email)) { return(AjaxResult("email", "邮箱格式不正确")); } if (!SecureHelper.IsSafeSqlString(email, false)) { return(AjaxResult("email", "邮箱已经存在")); } int tempUid = Users.GetUidByEmail(email); if (tempUid > 0 && tempUid != WorkContext.Uid) { return(AjaxResult("email", "邮箱已经存在")); } string v2 = ShopUtils.AESEncrypt(string.Format("{0},{1},{2},{3}", WorkContext.Uid, email, DateTime.Now, Randoms.CreateRandomValue(6))); string url = string.Format("http://{0}{1}", Request.Url.Authority, Url.Action("updateemail", new RouteValueDictionary { { "v", v2 } })); //发送验证邮件 Emails.SendSCUpdateEmail(email, WorkContext.UserName, url); return(AjaxResult("success", "邮件已经发送,请前往你的邮箱进行验证")); }
private void DeleteOldEmails() { using (SqlCommand command = new SqlCommand("delete from Emails where Id not in (@IdList)")) { command.Parameters.Add(DataContext.CreateSqlParameter("@IdList", string.Join(",", Emails.Select(em => em.Id)))); DataContext.ExecuteNonQuery(command); } }
partial void Emails_Inserting(Emails entity) { if (entity.Message == null) { entity.Message = ""; } if (entity.Subject == null) { entity.Subject = ""; } UserPrefs latest = null; foreach (UserPrefs prefs in this.DataWorkspace.ApplicationData.UserPrefs) { if (null == prefs) { continue; } if (latest == null) latest = prefs; else if (latest.CreatedDate < prefs.CreatedDate) latest = prefs; } if (latest == null) { return; } else if (latest.MailAddress == null || latest.Password == null || latest.DisaplayName == null) { return; } MailHelper mailHelper = new MailHelper( latest.DisaplayName, entity.ReceiverMail, entity.Receiver, entity.Subject, entity.Message, latest); // Send Email mailHelper.SendMail(); }
public Pair <Guid, Pair <string, string> > SearchEmailById(Guid id) { return(Emails.Find(email => new Guid(email.Key.ToString()) == id)); }
public virtual int FillByCustomerId(Emails.CustomerEmailsDataTable dataTable, string CustomerID) { this.Adapter.SelectCommand = this.CommandCollection[2]; if ((CustomerID == null)) { this.Adapter.SelectCommand.Parameters[0].Value = global::System.DBNull.Value; } else { this.Adapter.SelectCommand.Parameters[0].Value = ((string)(CustomerID)); } if ((this.ClearBeforeFill == true)) { dataTable.Clear(); } int returnValue = this.Adapter.Fill(dataTable); return returnValue; }
protected override void Execute(NativeActivityContext context) { var folder = Folder.Get(context); var maxresults = MaxResults.Get(context); var filter = Filter.Get(context); if (string.IsNullOrEmpty(folder)) { return; } var outlookApplication = CreateOutlookInstance(); if (outlookApplication.ActiveExplorer() == null) { Log.Warning("Outlook not running!"); return; } MAPIFolder inBox = (MAPIFolder)outlookApplication.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox); MAPIFolder folderbase = inBox.Store.GetRootFolder(); MAPIFolder mfolder = GetFolder(folderbase, folder); Items Items = mfolder.Items; var unreadonly = UnreadOnly.Get(context); if (unreadonly) { if (string.IsNullOrEmpty(filter)) { filter = ""; } //if (!filter.ToLower().Contains("[unread]") && filter.ToLower().Contains("httpmail:read")) //{ if (string.IsNullOrEmpty(filter)) { filter = "[Unread]=true"; } else { filter += "and [Unread]=true"; } // } // var Filter = "@SQL=" + (char)34 + "urn:schemas:httpmail:hasattachment" + (char)34 + "=1 AND " + // var Filter = "@SQL=" + (char)34 + "urn:schemas:httpmail:read" + (char)34 + "=0"; } else { } if (!string.IsNullOrEmpty(filter)) { Items = Items.Restrict(filter); } var result = new List <email>(); foreach (var folderItem in Items) { MailItem mailItem = folderItem as MailItem; if (mailItem != null) { var _e = new email(mailItem); result.Add(_e); if (result.Count == maxresults) { break; } } } Emails.Set(context, result); IEnumerator <email> _enum = result.ToList().GetEnumerator(); context.SetValue(_elements, _enum); bool more = _enum.MoveNext(); if (more) { context.ScheduleAction(Body, _enum.Current, OnBodyComplete); } }
public virtual int Update(Emails.CustomerEmailsDataTable dataTable) { return this.Adapter.Update(dataTable); }
public void sendMail(string sender, string receiver, string strSubject, string strMessage, string receiverMail) { // Create the MailHelper class created in the Server project. Emails new_entry = new Emails(); new_entry.Sender = sender; new_entry.Receiver = receiver; new_entry.Subject = strSubject; new_entry.Message = strMessage; new_entry.ReceiverMail = receiverMail; }
public virtual int Update(Emails dataSet) { return this.Adapter.Update(dataSet, "CustomerEmails"); }
protected void submit_Click(object sender, EventArgs e) { if (Utils.IsNumeric(hdnOrganizationID.Value) == false) return; List<OrganizationInfo.Organization_Business> lstOrganizationBusiness = new List<OrganizationInfo.Organization_Business>(); //OrganizationInfo.Organization_Business objOrgBusiness; //foreach (RepeaterItem rptItem in rptBusiness.Items) //{ // objOrgBusiness = new OrganizationInfo.Organization_Business(); // CheckBox chkY = (CheckBox)rptItem.FindControl("chkY"); // CheckBox chkN = (CheckBox)rptItem.FindControl("chkN"); // if (chkY.Checked || chkN.Checked) // { // objOrgBusiness.BusinessID = Convert.ToInt32(((HiddenField)rptItem.FindControl("hdnID")).Value); // objOrgBusiness.IsNew = chkY.Checked; // lstOrganizationBusiness.Add(objOrgBusiness); // } //} //Commented by wajid shah 09-04-2013 int RoleId = Convert.ToInt32(UserInfo.UserRole.Stakeholder); //if (Convert.ToInt32(ddlOrganizationType.SelectedValue) == Convert.ToInt32(LookupsManagement.LookupType.OrganizationTypes_Stewardship)) //{ // RoleId = Convert.ToInt32(UserInfo.UserRole.Stewardship); //} //if (OrganizationInfo.SubmitApplication(Convert.ToInt32(hdnOrganizationID.Value), RoleId, Convert.ToInt32(ddlOrganizationType.SelectedValue), lstOrganizationBusiness, Convert.ToInt32(Request.QueryString["SSID"])) == true) ////end comment UserInfo objUserInfo = null; //if (ViewState["UserName"] != null && Convert.ToString(ViewState["UserName"]) == txtLoginName.Text.Trim()) //{ // ToolkitScriptManager.RegisterStartupScript(this, this.GetType(), "Step6", "GotoNextStep();", true); // return; //} //if (UserInfo.CheckLoginNameAvailable(txtLoginName.Text.Trim()) == true) // { objUserInfo = new UserInfo(); objUserInfo.OrganizationId = Convert.ToInt32(hdnOrganizationID.Value); objUserInfo.Login = ViewState["PrimaryEmail"].ToString();// txtLoginName.Text.Trim(); objUserInfo.Pwd = Encryption.Encrypt("000000"); objUserInfo.PwdSalt = String.Empty; objUserInfo.IsActive = true; objUserInfo.TX_UserId = String.Empty; objUserInfo.LanguageId = LanguageId; objUserInfo.TimeZoneID = 1; objUserInfo.ContactId = 1; objUserInfo.IsApproved = false; objUserInfo.IsOrgAdmin = true; objUserInfo.DateCreated = DateTime.Now; objUserInfo.RoleId = 0;// "Role ID select from stored Procedure" Conversion.ParseInt(ViewState["OrganizationTypeId"].ToString()); objUserInfo.bitSetPassword = false; UserInfo.CreateStakeholderUser(objUserInfo); Emails email = new Emails(); email.To = ViewState["PrimaryEmail"].ToString(); email.From = "*****@*****.**"; email.Subject = "Registration Submitted Email"; Thread Email_Thread = new Thread(() => SendEmails(email, Emails.EmailType.RegistrationSubmissionEmail.ToString())); Email_Thread.Start(); string standardstewardshipIds = System.Configuration.ConfigurationManager.AppSettings["StewardshipStandardIDs"]; if (OrganizationInfo.SubmitApplication(Convert.ToInt32(hdnOrganizationID.Value), Convert.ToInt32(ddlOrganizationType.SelectedValue), lstOrganizationBusiness, Convert.ToInt32(ViewState["StewardShipId"].ToString()), standardstewardshipIds) == true) ToolkitScriptManager.RegisterStartupScript(this, this.GetType(), "Thankyou", "ShowThankYou();", true); //OrganizationInfo org=new OrganizationInfo(Convert.ToInt32(hdnOrganizationID.Value)); //Emails email = new Emails(); //email.To = org.objSupplier.OwnerManagerEmail; //email.From = org.objSupplier.OwnerManagerEmail; //email.Subject = "Test It"; //email.CC = org.objSupplier.OwnerManagerEmail; //email.BCC = org.objSupplier.OwnerManagerEmail; }
public virtual int Fill(Emails.CustomerEmailsChangeLogsDataTable dataTable, int ID, global::System.Nullable<int> MAX_SequenceNumber_, global::System.Nullable<int> MAX_SequenceNumber_1, string ChangeUser) { this.Adapter.SelectCommand = this.CommandCollection[0]; this.Adapter.SelectCommand.Parameters[0].Value = ((int)(ID)); if ((MAX_SequenceNumber_.HasValue == true)) { this.Adapter.SelectCommand.Parameters[1].Value = ((int)(MAX_SequenceNumber_.Value)); } else { this.Adapter.SelectCommand.Parameters[1].Value = global::System.DBNull.Value; } if ((MAX_SequenceNumber_1.HasValue == true)) { this.Adapter.SelectCommand.Parameters[2].Value = ((int)(MAX_SequenceNumber_1.Value)); } else { this.Adapter.SelectCommand.Parameters[2].Value = global::System.DBNull.Value; } if ((ChangeUser == null)) { this.Adapter.SelectCommand.Parameters[3].Value = global::System.DBNull.Value; } else { this.Adapter.SelectCommand.Parameters[3].Value = ((string)(ChangeUser)); } if ((this.ClearBeforeFill == true)) { dataTable.Clear(); } int returnValue = this.Adapter.Fill(dataTable); return returnValue; }
protected void gvUserAdmin_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Approve") { UserInfo.ApproveAdminUser(Convert.ToInt32(e.CommandArgument)); UserInfo user = new UserInfo(Convert.ToInt32(e.CommandArgument)); if (!user.IsApproved) { Emails email = new Emails(); email.To = user.Login; email.URL = ConfigurationManager.AppSettings["EmailUrl"].ToString() + "ChangePassword.aspx?userId=" + Encryption.Encrypt(user.UserId.ToString()); email.From = "*****@*****.**"; email.Subject = "Registration Approval Email"; Thread Email_Thread = new Thread(() => SendEmails(email, Emails.EmailType.ApplicationApprovedEmail.ToString())); Email_Thread.Start(); } SearchAdminUsers(); } else if (e.CommandName == "DeleteUser") { UserInfo.DeleteAdminUser(Convert.ToInt32(e.CommandArgument)); SearchAdminUsers(); } else if (e.CommandName == "DisApprove") { UserInfo.DisApproveAdminUser(Convert.ToInt32(e.CommandArgument)); SearchAdminUsers(); } else if (e.CommandName == "UserInfo") { // ScriptManager.RegisterStartupScript(this, GetType(), "DataInfo", "ShowUserInfo();", true); ViewUserInfo(Convert.ToInt32(e.CommandArgument)); //SearchAdminUsers(); ScriptManager.RegisterStartupScript(this, GetType(), "DataInfo", "ShowUserInfo();", true); } }
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { Emails ds = new Emails(); global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); any.Namespace = ds.Namespace; sequence.Items.Add(any); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte())); ) { ; } if ((s1.Position == s1.Length)) { return type; } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return type; }
partial void SendMails_Execute() { this.FindControl("SendingMessage").ControlAvailable += PostsListDetail_ControlAvailable; Email = new Emails(); Boolean isEmpty = true; string receiver = "", receiverMail = ""; foreach (Partners friend in this.PartnersGroups.SelectedItem.Partner) { if (friend.Email == null || friend.Email == "" || !friend.Email.Contains('@')) continue; isEmpty = false; receiver += friend.FirstName + " " + friend.LastName + ", "; receiverMail += friend.Email + ", "; } if (isEmpty) { this.ShowMessageBox("אין נמענים בקבוצה"); return; } receiver = receiver.Substring(0, receiver.Length - 2); receiverMail = receiverMail.Substring(0, receiverMail.Length - 2); Email.Receiver = receiver; Email.ReceiverMail = receiverMail; Email.Sender = "me"; this.OpenModalWindow("SendingMessage"); }
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); Emails ds = new Emails(); global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); any1.Namespace = "http://www.w3.org/2001/XMLSchema"; any1.MinOccurs = new decimal(0); any1.MaxOccurs = decimal.MaxValue; any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any1); global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; any2.MinOccurs = new decimal(1); any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute1.Name = "namespace"; attribute1.FixedValue = ds.Namespace; type.Attributes.Add(attribute1); global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute2.Name = "tableTypeName"; attribute2.FixedValue = "CustomerEmailsChangeLogsDataTable"; type.Attributes.Add(attribute2); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte())); ) { ; } if ((s1.Position == s1.Length)) { return type; } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return type; }
// A method that accepts a subscriber method that must follow the PromotionSender delegate // It also takes the email of the subscriber // This subscriber expects to get a promotion each time the market sends one public void SubscribeForPromotion(PromotionSender subscriber, string email) { PromotionEvent += subscriber; Emails.Add(email); }
//protected void RGVSMSSent_SortCommand(object sender, GridSortCommandEventArgs e) //{ // this.RGVSMSSent.MasterTableView.AllowNaturalSort = true; // this.RGVSMSSent.MasterTableView.Rebind(); //} //protected void RGVSMSSent_NeedDataSource(object sender, GridNeedDataSourceEventArgs e) //{ // GlobalGridBind(); //} //private void StudentSent_SMS() //{ // DataTable dtStudentLeadSMSSent = new DataTable(); // dtStudentLeadSMSSent = DataAccessManager.GetSMSSentStd(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"])); // Session["dtStudentLeadSMSSent"] = dtStudentLeadSMSSent; // RGVSMSSent.DataSource = (DataTable)Session["dtStudentLeadSMSSent"]; //} //private void LeadSent_SMS() //{ // DataTable dtStudentLeadSMSSent = new DataTable(); // dtStudentLeadSMSSent = DataAccessManager.GetSMSSentLead(Convert.ToString(Session["LeadId"]), Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"])); // Session["dtStudentLeadSMSSent"] = dtStudentLeadSMSSent; // RGVSMSSent.DataSource = (DataTable)Session["dtStudentLeadSMSSent"]; //} //protected void RGVSMSSent_PageIndexChanged(object sender, GridPageChangedEventArgs e) //{ // try // { // RGVSMSSent.DataSource = (DataTable)Session["dtStudentLeadSMSSent"]; // } // catch (Exception ex) // { // } //} #endregion public void fetchmail(string DeptID, int CampusID) { try { DataTable dtEmailConfig = DataAccessManager.GetEmailConfigDetail(DeptID, CampusID); if (dtEmailConfig.Rows.Count > 0) { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(dtEmailConfig.Rows[0]["Pop3"].ToString(), Convert.ToInt32(dtEmailConfig.Rows[0]["PortIn"]), Convert.ToBoolean(dtEmailConfig.Rows[0]["SSL"])); pop3Client.Authenticate(dtEmailConfig.Rows[0]["DeptEmail"].ToString(), dtEmailConfig.Rows[0]["Pass"].ToString(), AuthenticationMethod.UsernameAndPassword); if (pop3Client.Connected) { int count = pop3Client.GetMessageCount(); int progressstepno; if (count == 0) { } else { progressstepno = 100 - count; this.Emails = new List <Email>(); for (int i = 1; i <= count; i++) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); Email email = new Email() { MessageNumber = i, messageId = message.Headers.MessageId, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } email.IsAttached = false; this.Emails.Add(email); //Attachment Process List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.IsAttached = true; string FolderName = string.Empty; FolderName = Convert.ToString(Session["CampusName"]); String path = Server.MapPath("~/InboxAttachment/" + FolderName); if (!Directory.Exists(path)) { // Try to create the directory. DirectoryInfo di = Directory.CreateDirectory(path); } string ext = attachment.FileName.Split('.')[1]; // FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\") + attachment.FileName.ToString()); FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\" + FolderName + "\\") + attachment.FileName.ToString()); attachment.SaveToFile(file); Attachment att = new Attachment(); att.messageId = message.Headers.MessageId; att.FileName = attachment.FileName; attItem.Add(att); } //System.Threading.Thread.Sleep(500); } //Insert into database Inbox table DataTable dtStudentNo = new DataTable(); bool IsReadAndSave = false; foreach (var ReadItem in Emails) { string from = string.Empty, subj = string.Empty, messId = string.Empty, Ebody = string.Empty; from = Convert.ToString(ReadItem.From); subj = Convert.ToString(ReadItem.Subject); messId = Convert.ToString(ReadItem.messageId); Ebody = Convert.ToString(ReadItem.Body); if (Ebody != string.Empty && Ebody != null) { Ebody = Ebody.Replace("'", " "); } DateTime date = ReadItem.DateSent; bool IsAtta = ReadItem.IsAttached; //Student Email if (Source.SOrL(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["leadID"]))) { dtStudentNo = DyDataAccessManager.GetStudentNo(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase(dtStudentNo.Rows[0]["StudentNo"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } //Leads Email if (Source.SOrL(Convert.ToString(Session["ParamStudentNo"]), Convert.ToString(Session["ParamleadID"])) == false) { dtStudentNo = DyDataAccessManager.GetLeadsID(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead(dtStudentNo.Rows[0]["LeadsID"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } // } //Insert into database Attachment table foreach (var attachItem in attItem) { bool success; string Filname = attachItem.FileName; string MssID = attachItem.messageId; success = DataAccessManager.ReadEmailAttachmentAndSaveDatabase(MssID, Filname); } Emails.Clear(); // attItem.Clear(); pop3Client.DeleteAllMessages(); //StartNotification(count); } } pop3Client.Disconnect(); } } catch (Exception ex) { } }
public override string ToString() { return(string.Format("[Contact: Identifier={0}, NamePrefix={1}, GivenName={2}, MiddleName={3}, FamilyName={4}, PreviousFamilyName={5}, NameSuffix={6}, Nickname={7}, OrganizationName={8}, DepartmentName={9}, JobTitle={10}, PhoneticGivenName={11}, PhoneticMiddleName={12}, PhoneticFamilyName={13}, PhoneticOrganizationName={14}, Note={15}, Birthday={16}, PhoneNumbers={17}, Emails={18}, PostalAddresses={19}, Urls={20}, Relations={21}, SocialProfiles={22}, InstantMessageAddresses={23}, Dates={24}]", Identifier, NamePrefix, GivenName, MiddleName, FamilyName, PreviousFamilyName, NameSuffix, Nickname, OrganizationName, DepartmentName, JobTitle, PhoneticGivenName, PhoneticMiddleName, PhoneticFamilyName, PhoneticOrganizationName, Note, Birthday, PhoneNumbers.ToStringList(), Emails.ToStringList(), PostalAddresses.ToStringList(), Urls.ToStringList(), Relations.ToStringList(), SocialProfiles.ToStringList(), InstantMessageAddresses.ToStringList(), Dates.ToStringList())); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="emailaddress"></param> /// <param name="authstr"></param> private void SendEmail(string username, string password, string emailaddress, string authstr) { Emails.DiscuzSmtpMail(username, emailaddress, password, authstr); }
public async Task <IActionResult> ResetPassword([FromBody] LoginViewModel l) { IActionResult res = null; var _b = new BaseEntityDTO <string>() { Start = DateTime.Now }; try { var existUser = await _userManager.FindByEmailAsync(l.Email); if (existUser == null) { throw new Exception($"{l.Email} não encontrado"); } if (!existUser.LockoutEnabled) { throw new Exception("Usuário inativo no sistema"); } l.Username = existUser.UserName; //existUser.Email = "*****@*****.**"; //tokenResponse.AccessToken string senha = Uteis.GeraSenha(); var guid = Guid.NewGuid().ToString(); await repository.Add(new UsersResetPasswordModel[] { new UsersResetPasswordModel() { Token = guid, SenhaTrocada = false, LoginUser = l.Username } }, ClienteID, UsuarioID); // existUser.Email = "*****@*****.**"; await Util.SendEmailAsync( new EmailViewModel[] { new EmailViewModel(existUser.Email) }, "Senha zerada", Emails.RedefinicaoSenha($"{Util.Configuration["UrlIdentity"]}redefine-senha/{guid}"), true, TipoEmail.RESETSENHA); _b.Result = $"Email encaminhado pra {l.Email} com o link pra reset da senha"; _b.End = DateTime.Now; _b.Itens = 1; res = Ok(_b); } catch (Exception err) { _b.End = DateTime.Now; _b.Error = (err.InnerException ?? err).Message; res = BadRequest(_b); } return(res); }
public void AddToEmails(Emails emails) { base.AddObject("Emails", emails); }
public void AddEmail(Pair <Guid, Pair <string, string> > email) { Emails.Add(email); }
public static Emails CreateEmails(int ID, string sender, string receiver, string receiverMail, byte[] rowVersion) { Emails emails = new Emails(); emails.Id = ID; emails.Sender = sender; emails.Receiver = receiver; emails.ReceiverMail = receiverMail; emails.RowVersion = rowVersion; return emails; }
protected override void OnPreRender(EventArgs e) { int idCurrency = 1; int.TryParse(rblMena.SelectedValue, out idCurrency); var currency = _dropDownData.Currencies.First(x => x.Id == idCurrency); lblMena.Text = currency.Name; var now = DateTime.UtcNow; foreach (var item in _dropDownData.Poplatky) { item.CostString = currency.FormatMoney(item.Amount); item.CssClass = (item.From ?? now) <= now && now <= (item.To ?? now) ? "currentFee" : ""; } gridPoplatky.DataSource = _dropDownData.Poplatky.Where(x => x.Online); gridPoplatky.DataBind(); gridPoplatkyNaMieste.DataSource = _dropDownData.Poplatky.Where(x => !x.Online); gridPoplatkyNaMieste.DataBind(); float sum = 0; bool valid = true; for (int i = 0; i < _data.Count; i++) { _data[i] = _controls[i].Data; _data[i].Id = _indices[i]; _tabPanels[i].HeaderText = _data[i].Title; _controls[i].Currency = currency; _data[i].Currency = currency; _data[i].Single = _data.Count == 1; _controls[i].Single = _data.Count == 1; var cost = _data[i].GetCost(_dropDownData.Sluziaci, _dropDownData.Poplatky); sum += cost; _data[i].CostString = currency.FormatMoney(cost); valid = valid && _data[i].Valid; } trPayerEmail.Visible = _data.Count > 1; txtEmail.CssClass = ""; if (_data.Count > 1 && !Common.ValidateEmail(txtEmail.Text.Trim())) { valid = false; txtEmail.CssClass = "errorBorder"; } var payerEmail = _data.Count > 1 ? txtEmail.Text.Trim().ToLower() : _data[0].Email.Trim().ToLower(); txtCaptcha.CssClass = ""; if (txtCaptcha.Text != "") { valid = false; txtCaptcha.CssClass = "errorBorder"; } float sponzorskyDar = 0; txtDar.CssClass = ""; if (!string.IsNullOrWhiteSpace(txtDar.Text)) { if (!float.TryParse(txtDar.Text, out sponzorskyDar)) { txtDar.CssClass = "errorBorder"; valid = false; } if (sponzorskyDar < 0) { sponzorskyDar = 0; } } var amountToPay = sum + sponzorskyDar / currency.Rate; lblSuma.Text = currency.FormatMoney(amountToPay); if (!chbGdprConsent.Checked) { valid = false; } lblGdprMissing.Visible = !chbGdprConsent.Checked; // check for duplicate emails var emailHash = new Dictionary <string, int>(); foreach (var item in _data) { var email = item.Email.Trim().ToLower(); if (string.IsNullOrWhiteSpace(email)) { continue; } emailHash[email] = emailHash.ContainsKey(email) ? emailHash[email] + 1 : 1; } foreach (var item in emailHash) { if (item.Value > 1) { valid = false; for (int i = 0; i < _data.Count; i++) { if (_data[i].Email.Trim().ToLower() == item.Key) { _data[i].Errors.Add(Common.ChybaEmailSaOpakuje); } } } } lblResult.Text = ""; if (valid && _registerClicked) { try { var emails = new List <Email>(); if (_data.Count == 1) { emails.Add(new Email(payerEmail, Emails.RegistrationSubject, Emails.GetSingle(_data[0], amountToPay, currency))); } else { var payerIsRegistered = false; for (var i = 0; i < _data.Count; i++) { _data[i].Email = _data[i].Email.Trim().ToLower(); if (payerEmail == _data[i].Email) { payerIsRegistered = true; emails.Add(new Email(payerEmail, Emails.RegistrationSubject, Emails.GetMultiplePayerRegistered(_data, i, amountToPay, currency))); } else { emails.Add(new Email(_data[i].Email, Emails.RegistrationSubject, Emails.GetMultiple(_data[i], payerEmail))); } } if (!payerIsRegistered) { emails.Add(new Email(payerEmail, Emails.RegistrationSubject, Emails.GetMultiplePayerNotRegistered(_data, amountToPay, currency, payerEmail))); } } // write to database var data = Database.WriteData(_data, emails, payerEmail, sponzorskyDar, currency); if (data.Success) { _success = true; } else { // there are bad emails valid = false; foreach (var item in data.AlreadyRegisteredEmails) { for (int i = 0; i < _data.Count; i++) { if (_data[i].Email.Trim().ToLower() == item.Trim().ToLower()) { _data[i].Errors.Add(Common.ChybaEmailUzZaregistrovany); } } } } } catch (Exception ex) { lblResult.Text = ex.Message + " " + ex.InnerException; } } gridSummary.DataSource = _data; gridSummary.DataBind(); pnlRegistration.Visible = !_success && !pnlRegistrationDone.Visible; pnlSuccess.Visible = _success && !pnlRegistrationDone.Visible; base.OnPreRender(e); }
public HttpResponseMessage InserirPf(HttpRequestMessage request, MembroPFViewModel membroPFViewModel) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { if (_membroRep.CpfExistente(membroPFViewModel.Cpf) > 0) { ModelState.AddModelError("CPF Existente", "CPF:" + membroPFViewModel.Cpf + " já existe ."); response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else if (_membroRep.CroExistente(membroPFViewModel.Cro) > 0) { ModelState.AddModelError("CRO Existente", "CRO:" + membroPFViewModel.Cro + " já existe ."); response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { var usuario = _usuarioRep.GetSingle(1); var pessoa = new Pessoa { UsuarioCriacao = usuario, DtCriacao = DateTime.Now, TipoPessoa = TipoPessoa.PessoaFisica, Ativo = membroPFViewModel.Ativo, }; var pessoaFisica = new PessoaFisica { UsuarioCriacao = usuario, DtCriacao = DateTime.Now, Pessoa = pessoa, Nome = membroPFViewModel.Nome, Cpf = membroPFViewModel.Cpf, Rg = membroPFViewModel.Rg, Cro = membroPFViewModel.Cro, DtNascimento = membroPFViewModel.DtNascimento, Email = membroPFViewModel.Email, Sexo = (Sexo)membroPFViewModel.Sexo, Ativo = membroPFViewModel.Ativo }; _pessoaFisicaRep.Add(pessoaFisica); _unitOfWork.Commit(); pessoa.PessoaFisica = pessoaFisica; _pessoaRep.Edit(pessoa); _unitOfWork.Commit(); var novoMembro = new Membro { UsuarioCriacao = usuario, DtCriacao = DateTime.Now, Pessoa = pessoa, Comprador = membroPFViewModel.Comprador, Ativo = membroPFViewModel.Ativo, Vip = membroPFViewModel.Vip, DddTel = membroPFViewModel.DddTelComl, Telefone = membroPFViewModel.TelefoneComl, DddCel = membroPFViewModel.DddCel, Celular = membroPFViewModel.Celular, Contato = membroPFViewModel.Contato, DataFimPeriodoGratuito = DateTime.Now.AddDays(30) }; _membroRep.Add(novoMembro); _unitOfWork.Commit(); var email = new Emails { UsuarioCriacao = usuario, DtCriacao = DateTime.Now, AssuntoEmail = "Novo Membro Cliente PF", EmailDestinatario = "*****@*****.**", CorpoEmail = "NOVO CLIENTE", Status = Status.NaoEnviado, Origem = 0, Ativo = true }; _emailsRep.Add(email); _unitOfWork.Commit(); // Update view model membroPFViewModel = Mapper.Map <Membro, MembroPFViewModel>(novoMembro); response = request.CreateResponse(HttpStatusCode.Created, membroPFViewModel); } } return response; })); }
public void SendEmail(string name, string emailAddress, string subject, string body) { Emails.Add(new ReceivedEmail { EmailAddress = emailAddress, Subject = subject, Body = body }); }
public HttpResponseMessage Inserir(HttpRequestMessage request, MembroViewModel membroViewModel) { membroViewModel.Cnpj = membroViewModel.Cnpj.Replace('.', ' ').Replace('/', ' ').Replace('-', ' '); return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { if (_membroRep.CnpjExistente(membroViewModel.Cnpj) > 0) { ModelState.AddModelError("CNPJ Existente", "CNPJ:" + membroViewModel.Cnpj + " já existe ."); response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { var usuario = _usuarioRep.GetSingle(1); var pessoa = new Pessoa { UsuarioCriacao = usuario, DtCriacao = DateTime.Now, TipoPessoa = TipoPessoa.PessoaJuridica, Ativo = membroViewModel.Ativo, }; var pessoaJuridica = new PessoaJuridica { UsuarioCriacao = usuario, DtCriacao = DateTime.Now, Pessoa = pessoa, NomeFantasia = membroViewModel.NomeFantasia, Cnpj = membroViewModel.Cnpj, RazaoSocial = membroViewModel.RazaoSocial, DtFundacao = membroViewModel.DtFundacao, Email = membroViewModel.Email, InscEstadual = membroViewModel.InscEstadual, Ativo = membroViewModel.Ativo }; _pessoaJuridicaRep.Add(pessoaJuridica); _unitOfWork.Commit(); pessoa.PessoaJuridica = pessoaJuridica; _pessoaRep.Edit(pessoa); _unitOfWork.Commit(); var novoMembro = new Membro { UsuarioCriacao = usuario, DtCriacao = DateTime.Now, Pessoa = pessoa, Comprador = membroViewModel.Comprador, Ativo = membroViewModel.Ativo, Vip = membroViewModel.Vip, DddTel = membroViewModel.DddTelComl, Telefone = membroViewModel.TelefoneComl, DddCel = membroViewModel.DddCel, Celular = membroViewModel.Celular, Contato = membroViewModel.Contato, FranquiaId = membroViewModel.FranquiaId, DataFimPeriodoGratuito = DateTime.Now.AddDays(30) }; _membroRep.Add(novoMembro); _unitOfWork.Commit(); var email = new Emails { UsuarioCriacao = usuario, DtCriacao = DateTime.Now, AssuntoEmail = "Novo Membro Cliente PJ", EmailDestinatario = "*****@*****.**", CorpoEmail = "NOVO CLIENTE", Status = Status.NaoEnviado, Origem = 0, Ativo = true }; _emailsRep.Add(email); _unitOfWork.Commit(); // Update view model membroViewModel = Mapper.Map <Membro, MembroViewModel>(novoMembro); response = request.CreateResponse(HttpStatusCode.Created, membroViewModel); } } return response; })); }
/// <summary> /// 注册 /// </summary> public ActionResult Register() { string returnUrl = WebHelper.GetQueryString("returnUrl"); if (returnUrl.Length == 0) { returnUrl = "/"; } if (WorkContext.MallConfig.RegType.Length == 0) { return(PromptView(returnUrl, "商城目前已经关闭注册功能!")); } if (WorkContext.Uid > 0) { return(PromptView(returnUrl, "你已经是本商城的注册用户,无需再注册!")); } if (WorkContext.MallConfig.RegTimeSpan > 0) { DateTime registerTime = Users.GetRegisterTimeByRegisterIP(WorkContext.IP); if ((DateTime.Now - registerTime).Minutes <= WorkContext.MallConfig.RegTimeSpan) { return(PromptView(returnUrl, "你注册太频繁,请间隔一定时间后再注册!")); } } //get请求 if (WebHelper.IsGet()) { RegisterModel model = new RegisterModel(); model.ReturnUrl = returnUrl; model.ShadowName = WorkContext.MallConfig.ShadowName; model.IsVerifyCode = CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages); return(View(model)); } //ajax请求 string accountName = WebHelper.GetFormString(WorkContext.MallConfig.ShadowName).Trim().ToLower(); string password = WebHelper.GetFormString("password"); string confirmPwd = WebHelper.GetFormString("confirmPwd"); string verifyCode = WebHelper.GetFormString("verifyCode"); StringBuilder errorList = new StringBuilder("["); #region 验证 //账号验证 if (string.IsNullOrWhiteSpace(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不能为空", "}"); } else if (accountName.Length < 4 || accountName.Length > 50) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名必须大于3且不大于50个字符", "}"); } else if (accountName.Contains(" ")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含空格", "}"); } else if (accountName.Contains(":")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含冒号", "}"); } else if (accountName.Contains("<")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含'<'符号", "}"); } else if (accountName.Contains(">")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含'>'符号", "}"); } else if ((!SecureHelper.IsSafeSqlString(accountName, false))) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不符合系统要求", "}"); } else if (CommonHelper.IsInArray(accountName, WorkContext.MallConfig.ReservedName, "\n")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "此账户名不允许被注册", "}"); } else if (FilterWords.IsContainWords(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名包含禁止单词", "}"); } //密码验证 if (string.IsNullOrWhiteSpace(password)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码不能为空", "}"); } else if (password.Length < 4 || password.Length > 32) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码必须大于3且不大于32个字符", "}"); } else if (password != confirmPwd) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "两次输入的密码不一样", "}"); } //验证码验证 if (CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages)) { if (string.IsNullOrWhiteSpace(verifyCode)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不能为空", "}"); } else if (verifyCode.ToLower() != Sessions.GetValueString(WorkContext.Sid, "verifyCode")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不正确", "}"); } } //其它验证 int gender = WebHelper.GetFormInt("gender"); if (gender < 0 || gender > 2) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "gender", "请选择正确的性别", "}"); } string nickName = WebHelper.GetFormString("nickName"); if (nickName.Length > 10) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "nickName", "昵称的长度不能大于10", "}"); } else if (FilterWords.IsContainWords(nickName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "nickName", "昵称中包含禁止单词", "}"); } if (WebHelper.GetFormString("realName").Length > 5) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "realName", "真实姓名的长度不能大于5", "}"); } string bday = WebHelper.GetFormString("bday"); if (bday.Length == 0) { string bdayY = WebHelper.GetFormString("bdayY"); string bdayM = WebHelper.GetFormString("bdayM"); string bdayD = WebHelper.GetFormString("bdayD"); bday = string.Format("{0}-{1}-{2}", bdayY, bdayM, bdayD); } if (bday.Length > 0 && bday != "--" && !ValidateHelper.IsDate(bday)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "bday", "请选择正确的日期", "}"); } string idCard = WebHelper.GetFormString("idCard"); if (idCard.Length > 0 && !ValidateHelper.IsIdCard(idCard)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "idCard", "请输入正确的身份证号", "}"); } int regionId = WebHelper.GetFormInt("regionId"); if (regionId > 0) { if (Regions.GetRegionById(regionId) == null) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "regionId", "请选择正确的地址", "}"); } if (WebHelper.GetFormString("address").Length > 75) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "address", "详细地址的长度不能大于75", "}"); } } if (WebHelper.GetFormString("bio").Length > 150) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "bio", "简介的长度不能大于150", "}"); } //当以上验证都通过时 UserInfo userInfo = null; if (errorList.Length == 1) { if (ValidateHelper.IsEmail(accountName))//验证邮箱 { if (!WorkContext.MallConfig.RegType.Contains("2")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用邮箱注册", "}"); } else { string emailProvider = CommonHelper.GetEmailProvider(accountName); if (WorkContext.MallConfig.AllowEmailProvider.Length != 0 && (!CommonHelper.IsInArray(emailProvider, WorkContext.MallConfig.AllowEmailProvider, "\n"))) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用'" + emailProvider + "'类型的邮箱", "}"); } else if (CommonHelper.IsInArray(emailProvider, WorkContext.MallConfig.BanEmailProvider, "\n")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用'" + emailProvider + "'类型的邮箱", "}"); } else if (Users.IsExistEmail(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "邮箱已经存在", "}"); } else { userInfo = new UserInfo(); userInfo.UserName = string.Empty; userInfo.Email = accountName; userInfo.Mobile = string.Empty; } } } else if (ValidateHelper.IsMobile(accountName))//验证手机 { if (!WorkContext.MallConfig.RegType.Contains("3")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用手机注册", "}"); } else if (Users.IsExistMobile(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "手机号已经存在", "}"); } else { userInfo = new UserInfo(); userInfo.UserName = string.Empty; userInfo.Email = string.Empty; userInfo.Mobile = accountName; } } else//验证用户名 { if (!WorkContext.MallConfig.RegType.Contains("1")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用用户名注册", "}"); } else if (accountName.Length > 20) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名长度不能超过20个字符", "}"); } else if (BrnMall.Services.Users.IsExistUserName(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名已经存在", "}"); } else { userInfo = new UserInfo(); userInfo.UserName = accountName; userInfo.Email = string.Empty; userInfo.Mobile = string.Empty; } } } #endregion if (errorList.Length > 1)//验证失败 { return(AjaxResult("error", errorList.Remove(errorList.Length - 1, 1).Append("]").ToString(), true)); } else//验证成功 { #region 绑定用户信息 userInfo.Salt = Randoms.CreateRandomValue(6); userInfo.Password = Users.CreateUserPassword(password, userInfo.Salt); userInfo.UserRid = UserRanks.GetLowestUserRank().UserRid; userInfo.StoreId = 0; userInfo.MallAGid = 1;//非管理员组 if (nickName.Length > 0) { userInfo.NickName = WebHelper.HtmlEncode(nickName); } else { userInfo.NickName = "bma" + Randoms.CreateRandomValue(7); } userInfo.Avatar = ""; userInfo.PayCredits = 0; userInfo.RankCredits = 0; userInfo.VerifyEmail = 0; userInfo.VerifyMobile = 0; userInfo.LastVisitIP = WorkContext.IP; userInfo.LastVisitRgId = WorkContext.RegionId; userInfo.LastVisitTime = DateTime.Now; userInfo.RegisterIP = WorkContext.IP; userInfo.RegisterRgId = WorkContext.RegionId; userInfo.RegisterTime = DateTime.Now; userInfo.Gender = WebHelper.GetFormInt("gender"); userInfo.RealName = WebHelper.HtmlEncode(WebHelper.GetFormString("realName")); userInfo.Bday = bday.Length > 0 ? TypeHelper.StringToDateTime(bday) : new DateTime(1900, 1, 1); userInfo.IdCard = WebHelper.GetFormString("idCard"); userInfo.RegionId = WebHelper.GetFormInt("regionId"); userInfo.Address = WebHelper.HtmlEncode(WebHelper.GetFormString("address")); userInfo.Bio = WebHelper.HtmlEncode(WebHelper.GetFormString("bio")); #endregion //创建用户 userInfo.Uid = Users.CreateUser(userInfo); //添加用户失败 if (userInfo.Uid < 1) { return(AjaxResult("exception", "创建用户失败,请联系管理员")); } //发放注册积分 Credits.SendRegisterCredits(ref userInfo, DateTime.Now); //更新购物车中用户id Carts.UpdateCartUidBySid(userInfo.Uid, WorkContext.Sid); //将用户信息写入cookie MallUtils.SetUserCookie(userInfo, 0); //发送注册欢迎信息 if (WorkContext.MallConfig.IsWebcomeMsg == 1) { if (userInfo.Email.Length > 0) { Emails.SendWebcomeEmail(userInfo.Email); } if (userInfo.Mobile.Length > 0) { SMSes.SendWebcomeSMS(userInfo.Mobile); } } //同步上下文 WorkContext.Uid = userInfo.Uid; WorkContext.UserName = userInfo.UserName; WorkContext.UserEmail = userInfo.Email; WorkContext.UserMobile = userInfo.Mobile; WorkContext.NickName = userInfo.NickName; return(AjaxResult("success", "注册成功")); } }
public void SubscribeForPromotion(string email, PromotionDelegate subscriber) { Promotions += subscriber; Emails.Add(email); }
public int CreateEmail(Emails email) => throw new NotImplementedException();
public override int GetHashCode() { return(-528980569 + PhoneNumbers.GetHashCode() + Emails.GetHashCode()); }
private void SendMail(string email,string comment) { string strMessage = "<html><body>" + "<font size=4>" + "<p align=\"right\">" + ".מדריך יקר, שובצה עבורך פעילות" + "</p>" + "<p align=\"right\">" + "<u>" + "<b>" + "פרטי הפעילות" + "</u>" + "</b>" + "</p>"; if (this.Activity.Summary != null) { strMessage += "<p align=\"right\">" + "<u>" + "תאריך: " + "</u>" + this.Activity.Summary + "</p>" + "<p align=\"right\">" + "<u>" + "יום: " + "</u>" + this.Activity.DayInWeek + "</p>"; } if (this.Activity.ActivityType != null) { strMessage += "<p align=\"right\">" + "<u>" + "סוג פעילות: " + "</u>" + this.Activity.ActivityType.ToString() + "</p>"; } if (this.Activity.FullTopicTitle != null) { strMessage+= "<p align=\"right\">" + "<u>" + "נושא: " + "</u>" + this.Activity.FullTopicTitle.ToString() + "</p>" ; } if (this.Activity.SchoolPart != null) { strMessage += "<p align=\"right\">" + "<u>" + "בית ספר: " + "</u>" + this.Activity.SchoolPart.ToString() + "</p>" + "<p align=\"right\">" + "<u>" + "עיר: " + "</u>" + this.Activity.ActivityPlace.ToString() + "</p>" ; } if (this.Activity.SchoolPart.SchoolMapLink != null) { strMessage += "<p align=\"right\">" + "<u>" + ":קישור למפת מיקום בית הספר " + "</u>" + "</p>"; strMessage += "<p align=\"right\">" + this.Activity.SchoolPart.SchoolMapLink + "</p>"; } if (this.Activity.StartTime !=null && this.Activity.EndTime != null) { strMessage+= "<p align=\"right\">" + "<u>" + "בין השעות: " + "</u>" + this.Activity.StartTimeToShow.Substring(0,5) + " - " + this.Activity.EndTimeToShow.Substring(0, 5) + "</p>"; } string roundsInfo = null; for (int i = 0; i < this.Activity.NumberOfRounds; i++) { Round round = this.Activity.Rounds.ElementAt<Round>(i); if (round.StartTime == null || round.StopTime == null) { roundsInfo = null; break; } roundsInfo += "<p align=\"right\">" + "סבב מספר " + (i + 1) + " בין השעות " + round.Start_Stop + "</p>"; } if (roundsInfo != null) { strMessage += "<p align=\"right\">" + "<u>" + ":סבבי פעילות" + "</u>" + roundsInfo + "</p>"; } if (comment != null && !comment.Equals("")) { strMessage += "<p align=\"right\">" + "<u>" + "הערות: " + "</u>" + comment +"</p>"; } strMessage += "<p align=\"right\">" + "<u>" + ":קישור לאתר השיבוץ " + "</u>" + "</p>"; strMessage += "<p align=\"right\">" + "http://binyamin.info/binyamin/" + "</p>"; string strSubject = "אל עמי - הודעה בדבר שיבוץ לפעילות"; string strFrom = "*****@*****.**"; // Create the MailHelper class created in the Server project. Emails new_entry = new Emails(); new_entry.Sender = strFrom; new_entry.Receiver = "EL-AMI"; new_entry.Subject = strSubject; new_entry.ReceiverMail = email; new_entry.Message = strMessage; this.DataWorkspace.ApplicationData.SaveChanges(); //this.ShowMessageBox(strMessage); }
/// <summary> /// Handles the Submit button-click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void SubmitBtn_Click(object sender, EventArgs e) { string message = ""; bool isValid = validate(); // If invalid/incomplete data exists, alert the user to the problem, // redirect them to the right location, and don't attempt to save // or submit the module. (we don't save because duplicate items may // be the cause of invalid data, and the DB can't handle duplicates) if (!isValid) { ErrorMessage.Text = "Some required items are missing or invalid. " + "Please review the following fields before attempting to submit again."; // Now we should find where the first error is and redirect the // user to that upload step if (!(TitleValidator.IsValid && AbstractValidator.IsValid && CategoriesControl1.validate())) { UploadStep = 0; } else if (!AuthorsControl1.validate()) { UploadStep = 1; } else if (!(PrerequisitesControl1.validate() && ObjectivesControl1.validate() && TopicsControl1.validate())) { UploadStep = 2; } else if (!(MaterialsControl1.validate() && ResourcesControl1.validate())) { UploadStep = 3; } else if (!(SeeAlsoControl1.validate() && CheckInValidator.IsValid)) { UploadStep = 4; } else { ErrorMessage.Text = "Could not locate problem."; UploadStep = 4; } StepLbl.Text = "" + (UploadStep + 1); toggleButtonsAndPanels(UploadStep); NextBtn.CausesValidation = true; return; } // If the module was valid, save it and submit it for approval. // (if an admin is submitting, it doesn't need approval) try { ModuleStatus status; Modules.ModuleInfo module; if ((User.Identity.IsAuthenticated && User.IsInRole(UserRole.Admin.ToString()))) { status = ModuleStatus.Approved; module = saveModule(status); ModulesControl.approveModule(module.Id); } else { status = ModuleStatus.PendingApproval; module = saveModule(status); // Send a Module Approval notification to the editors Email email = Emails.getEmail(EmailType.ApproveModule); Emails.formatEmail(email, User.Identity.Name, module.Id); MailMessage msg = Emails.constructEditorsMail(email, Globals.AdminsEmail); SmtpMail.SmtpServer = AspNetForums.Components.Globals.SmtpServer; SmtpMail.Send(msg); } // Postprocessing // Only reset if everything worked. Otherwise, the data will // be saved so the user may try again. reset(); Response.Redirect("uploadResult.aspx?moduleID=" + ModuleID, true); } catch (Exception ex) { ErrorMessage.Text = ex.Message + "..." + ex.StackTrace; } }
private void SendEmails(Emails email, string type) { try { Emails.SendEmail(email, type); } catch (Exception ex) { new SqlLog().InsertSqlLog(0, "RegistrationFormUS SendEmails", ex); } }
/// <summary> /// Save a new module or changes to an existing module. /// </summary> /// <param name="status">The status to designate for the module.</param> private Modules.ModuleInfo saveModule(ModuleStatus status) { // tells whether old data exists that needs to be // removed before adding any new data bool removePrevious = false; // tells whether user is just updating an existing // module or if they want to create a new module // (possibly a new version of an existing module) bool isUpdate = false; Modules.ModuleInfo mi = createModuleInfo(); ModuleID = mi.Id; ErrorMessage.Text += "Getting base ID for module: " + ModuleID; if (ModuleID > 0) { mi.BaseId = Modules.getModuleInfo(ModuleID).BaseId; } else { mi.BaseId = 0; } mi.Status = status; mi.Submitter = User.Identity.Name; mi.SubmitterID = UserAccounts.getUserInfo(User.Identity.Name).SubmitterID; switch (ModuleEditType) { case EditType.New: isUpdate = false; break; case EditType.InProgress: isUpdate = true; removePrevious = true; break; case EditType.Approved: Modules.ModuleInfo oldModule = Modules.getModuleInfo(ModuleID); mi.BaseId = oldModule.BaseId; // If this module was previously Approved, and an admin changed it, // just update the module without creating a new version. if (User.Identity.IsAuthenticated && User.IsInRole(UserRole.Admin.ToString())) { string modSubmitter = oldModule.Submitter; // If this module is the admin's own, behave as if not an admin. // Admins deserve multiple versions too. if (User.Identity.Name.Equals(modSubmitter)) { isUpdate = false; mi.Version = oldModule.Version + 1; } else { mi.Submitter = modSubmitter; mi.SubmitterID = oldModule.SubmitterID; isUpdate = true; mi.Version = oldModule.Version; } } // If this module was previously Approved, and a non-admin changed // it, create a new version of the module, and check it out accordingly. else { isUpdate = false; MaterialsControl1.retrieveMaterials(oldModule.Id); mi.Version = oldModule.Version + 1; } removePrevious = true; break; } try { ModuleID = ModulesControl.checkInModule(mi, isUpdate); ErrorMessage.Text += " Assigned ModuleID = " + ModuleID + ". "; mi.Id = ModuleID; foreach (IEditControl ec in editControls) { ec.insertAll(ModuleID, removePrevious); } /** HANDLE THE VARIANTS **/ // is true if this module is new OR a variant is chosen (including <None>) if (VariantOf != -1) { int groupID = ModuleGroups.getGroupID(mi.BaseId); // if this module was reset as a variant of the same module // as before, or if it was set as a variant of a module in // the same group as it already is in, do nothing if (groupID != -1 && groupID == ModuleGroups.getGroupID(VariantOf)) { } // if this module was already in a group by itself, and the // user tries to put it in a new group by itself, ignore // the request and do nothing else if (groupID != -1 && VariantOf == 0 && ModuleGroups.getRelatedModules(mi.BaseId).Count == 0) { } else { // if <None> was chosen, add this module to its own module group if (VariantOf == 0) { ModuleGroups.addToNew(mi.BaseId); } // else add this module to the group that was chosen // SQL code resolves duplicates else { ModuleGroups.addToExisting(mi.BaseId, VariantOf); } } } else { // If the module was not a variant, add this module to its own module group ModuleGroups.addToNew(mi.BaseId); } } catch (Exception e) { string message = "An error occurred while saving your module."; // If a new module was being created and there was an error, remove // the module (and by cascading, any added pieces). if (ModuleEditType == EditType.New && ModuleID != 0) { ModulesControl.removeModule(ModuleID); message += " Module was not saved. Review the module and try to resubmit it."; } else { message += " All of your changes were not saved. Review the module and try to resubmit it."; ModuleEditType = EditType.InProgress; } // send an email to admins reporting the error Email msg = Emails.getEmail(EmailType.CriticalError); Emails.formatEmail(msg, mi.Submitter, mi.Id); Emails.formatEmailBody(msg, e.StackTrace + "::" + e.Message); MailMessage mail = Emails.constructErrorMessage(msg, Globals.AdminsEmail); SmtpMail.SmtpServer = AspNetForums.Components.Globals.SmtpServer; SmtpMail.Send(mail); message += " An e-mail reporting the error has been sent to the SWEnet Administrators."; throw new Exception(message, e); } return(mi); }
protected void submit_Click(object sender, EventArgs e) { if (Utils.IsNumeric(hdnOrganizationID.Value) == false) return; List<OrganizationInfo.Organization_Business> lstOrganizationBusiness = new List<OrganizationInfo.Organization_Business>(); //OrganizationInfo.Organization_Business objOrgBusiness; //foreach (RepeaterItem rptItem in rptBusiness.Items) //{ // objOrgBusiness = new OrganizationInfo.Organization_Business(); // CheckBox chkY = (CheckBox)rptItem.FindControl("chkY"); // CheckBox chkN = (CheckBox)rptItem.FindControl("chkN"); // if (chkY.Checked || chkN.Checked) // { // objOrgBusiness.BusinessID = Convert.ToInt32(((HiddenField)rptItem.FindControl("hdnID")).Value); // objOrgBusiness.IsNew = chkY.Checked; // lstOrganizationBusiness.Add(objOrgBusiness); // } //} int RoleId = Convert.ToInt32(UserInfo.UserRole.Stakeholder); UserInfo objUserInfo = new UserInfo(); objUserInfo.OrganizationId = Convert.ToInt32(hdnOrganizationID.Value); objUserInfo.Login = ViewState["PrimaryEmail"].ToString();// txtLoginName.Text.Trim(); objUserInfo.Pwd = Encryption.Encrypt("000000"); objUserInfo.PwdSalt = String.Empty; objUserInfo.IsActive = true; objUserInfo.TX_UserId = String.Empty; objUserInfo.LanguageId = LanguageId; objUserInfo.TimeZoneID = 1; objUserInfo.ContactId = 1; objUserInfo.IsApproved = false; objUserInfo.IsOrgAdmin = true; objUserInfo.DateCreated = DateTime.Now; objUserInfo.RoleId = 0;// "Role ID select from stored Procedure" ` objUserInfo.bitSetPassword = false; UserInfo.CreateStakeholderUser(objUserInfo); Emails email = new Emails(); email.To = ViewState["PrimaryEmail"].ToString(); email.From = "*****@*****.**"; email.Subject = "Registration Submitted Email"; Thread Email_Thread = new Thread(() => SendEmails(email, Emails.EmailType.RegistrationSubmissionEmail.ToString())); Email_Thread.Start(); //if (Convert.ToInt32(ddlOrganizationType.SelectedValue) == Convert.ToInt32(LookupsManagement.LookupType.OrganizationTypes_Stewardship)) //{ // RoleId = Convert.ToInt32(UserInfo.UserRole.Stewardship); //} string standardstewardshipIds = System.Configuration.ConfigurationManager.AppSettings["StewardshipStandardIDs"]; if (OrganizationInfo.SubmitApplication(Convert.ToInt32(hdnOrganizationID.Value), Convert.ToInt32(ddlOrganizationType.SelectedValue), lstOrganizationBusiness, Convert.ToInt32(ViewState["StewardShipId"]),standardstewardshipIds) == true) ScriptManager.RegisterStartupScript(this, this.GetType(), "Thankyou", "ShowThankYou();", true); //int organizationtypeid = Convert.ToInt32(ddlOrganizationType.SelectedItem.Value); //OrganizationInfo.SetStatus(OrganizationStatus.Pending, Convert.ToInt32(hdnOrganizationID.Value), "Registered", organizationtypeid); }
public void PopulateEmailList(IMailFolder mailFolder) { // The Inbox folder is always available on all IMAP servers... mailFolder.Open(FolderAccess.ReadOnly); var emailSummaries = mailFolder.Fetch(0, 49, MessageSummaryItems.UniqueId | MessageSummaryItems.PreviewText | MessageSummaryItems.Envelope); Console.WriteLine("Total messages: {0}", mailFolder.Count); Console.WriteLine("Recent messages: {0}", mailFolder.Recent); foreach (var emailSummary in emailSummaries) { if (AppConfig.CurrentIMap.IsConnected && AppConfig.CurrentIMap.IsAuthenticated && ThreadHelper.LogoutRequested == false) { try { Email email = null; ThreadHelper.StallLogout = true; if (emailSummary.TextBody != null) { email = new Email(emailSummary); } else if (emailSummary.HtmlBody != null) { lock (mailFolder.SyncRoot) { email = new Email(emailSummary, mailFolder.GetMessage(emailSummary.UniqueId)); } } if (email != null && email.Id != null && email.MessageSummary != null) { Application.Current.Dispatcher.Invoke(delegate { Emails.Add(email); Console.WriteLine("[Email Added] {0:D2}: {1}", email.Id, email.MessageSummary.Envelope.Subject); }); } else { var idState = "NOT NULL"; var messageState = "NOT NULL"; if (email.Id == null) { idState = "NULL"; } if (email.MessageSummary == null) { messageState = "NULL"; } Console.WriteLine("Email not added successfully.\nId {" + idState + "}\nMessage {" + messageState + "}"); } ThreadHelper.StallLogout = false; } catch (Exception exception) { if (ThreadHelper.LogoutRequested) { Console.WriteLine("Logout requested during email collection. "); ThreadHelper.StallLogout = false; } else { Console.WriteLine(exception); throw; } } } else { break; } } }
protected void gvLatestSteward_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Approve") { OrganizationInfo o = new OrganizationInfo(Convert.ToInt32(e.CommandArgument)); standardIds = System.Configuration.ConfigurationManager.AppSettings["StewardshipStandardIDs"]; OrganizationInfo.SetStatus(OrganizationStatus.Accepted, o.OrganizationId, "Approved from dashboard", o.OrganizationTypeId, standardIds); DataSet ds = UserInfo.getDefaultUsers(o.OrganizationId); if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { UserInfo user = new UserInfo(Convert.ToInt32(ds.Tables[0].Rows[0]["UserId"].ToString())); if (!user.IsApproved) { Emails email = new Emails(); email.To = user.Login; email.URL = ConfigurationManager.AppSettings["EmailUrl"].ToString() + "ChangePassword.aspx?userId=" + Encryption.Encrypt(user.UserId.ToString()); email.From = "*****@*****.**"; email.Subject = "Registration Approval Email"; //If thread doesnt works then uncomment the commented area below and comment 2 lines of threading. Thread Email_Thread = new Thread(() => SendEmails(email, Emails.EmailType.ApplicationApprovedEmail.ToString())); Email_Thread.Start(); //SendEmails(email, Emails.EmailType.ApplicationApprovedEmail.ToString()); } } Response.Redirect("/Dashboard/admindashboard.aspx");//,false); //Context.ApplicationInstance.CompleteRequest(); } }
protected override void ShowPage() { pagetitle = "密码找回"; username = Utils.RemoveHtml(DNTRequest.GetString("username")); //如果提交... if (DNTRequest.IsPost()) { if (ForumUtils.IsCrossSitePost()) { AddErrLine("您的请求来路不正确,无法提交。如果您安装了某种默认屏蔽来路信息的个人防火墙软件(如 Norton Internet Security),请设置其不要禁止来路信息后再试。"); return; } base.SetBackLink("getpassword.aspx?username="******"用户不存在"); return; } if (DNTRequest.GetString("email").Equals("")) { AddErrLine("电子邮件不能为空"); return; } if (IsErr()) { return; } int uid = Discuz.Forum.Users.CheckEmailAndSecques(username, DNTRequest.GetString("email"), DNTRequest.GetInt("question", 0), DNTRequest.GetString("answer")); if (uid != -1) { string Authstr = ForumUtils.CreateAuthStr(20); Discuz.Forum.Users.UpdateAuthStr(uid, Authstr, 2); string title = config.Forumtitle + " 取回密码说明"; StringBuilder body = new StringBuilder(); body.Append(username); body.Append("您好!<br />这封信是由 "); body.Append(config.Forumtitle); body.Append(" 发送的.<br /><br />您收到这封邮件,是因为在我们的论坛上这个邮箱地址被登记为用户邮箱,且该用户请求使用 Email 密码重置功能所致."); body.Append("<br /><br />----------------------------------------------------------------------"); body.Append("<br />重要!"); body.Append("<br /><br />----------------------------------------------------------------------"); body.Append("<br /><br />如果您没有提交密码重置的请求或不是我们论坛的注册用户,请立即忽略并删除这封邮件.只在您确认需要重置密码的情况下,才继续阅读下面的内容."); body.Append("<br /><br />----------------------------------------------------------------------"); body.Append("<br />密码重置说明"); body.Append("<br /><br />----------------------------------------------------------------------"); body.Append("<br /><br />您只需在提交请求后的三天之内,通过点击下面的链接重置您的密码:"); body.AppendFormat("<br /><br /><a href={0}/setnewpassword.aspx?uid={1}&id={2} target=_blank>", GetForumPath(), uid, Authstr); body.Append(GetForumPath()); body.Append("/setnewpassword.aspx?uid="); body.Append(uid); body.Append("&id="); body.Append(Authstr); body.Append("</a>"); body.Append("<br /><br />(如果上面不是链接形式,请将地址手工粘贴到浏览器地址栏再访问)"); body.Append("<br /><br />上面的页面打开后,输入新的密码后提交,之后您即可使用新的密码登录论坛了.您可以在用户控制面板中随时修改您的密码."); body.Append("<br /><br />本请求提交者的 IP 为 "); body.Append(DNTRequest.GetIP()); body.Append("<br /><br /><br /><br />"); body.Append("<br />此致 <br /><br />"); body.Append(config.Forumtitle); body.Append(" 管理团队."); body.Append("<br />"); body.Append(GetForumPath()); body.Append("<br /><br />"); Emails.DiscuzSmtpMailToUser(DNTRequest.GetString("email"), title, body.ToString()); SetUrl(forumpath); SetMetaRefresh(5); SetShowBackLink(false); AddMsgLine("取回密码的方法已经通过 Email 发送到您的信箱中,<br />请在 3 天之内到论坛修改您的密码."); } else { AddErrLine("用户名,Email 地址或安全提问不匹配,请返回修改."); } } }
private void createMailClient(Orders new_order) { string strSubject = "פרטי הזמנה שבוצעה - אל-עמי"; string strMessage = "<html><body dir=\"rtl\">"; strMessage = strMessage + String.Format("פרטי ההזמנה:") + Environment.NewLine + "<br><br>"; string tab = " "; strMessage = strMessage + tab + String.Format("בית הספר המזמין: {0}", new_order.SchoolPart.FullName) + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("נושא הפעילות: {0}", new_order.Topic.Title) + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("קהל: {0}", new_order.Audience.Title) + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("מספר כיתות: {0}", new_order.OrderClassesAndCounslers.ClassesNumber) + Environment.NewLine + Environment.NewLine + "<br>"; //strMessage = strMessage + String.Format("מספר סבבים: {0}", // new_order.RoundsNumber) + Environment.NewLine + Environment.NewLine + "<br><br>"; strMessage = strMessage + tab + String.Format("מספר מדריכים: {0}", new_order.OrderClassesAndCounslers.CounslerNumber) + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("מחיר: {0}", new_order.OrderClassesAndCounslers.Price) + Environment.NewLine + Environment.NewLine + "<br>"; if (null != new_order.DT1) { strMessage = strMessage + tab + String.Format("התאריכים:") + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("{0}", new_order.DT1) + Environment.NewLine + Environment.NewLine + "<br>"; } if (null != new_order.DT2) { strMessage = strMessage + tab + String.Format("{0}", new_order.DT2) + Environment.NewLine + Environment.NewLine + "<br>"; } if (null != new_order.DT3) { strMessage = strMessage + tab + String.Format("{0}", new_order.DT3) + Environment.NewLine + Environment.NewLine + "<br>"; } strMessage = strMessage + "<br>"; strMessage = strMessage + String.Format("ההזמנה בוצעה בהצלחה." + "\n" + " במידה ולא נוצר קשר, אנא פנה אלינו שנית דרך המערכת או התקשר אלינו.") + Environment.NewLine + "<br>"; strMessage = strMessage + "</body></html>"; UserPrefs latest = null; foreach (UserPrefs prefs in this.DataWorkspace.ApplicationData.UserPrefs) { if (null == prefs) { continue; } if (latest == null) latest = prefs; else if (latest.CreatedDate < prefs.CreatedDate) latest = prefs; } if (latest == null) { return; } else if (latest.MailAddress == null || latest.Password == null || latest.DisaplayName == null) { return; } string receiver_name = new_order.Contact.FullName; if (null == receiver_name || receiver_name.Equals("")) receiver_name = new_order.Email; // Create the MailHelper class created in the Server project. Emails new_entry = new Emails(); new_entry.Sender = latest.MailAddress; new_entry.Receiver = receiver_name; new_entry.Subject = strSubject; new_entry.Message = strMessage; new_entry.ReceiverMail = new_order.Email; }
private void mailSender(Orders entity) { string strSubject = "אל עמי - הודעה בנוגע לעדכון סטטוס הזמנה"; // dealing with approved and unapproved message string strMessage = "<html><body dir=\"rtl\">"; strMessage = strMessage + String.Format("לכבוד {0},", entity.Contact.FullName) + Environment.NewLine; strMessage = strMessage + "<br>"; if (true == entity.Approved) strMessage = strMessage + String.Format("הזמנתך אושרה.") + Environment.NewLine + "<br>"; else strMessage = strMessage + String.Format("הזמנתך בוטלה.") + Environment.NewLine + "<br>"; strMessage = strMessage + Environment.NewLine + "<br>"; strMessage = strMessage + String.Format("פרטי ההזמנה:") + Environment.NewLine + "<br><br>"; string tab = " "; strMessage = strMessage + tab + String.Format("בית הספר המזמין: {0}", entity.SchoolPart.FullName) + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("נושא הפעילות: {0}", entity.Topic.Title) + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("קהל: {0}", entity.Audience.Title) + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("מספר כיתות: {0}", entity.OrderClassesAndCounslers.ClassesNumber) + Environment.NewLine + Environment.NewLine + "<br>"; //strMessage = strMessage + String.Format("מספר סבבים: {0}", // entity.RoundsNumber) + Environment.NewLine + Environment.NewLine + "<br><br>"; strMessage = strMessage + tab + String.Format("מספר מדריכים: {0}", entity.OrderClassesAndCounslers.CounslerNumber) + Environment.NewLine + Environment.NewLine + "<br>"; if (true == entity.Approved) strMessage = strMessage + tab + String.Format("התאריך שאושר: {0}", entity.ChosenDate) + Environment.NewLine + Environment.NewLine + "<br>"; else { if (null != entity.DT1) { strMessage = strMessage + tab + String.Format("התאריכים:") + Environment.NewLine + Environment.NewLine + "<br>"; strMessage = strMessage + tab + String.Format("{0}", entity.DT1) + Environment.NewLine + Environment.NewLine + "<br>"; } if (null != entity.DT2) { strMessage = strMessage + tab + String.Format("{0}", entity.DT2) + Environment.NewLine + Environment.NewLine + "<br>"; } if (null != entity.DT3) { strMessage = strMessage + tab + String.Format("{0}", entity.DT3) + Environment.NewLine + Environment.NewLine + "<br>"; } } strMessage = strMessage + "<br>"; if (true == entity.Approved) strMessage = strMessage + String.Format("לפרטים נוספים ויצירת קשר, אנא שלח/י מייל לכתובת זו.") + Environment.NewLine; else strMessage = strMessage + String.Format("אנו מצטערים על ביטול ההזמנה, נשמח אם תיצור/תיצרי איתנו קשר באימייל זה לקבלת פרטים נוספים.") + Environment.NewLine; strMessage = strMessage + String.Format("בברכה,") + Environment.NewLine + "<br>"; strMessage = strMessage + String.Format("ארגון אל-עמי") + Environment.NewLine + "<br>"; strMessage = strMessage + "</body></html>"; string strFrom = "*****@*****.**"; // Create the MailHelper class created in the Server project. Emails new_entry = new Emails(); new_entry.Sender = strFrom; new_entry.Receiver = entity.Contact.FullName; new_entry.Subject = strSubject; new_entry.Message = strMessage; new_entry.ReceiverMail = entity.Email.ToString(); this.DataWorkspace.ApplicationData.SaveChanges(); this.ShowMessageBox("ההודעה נשלחה בהצלחה"); }
public void UpdateFrom(IContactInfo source, bool suppressIsChanged) { FirstName = source.FirstName; MiddleName = source.MiddleName; LastName = source.LastName; Company = source.Company; JobTitle = source.JobTitle; Note = source.Note; Key = source.Key; VersionKey = source.VersionKey == null ? String.Empty : source.VersionKey.ToString(); // Phone numbers foreach (var item in source.PhoneNumbers) { var phoneNumber = PhoneNumbers.FirstOrDefault(x => x.Key == item.Key); if (phoneNumber != null) { phoneNumber.UpdateFrom(item); } else { PhoneNumbers.Add(new ContactPhoneLocal(item, AddressBook)); } } foreach (var item in PhoneNumbers.Where(x => source.PhoneNumbers.All(y => x.Key != y.Key)).ToArray()) { PhoneNumbers.Remove(item); } // Emails foreach (var item in source.Emails) { var email = Emails.FirstOrDefault(x => x.Key == item.Key); if (email != null) { email.UpdateFrom(item); } else { Emails.Add(new ContactEmailLocal(item, AddressBook)); } } foreach (var item in Emails.Where(x => source.Emails.All(y => x.Key != y.Key)).ToArray()) { Emails.Remove(item); } // Tags foreach (var item in source.Tags) { var tag = Tags.FirstOrDefault(x => x.Key == item.Key); if (tag != null) { tag.UpdateFrom(item); } else { var newTag = _contactsManager.Tags.FirstOrDefault(x => x.Key == item.Key); if (newTag != null) { Tags.Add(newTag); } } } foreach (var item in Tags.Where(x => source.Tags.All(y => x.Key != y.Key)).ToArray()) { Tags.Remove(item); } if (suppressIsChanged) { IsChanged = false; } }
/// <summary> /// Enviar pedido do cliente Membro /// </summary> /// <param name="pedidoId"></param> /// <param name="situacao">1 envia pedido gerado e 2 Enviar o pedido com os preços cotados </param> /// public void EnviaEmailPedido(int pedidoId, int situacao, Usuario Usuario) { Pedido pedido = _pedidoRep.GetSingle(pedidoId); var usuarioMembro = _usuarioRep.FirstOrDefault(x => x.Id == pedido.UsuarioCriacaoId); PedidoEmailViewModel pedidoEmailVm = null; if (usuarioMembro.Pessoa.TipoPessoa == TipoPessoa.PessoaJuridica) { pedidoEmailVm = new PedidoEmailViewModel() { Id = pedido.Id, NomeFantasia = pedido.Membro.Pessoa.PessoaJuridica.NomeFantasia }; } else { pedidoEmailVm = new PedidoEmailViewModel() { Id = pedido.Id, NomeFantasia = pedido.Membro.Pessoa.PessoaFisica.Nome }; } switch (situacao) { //Depois, talvez precisamos mandar no email do cadastro do membro e no email do usuário ou mandar de acordo com a configuração decidida pelo mesmo no menu configurações do membro //Situacao 1 é para quando gerar o pedido case 1: Emails email1 = new Emails() { EmailDestinatario = Usuario.UsuarioEmail, CorpoEmail = _emailService.MontaEmail(pedidoEmailVm, _templateEmailRep.GetSingle(6).Template.Replace("#Grid#", "" + MontaGridItensPedido(pedido.ItemPedidos.ToList()) + "")), AssuntoEmail = "Confirmação - Número do Pedido " + pedidoId, Status = Status.NaoEnviado, Origem = Origem.PedidoMembroGerado, DtCriacao = DateTime.Now, UsuarioCriacao = Usuario, Ativo = true }; _emailsRep.Add(email1); _unitOfWork.Commit(); break; //Situacao 2 é para quando atualizar o valor do item do pedido do cliente nesse email iremos pedir para ele aprovar case 2: Emails email2 = new Emails() { EmailDestinatario = Usuario.UsuarioEmail, CorpoEmail = _emailService.MontaEmail(pedidoEmailVm, _templateEmailRep.GetSingle(6).Template.Replace("#Grid#", "" + MontaGridItensPedido(pedido.ItemPedidos.ToList()) + "")), AssuntoEmail = "Aprovação de Preço - Número do Pedido " + pedidoId, Status = Status.NaoEnviado, Origem = Origem.PedidoMembroAprovado, DtCriacao = DateTime.Now, UsuarioCriacao = Usuario, Ativo = true }; _emailsRep.Add(email2); _unitOfWork.Commit(); break; //Situacao 3 é quando o fornecedor aprova um pedido da Cotação case 3: var fornecedor = _fornecedorRep.FirstOrDefault(x => x.PessoaId == Usuario.PessoaId); var itensPedido = pedido.ItemPedidos.Where(x => x.FornecedorId == fornecedor.Id && x.AprovacaoMembro && x.AprovacaoFornecedor).ToList(); Emails email3 = new Emails() { EmailDestinatario = usuarioMembro.UsuarioEmail, CorpoEmail = _emailService.MontaEmail(pedidoEmailVm, _templateEmailRep.GetSingle(25).Template .Replace("#Grid#", MontaGridItensPedido(itensPedido)) .Replace("#NomeFornecedor#", fornecedor.Pessoa.PessoaJuridica.NomeFantasia)), AssuntoEmail = "Itens do Pedido Aprovados - Número do Pedido " + pedidoId, Status = Status.NaoEnviado, Origem = Origem.PedidoMembroAprovado, DtCriacao = DateTime.Now, UsuarioCriacao = Usuario, Ativo = true }; _emailsRep.Add(email3); _unitOfWork.Commit(); break; //Situacao 4 é quando o fornecedor aprova o pedido promocional case 4: var fornecedorPromocao = _fornecedorRep.FirstOrDefault(x => x.PessoaId == Usuario.PessoaId); Emails email4 = new Emails() { EmailDestinatario = usuarioMembro.UsuarioEmail, CorpoEmail = _emailService.MontaEmail(pedidoEmailVm, _templateEmailRep.GetSingle(26).Template .Replace("#Grid#", MontaGridItensPedidoPromocao(pedido)) .Replace("#NomeFornecedor#", fornecedorPromocao.Pessoa.PessoaJuridica.NomeFantasia)), AssuntoEmail = "Pedido promocional aprovado - Número do pedido " + pedidoId, Status = Status.NaoEnviado, Origem = Origem.PedidoMembroAprovado, DtCriacao = DateTime.Now, UsuarioCriacao = Usuario, Ativo = true }; _emailsRep.Add(email4); _unitOfWork.Commit(); break; //Envia email quando fornecedor confirma entrega dos itens do pedido. case 5: var fornecedorEntrega = _fornecedorRep.FirstOrDefault(x => x.PessoaId == Usuario.PessoaId); var itensPedidoEntrega = pedido.ItemPedidos.Where(x => x.FornecedorId == fornecedorEntrega.Id && x.AprovacaoMembro && x.AprovacaoFornecedor).ToList(); var tipoPedido = pedido.ItemPedidos .Any(x => x.FornecedorId == fornecedorEntrega.Id && x.AprovacaoMembro && x.AprovacaoFornecedor && x.Produto.ProdutoPromocionalId == null); var nomeMembro = pedido.Membro.Pessoa.TipoPessoa == TipoPessoa.PessoaJuridica ? pedido.Membro.Pessoa.PessoaJuridica.NomeFantasia : pedido.Membro.Pessoa.PessoaFisica.Nome; var corpoEmail = _templateEmailRep.GetSingle(32).Template .Replace("#IdPedido#", pedido.Id.ToString()) .Replace("#NomeMembro#", nomeMembro) .Replace("#NomeFornecedor#", fornecedorEntrega.Pessoa.PessoaJuridica.NomeFantasia) .Replace("#Grid#", tipoPedido ? MontaGridItensPedido(itensPedidoEntrega) : MontaGridItensPedidoPromocao(pedido)); var email = new Emails { UsuarioCriacao = Usuario, DtCriacao = DateTime.Now, AssuntoEmail = "Fornecedor confirmou a entrega dos itens do pedido " + pedido.Id + ".", EmailDestinatario = usuarioMembro.UsuarioEmail, CorpoEmail = corpoEmail.Trim(), Status = Status.NaoEnviado, Origem = Origem.FornecedorConfirmaEntregaPedido, Ativo = true }; _emailsRep.Add(email); _unitOfWork.Commit(); break; //Envia email quando fornecedor despachar dos itens do pedido. case 6: var fornecedorDespacho = _fornecedorRep.FirstOrDefault(x => x.PessoaId == Usuario.PessoaId); var itensPedidoDespacho = pedido.ItemPedidos.Where(x => x.FornecedorId == fornecedorDespacho.Id && x.AprovacaoMembro && x.AprovacaoFornecedor).ToList(); var tipoPedidoDespacho = pedido.ItemPedidos .Any(x => x.FornecedorId == fornecedorDespacho.Id && x.AprovacaoMembro && x.AprovacaoFornecedor && x.Produto.ProdutoPromocionalId == null); var nomeMembroDespacho = pedido.Membro.Pessoa.TipoPessoa == TipoPessoa.PessoaJuridica ? pedido.Membro.Pessoa.PessoaJuridica.NomeFantasia : pedido.Membro.Pessoa.PessoaFisica.Nome; var corpoEmailDespacho = _templateEmailRep.GetSingle(40).Template .Replace("#IdPedido#", pedido.Id.ToString()) .Replace("#NomeMembro#", nomeMembroDespacho) .Replace("#NomeFornecedor#", fornecedorDespacho.Pessoa.PessoaJuridica.NomeFantasia) .Replace("#Grid#", tipoPedidoDespacho ? MontaGridItensPedido(itensPedidoDespacho) : MontaGridItensPedidoPromocao(pedido)); var emailDespacho = new Emails { UsuarioCriacao = Usuario, DtCriacao = DateTime.Now, AssuntoEmail = "Fornecedor Despachou para Entrega itens do seu pedido " + pedido.Id + ".", EmailDestinatario = usuarioMembro.UsuarioEmail, CorpoEmail = corpoEmailDespacho.Trim(), Status = Status.NaoEnviado, Origem = Origem.FornecedorDespachouItensPedido, Ativo = true }; _emailsRep.Add(emailDespacho); _unitOfWork.Commit(); break; } }
private Emails GetEmails() { var constituentId = Convert.ToInt32(Session["constituentId"]); var emailsData = HttpHelper.Get<EmailsData>(serviceBaseUri+"/Emails?ConstituentId="+constituentId); mapper = new AutoDataContractMapper(); var emails = new Emails(); mapper.MapList(emailsData, emails, typeof(Email)); return emails; }
public async Task TestCreatePurchaseOrder() { UnitOfWork unitOfWork = new UnitOfWork(); ItemMaster itemMaster = new ItemMaster(); itemMaster.ItemNumber = "P2001Test"; itemMaster.Description = "Highlighter - 3 Color"; itemMaster.UnitOfMeasure = "Sets"; itemMaster.UnitPrice = 6M; bool result = await unitOfWork.itemMasterRepository.CreateItemMaster(itemMaster); if (result) { unitOfWork.CommitChanges(); } AddressBook addressBook = new AddressBook(); addressBook.CompanyName = "Sample Company Part Ltd"; addressBook.Name = ""; addressBook.FirstName = ""; addressBook.LastName = ""; LocationAddress locationAddress = new LocationAddress(); locationAddress.AddressLine1 = "204 Collins Street"; locationAddress.City = "Melbourne"; locationAddress.Zipcode = "3000"; locationAddress.Country = "Australia"; Emails email = new Emails(); email.Email = "*****@*****.**"; email.LoginEmail = true; email.Password = "******"; SupplierView supplierView = await unitOfWork.supplierRepository.CreateSupplierByAddressBook(addressBook, locationAddress, email); ChartOfAccts coa = await unitOfWork.supplierRepository.GetChartofAccount("1000", "1200", "240", ""); Company company = await unitOfWork.supplierRepository.GetCompany(); ItemMaster[] itemMasterLookup = new ItemMaster[5]; itemMasterLookup[0] = await unitOfWork.itemMasterRepository.GetObjectAsync(5); itemMasterLookup[1] = await unitOfWork.itemMasterRepository.GetObjectAsync(6); itemMasterLookup[2] = await unitOfWork.itemMasterRepository.GetObjectAsync(7); itemMasterLookup[3] = await unitOfWork.itemMasterRepository.GetObjectAsync(8); itemMasterLookup[4] = await unitOfWork.itemMasterRepository.GetObjectAsync(9); Udc udcAcctPayDocType = await unitOfWork.accountPayableRepository.GetUdc("AcctPayDocType", "STD"); string json = @"{ ""DocType"" : """ + udcAcctPayDocType.KeyCode + @""", ""PaymentTerms"" : ""Net 30"", ""GLDate"" : """ + DateTime.Parse("7/30/2018") + @""", ""AccountId"" :" + coa.AccountId + @", ""SupplierId"" :" + (supplierView.SupplierId ?? 0).ToString() + @", ""SupplierName"" :""" + supplierView.CompanyName + @""", ""Description"" :""Back to School Inventory"", ""PONumber"" :""PO-2"", ""TakenBy"" : ""David Nishimoto"", ""BuyerId"" :" + company.CompanyId + @", ""TaxCode1"" :""" + company.TaxCode1 + @""", ""TaxCode2"" :""" + company.TaxCode2 + @""", ""ShippedToName"" :""" + company.CompanyName + @""", ""ShippedToAddress1"" :""" + company.CompanyStreet + @""", ""ShippedToCity"" :""" + company.CompanyCity + @""", ""ShippedToState"" :""" + company.CompanyState + @""", ""ShippedToZipcode"" :""" + company.CompanyZipcode + @""", ""RequestedDate"" :""" + DateTime.Parse("7/24/2018") + @""", ""PromisedDeliveredDate"" :""" + DateTime.Parse("8/2/2018") + @""", ""TransactionDate"" :""" + DateTime.Parse("7/30/2018") + @""", ""PurchaseOrderDetailViews"":[ { ""ItemId"": 5, ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""", ""OrderedQuantity"": 5, ""UnitPrice"" : " + itemMasterLookup[0].UnitPrice + @", ""UnitOfMeasure"" : """ + itemMasterLookup[0].UnitOfMeasure + @""", ""Amount"" : " + itemMasterLookup[0].UnitPrice * 5 + @", ""Description"": """ + itemMasterLookup[0].Description + @""", ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""", ""ReceivedQuantity"":0, ""RemainingQuantity"":5 }, { ""ItemId"": 6, ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""", ""OrderedQuantity"": 4, ""UnitPrice"" : " + itemMasterLookup[1].UnitPrice + @", ""UnitOfMeasure"" : """ + itemMasterLookup[1].UnitOfMeasure + @""", ""Amount"" : " + itemMasterLookup[1].UnitPrice * 4 + @", ""Description"": """ + itemMasterLookup[1].Description + @""", ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""", ""ReceivedQuantity"":0, ""RemainingQuantity"":4 }, { ""ItemId"": 7, ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""", ""OrderedQuantity"": 10, ""UnitPrice"" : " + itemMasterLookup[2].UnitPrice + @", ""UnitOfMeasure"" : """ + itemMasterLookup[2].UnitOfMeasure + @""", ""Amount"" : " + itemMasterLookup[2].UnitPrice * 10 + @", ""Description"": """ + itemMasterLookup[2].Description + @""", ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""", ""ReceivedQuantity"":0, ""RemainingQuantity"":10 }, { ""ItemId"": 8, ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""", ""OrderedQuantity"": 15, ""UnitPrice"" : " + itemMasterLookup[3].UnitPrice + @", ""UnitOfMeasure"" : """ + itemMasterLookup[3].UnitOfMeasure + @""", ""Amount"" : " + itemMasterLookup[3].UnitPrice * 15 + @", ""Description"": """ + itemMasterLookup[3].Description + @""", ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""", ""ReceivedQuantity"":0, ""RemainingQuantity"":15 }, { ""ItemId"": 9, ""OrderDate"":""" + DateTime.Parse("7 / 30 / 2018") + @""", ""OrderedQuantity"": 10, ""UnitPrice"" : " + itemMasterLookup[4].UnitPrice + @", ""UnitOfMeasure"" : """ + itemMasterLookup[3].UnitOfMeasure + @""", ""Amount"" : " + itemMasterLookup[4].UnitPrice * 10 + @", ""Description"": """ + itemMasterLookup[4].Description + @""", ""ExpectedDeliveryDate"" :""" + DateTime.Parse("8/2/2018") + @""", ""ReceivedQuantity"":0, ""RemainingQuantity"":10 } ] }"; PurchaseOrderView purchaseOrderView = JsonConvert.DeserializeObject <PurchaseOrderView>(json); AccountsPayableModule apMod = new AccountsPayableModule(); //TODO Create the Purchase Order apMod .PurchaseOrder .CreatePurchaseOrder(purchaseOrderView) .Apply() .CreatePurchaseOrderDetails(purchaseOrderView) .Apply() .CreateAcctPayByPurchaseOrderNumber(purchaseOrderView) .Apply(); Assert.True(true); }