I want to do basic functionality with a simple contact form and on submit the form emails to someone. This is quite easy to do in asp.net, however I am having trouble once I upload it as a user control. Do you have a good example I can look at? Thank you!
It is the same as you would have in a normal asp.net page, the sample assumes you are using the latest version of Sitefinity and that you are have a RadScriptManager or ScriptManager on your master page.
Firstly here is my example form codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.ComponentModel;
public partial class UserControls_LandingPage_contactForm : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool bSent = false;
try
{
//create the email and add the settings
var email = new MailMessage();
email.From = new MailAddress(FromEmail);
email.To.Add(new MailAddress(FromEmail));
email.Subject = Subject;
email.IsBodyHtml = true;
//build the body
var sBody = new StringBuilder();
sBody.Append("<strong>Contact Details</strong><br /><br />");
sBody.AppendFormat("Needs: {0}<br />", cboConsultationType.SelectedValue);
sBody.AppendFormat("Name: {0}<br />", txtName.Text);
sBody.AppendFormat("Email: {0}<br />", txtEmail.Text);
sBody.AppendFormat("Number: {0}<br />", txtPhone.Text);
sBody.AppendFormat("Comment: {0}<br />", txtMsg.Text);
email.Body = sBody.ToString();
//send the email
var smtpServer = new SmtpClient();
smtpServer.Send(email);
//mark as sent ok
bSent = true;
}
catch (Exception ex)
{
//send any errors back
//add your own custom handling of errors;
}
//let the end user know if it was a success
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('" + (bSent ? SuccessText : FailureText) + "');", true);
}
//properties
public string FromEmail
{
get { return _fromEmail; }
set { _fromEmail = value; }
}
public string Subject
{
get { return _subject; }
set { _subject = value; }
}
public string SuccessText
{
get { return _successText; }
set { _successText = value; }
}
public string FailureText
{
get { return _failureText; }
set { _failureText = value; }
}
//fields
private string _fromEmail = "info#example.com.au";
private string _subject = "Website Enquiry";
private string _successText = "Thank you for submitting your details we will be in touch shortly.";
private string _failureText = "There was a problem submitting your details please try again shortly.";
}
ASCX Code:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ContactForm.ascx.cs" Inherits="UserControls_LandingPage_contactForm" %>
<fieldset>
<div class="focus">
<label>
I need...</label>
<asp:DropDownList ID="cboConsultationType" runat="server" CssClass="select sub web">
<asp:ListItem Value="I Need A New Web Site">A completely new website</asp:ListItem>
<asp:ListItem Value="Web Site Upgrade">My website upgraded</asp:ListItem>
<asp:ListItem Value="Application Design">An application </asp:ListItem>
<asp:ListItem Value="An ecommerce website">New Ecommerce website</asp:ListItem>
<asp:ListItem Value="Other">Other</asp:ListItem>
</asp:DropDownList>
</div>
<ul>
<li>
<asp:Label EnableViewState="false" ID="lblErrorMessage" runat="server"></asp:Label>
</li>
<li>
<asp:Label EnableViewState="false" ID="lblName" AssociatedControlID="txtName" runat="server"
Text="Name"></asp:Label>
<asp:TextBox ID="txtName" runat="server" ValidationGroup="ContactValidation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ValidationGroup="ContactValidation"
ControlToValidate="txtName" ErrorMessage="Name is required">*</asp:RequiredFieldValidator>
</li>
<li>
<asp:Label ID="lblPhone" runat="server" AssociatedControlID="txtPhone" EnableViewState="false"
Text="Phone"></asp:Label>
<asp:TextBox ID="txtPhone" runat="server" ValidationGroup="ContactValidation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorPhone" runat="server" ValidationGroup="ContactValidation"
ControlToValidate="txtPhone" ErrorMessage="Phone is required">*</asp:RequiredFieldValidator>
</li>
<li>
<asp:Label ID="lblEmail" runat="server" AssociatedControlID="txtEmail" EnableViewState="false"
Text="Email"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server" ValidationGroup="ContactValidation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ValidationGroup="ContactValidation"
ControlToValidate="txtEmail" ErrorMessage="Email is required">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail" runat="server"
ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="ContactValidation" ErrorMessage="Email address is invalid">*</asp:RegularExpressionValidator>
</li>
<li>
<asp:Label ID="lblMsg" runat="server" AssociatedControlID="txtMsg" EnableViewState="false"
Text="How can we assist you?"></asp:Label>
<asp:TextBox ID="txtMsg" runat="server" TextMode="MultiLine" Rows="5" Wrap="true"></asp:TextBox>
</li>
<li>
<asp:Button ID="btnSubmit" runat="server" EnableViewState="false" CssClass="submit"
Text="Send" ValidationGroup="ContactValidation" OnClick="btnSubmit_Click" />
</li>
</ul>
</fieldset>
Then the only other items you need to be wary of is in the web.config you need to modify the system.net settings for email:
<system.net>
<mailSettings>
<smtp from="mailmaster#yourdomain.com">
<network host="smtp.yourdomain.com" userName="Your_Username" password="Your_Password" port="25" />
</smtp>
</mailSettings>
</system.net>
Then upload the control or modify your web.config . Then provided your SMTP server is all set up correctly the form should send no problem.
I hope this helps you out.
I think one good approach is using the incorporated mail sender. The profits are that you can configure the settings inside the Administration->Settings->Advanced->System->SMTP
var smtpSettings = Config.Get<SystemConfig>().SmtpSettings;
MailMessage message = new MailMessage();
message.From = new MailAddress(smtpSettings.UserName);
message.To.Add(new MailAddress(toEmail));
StringBuilder sb = new StringBuilder();
sb.AppendFormat(body);
message.Subject = subject;
message.Body = sb.ToString();
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.Unicode;
message.SubjectEncoding = Encoding.Unicode;
EmailSender.Get().Send(message);
You can use notifications too.
Related
I have 2 files in my web site project, Translator2.aspx and Translator2.aspx.cs. I want to add new class (Erwin:Translator2) to my Translator2.aspx.cs file. However it was error like this :
Severity Code Description Project File Line Suppression State
Error 'translator2_aspx' does not contain a definition for 'Switch'
and no extension method 'Switch' accepting a first argument of type
'translator2_aspx' could be found (are you missing a using directive
or an assembly reference?)
C:\Users\erwin.surya\Documents\Visual
Studio 2017\WebSites\WebSite1\Translator2.aspx 33
Here is my Translator2.aspx code:
<%# Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="Translator2.aspx.cs" MasterPageFile="~/Site.Master" Inherits="Translator2" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="English" CssClass="col-md-2 control-label">English</asp:Label>
<div class="col-md-10">
<asp:TextBox Height="79px" TextMode="MultiLine" Width="452px" runat="server" ID="English" CssClass="form-control" />
</div> </div>
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" OnClick="Submit" Height="39px" Width="100px" Text="Translate" CssClass="btn btn-default" />
</div>
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" OnClick="Switch" Height="39px" Width="100px" Text="Switch" CssClass="btn btn-default" />
</div>
<br /><br /><br />
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="Japanese" CssClass="col-md-2 control-label">Japanese</asp:Label>
<div class="col-md-10">
<asp:TextBox Height="79px" TextMode="MultiLine" Width="452px" runat="server" ID="Japanese" CssClass="form-control" />
</div></div>
<br /><br />
<asp:PlaceHolder runat="server" ID="ErrorMessage" Visible="false">
<p class="text-danger">
<asp:Literal runat="server" ID="FailureText" />
</p>
</asp:PlaceHolder>
</asp:Content>
Here is my Translator2.aspx.cs code:
partial class Translator2 : Page
{
public async void Submit(object sender, EventArgs e)
{
string key = "92fcf1387f844a8";
var authTokenSource = new AzureAuthToken(key.Trim());
string authToken;
try
{
authToken = await authTokenSource.GetAccessTokenAsync();
}
catch (HttpRequestException)
{
if (authTokenSource.RequestStatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
return;
}
if (authTokenSource.RequestStatusCode == HttpStatusCode.Forbidden)
{
Console.WriteLine("Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
return;
}
throw;
}
string output = "";
string text = English.Text;
string uri = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(text) + "&from=" + "en" + "&to=" + "ja";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add("Authorization", authToken);
using (WebResponse response = httpWebRequest.GetResponse())
using (Stream stream = response.GetResponseStream())
{
DataContractSerializer dcs = new DataContractSerializer(Type.GetType("System.String"));
string translation = (string)dcs.ReadObject(stream);
Console.WriteLine("Translation for source text '{0}' from {1} to {2} is", text, "en", "ja");
Console.WriteLine(translation);
output = translation;
}
Japanese.Text = output;
}
class Erwin : Translator2
{
string from, to;
public void SwapStrings(string s1, string s2)
{
string temp = s1;
s1 = s2;
s2 = temp;
from = s1;
to = s2;
testing.Text = from;
testing1.Text = to;
}
protected void Switch(object sender, EventArgs e)
{
string str1 = testing.Text;
string str2 = testing1.Text;
System.Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2);
SwapStrings(str1, str2);
}
}
Do you have any idea why I can't add Erwin:Translato2 class? everything works fine before I add the class. Did I miss something?
The Switch method is in a different class than the class that is powering your aspx page. If you want switch to be some kind of utility method, you should create a new class, maybe Erwin in a completely separate file (Erwin.cs), and have a switch method inside that that is public and probably static. I also note that switch doesn't return anything, so not sure what you are trying to accomplish with it.
The OnClick handler for your button should be in the code behind -- ie in the Translator2 class. Inside this handler, you could call Erwin.Switch().
I am trying to do a multi Client - Server application. After I did some of the basic controls and functions with Windows Forms I thought to add a WebPage to my Client side.
I created a new project and edited it and it works ok, the page is connecting to the server and it receives the messages I send from the web page.
The problem I get when I need to post messages on a textbox on the web page. I searched on some pages here, on the internet and I can't find a good solution for my problem. I alose used the Page.IsPostBack but it didn't work, then I added an UpdatePanel because the page was refreshing when I clicked the buttons but that didn't work either... Now I am out of ideas.
Can anybody suggest how should I do this ? My code behind is C# and I don't know how to parse these details to JavaScript or jQuery, so any of you have some details on how to that it will also be appreciated.
Thanks in advance.
And also I will post anything needed if there is important for this question.
EDIT (Added code):
public void btnSend_Click(object sender, EventArgs e)
{
if (tbSendMessage.Text.Length > 0)
{
string message = tbSendMessage.Text;
byte[] outStream = Encoding.ASCII.GetBytes(message + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
tbSendMessage.Text = string.Empty;
}
}
private void getMessage()
{
while (true)
{
try
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[70000];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = Encoding.ASCII.GetString(inStream);
//tbReceivedMessages.Text += returndata + "\n";
ShowMessage(returndata);
}
catch (Exception ex)
{
ShowAlert("Connection lost.\n" + ex.Message);
//ShowMessage("Conexiunea cu serverul s-a pierdut.\n" );
serverStream.Close();
return;
}
}
}
private void ShowMessage(string message)
{
sb.AppendLine(message);
tbReceivedMessages.Text += sb;
}
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %></h2>
<p>
<asp:UpdatePanel ID="UpdatePanelConnect" runat="server">
<ContentTemplate>
<asp:Label ID="lblUsername" runat="server" Text="Enter username:"></asp:Label>
<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>
<asp:Button ID="btnConnect" runat="server" OnClick="btnConnect_Click" Text="Connect" />
</ContentTemplate>
</asp:UpdatePanel>
</p>
<p> </p>
<p>
<asp:UpdatePanel ID="UpdatePanelConnected" runat="server">
<ContentTemplate>
<asp:TextBox
ID="tbReceivedMessages"
runat="server"
Height="250px"
TextMode="MultiLine"
Width="250px"
MaxLength="2000000"
ReadOnly="True"></asp:TextBox>
</p>
<p> </p>
<p>
<asp:TextBox ID="tbSendMessage" runat="server"></asp:TextBox>
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" Text="Send" />
</ContentTemplate>
</asp:UpdatePanel>
</p>
</asp:Content>
If you want two server controls to communicate each other via Ajax, you will need to place them in same UpdatePanel.
FYI: If you are new to ASP.Net Web Form, do not use UpdatePanel yet. Instead, make it work with regular post back.
<asp:UpdatePanel ID="UpdatePanelConnect" runat="server">
<ContentTemplate>
<asp:Label ID="lblUsername" runat="server" Text="Enter username:"></asp:Label>
<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>
<asp:Button ID="btnConnect" runat="server" OnClick="btnConnect_Click" Text="Connect" />
<asp:TextBox
ID="tbReceivedMessages"
runat="server"
Height="250px"
TextMode="MultiLine"
Width="250px"
MaxLength="2000000"
ReadOnly="True"></asp:TextBox>
</p>
<p> </p>
<p>
<asp:TextBox ID="tbSendMessage" runat="server"></asp:TextBox>
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" Text="Send" />
</ContentTemplate>
</asp:UpdatePanel>
public void btnSend_Click(object sender, EventArgs e)
{
if (tbSendMessage.Text.Length > 0)
{
string message = tbSendMessage.Text;
// This code won't work.
/*byte[] outStream = Encoding.ASCII.GetBytes(message + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
tbSendMessage.Text = string.Empty;*/
}
}
I'm working in asp.net with c# and I decided to build a pop-up messaging module. I have done this on previous projects; however, I've never used it on a site that was also utilizing the Identity Framework or placed in my master page. I am also fairly new to C#.
The messenger appears to be working fine. However, now any kind of "submit" or "send" function found on the master page will not work properly. For example, if I try to log in as an admin, I will get my windows error messages for the field validation on the messenger. I tried taking out the RequiredFieldValidators, I was still unable to log in, instead it tried to send a message.
I then tried moving the module into a usercontrol and running it that way, still no luck. I had considered building a new masterpage for the log in page, that way I could remove the "contact" from the navigation on that page, thus eliminating the issue . However, I would prefer not to have to do this. I am sure there is a simple solution to correcting this, and my lack of experience with c# is not helping much.
Here is part of the navigation on my Site.Master, just to give an idea about what I'm doing:
<li><a runat="server" href="#" data-toggle="modal" data-target=".pop-up-1">Contact</a></li>
</ul>
<asp:LoginView runat="server" ViewStateMode="Disabled">
<AnonymousTemplate>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/Account/Login" style="color:#f46de6">Admin</a></li>
<li><asp:HyperLink ID="PayPalViewCart" runat="server" NavigateUrl=<%# Link.ToPayPalViewCart() %> style="color:#f46de6">View Cart</asp:HyperLink></li>
</ul>
</AnonymousTemplate>
<LoggedInTemplate>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/Account/Manage" title="Manage your account" style="color:#f46de6" >Hello, Admin</a></li>
<li>
<asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" />
</li>
</ul>
</LoggedInTemplate>
</asp:LoginView>
</div>
</div>
</div>
<uc1:popup1 runat="server" id="popup1" />
<div class="container body-content">
Now here is the code behind on this page, site.Master.cs:
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
{
Context.GetOwinContext().Authentication.SignOut();
}
}
}
This is my user control for the pop-up:
<div class="modal fade pop-up-1" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myLargeModalLabel-3">Contact Us</h4>
</div>
<div class="modal-body">
<table style="max-width:100%; height: auto; padding:20px">
<tr>
<td colspan="3">
<div style="margin:15px 0 20px 0"> Please, use the form below to contact us regarding any questions or concerns you might have:</div>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="width:150px; font-size:14px">Name:</td>
<td style="vertical-align:top; width:300px">
<asp:TextBox ID="txtName" runat="server" Width="300px" style="margin:10px"/>
</td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName" Display="Dynamic"
ErrorMessage="Name">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr style="margin-bottom: 10px ">
<td style="font-size: 14px">Organization (optional):</td>
<td><asp:TextBox ID="txtOrganization" runat="server" Width="300px" style="margin:10px" /></td>
<td>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="font-size:14px"> Phone (optional):</td>
<td><asp:TextBox ID="txtPhone" runat="server" Width="300px" style="margin:10px" /></td>
<td>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="font-size:14px">Email:</td>
<td><asp:TextBox ID="txtEmail" runat="server" Width="300px" style="margin:10px" /></td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ControlToValidate="txtEmail" Display="Dynamic"
ErrorMessage="Email">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr>
<td style="font-size:14px"> Message:</td>
<td><asp:TextBox ID="txtRequest" runat="server" TextMode="MultiLine" Width="300px" Height="60px" style="margin:10px" /></td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvRequest" runat="server"
ControlToValidate="txtRequest" Display="Dynamic"
ErrorMessage="Message">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SendMail" Width="60px" />
<asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="ResetEmail" Width="60px" CausesValidation="false" />
<!--<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Please fill out the required fields:" ShowMessageBox="true" ShowSummary="false" />-->
</td>
</tr>
</table>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal Contact Table-->
And last but not least, this is the code behind on the user control, and yes I know I can do this using my web.config also, and I tried that too with the same result:
public partial class pop_up_1 : System.Web.UI.UserControl
{
private bool IsValid;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendMail(object sender, EventArgs e)
{
if (IsValid)
{
//create a new email message
MailMessage mail = new MailMessage();
mail.From = new MailAddress("");
mail.To.Add("");
mail.Subject = "Information Request";
mail.IsBodyHtml = true;
mail.Body = "Name:" + this.txtName.Text + "<br />";
mail.Body += "Organization:" + txtOrganization.Text + "<br />";
mail.Body += "Phone:" + txtPhone.Text + "<br />";
mail.Body += "Email:" + txtEmail.Text + "<br />";
mail.Body += "Request or Question:" + txtRequest.Text + "<br />";
//Create SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "";
//Send the email
smtp.Send(mail);
//Define the name and type of the client script on the page.
String csName = "SuccessNotificationScript";
Type csType = this.GetType();
//Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
//Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
string csText = "<script language='javascript'>window.alert('Thank you for submitting your request');</script>";
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
//Clear the form
ClearForm();
}
}
protected void ResetEmail(object sender, EventArgs e)
{
ClearForm();
}
protected void ClearForm()
{
txtName.Text = "";
txtOrganization.Text = "";
txtPhone.Text = "";
txtEmail.Text = "";
txtRequest.Text = "";
}
}
}
Any suggestions or ideas, greatly appreciated. Thanks
here is the backend of my login page, I am using identity framework:
public partial class Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
//RegisterHyperLink.NavigateUrl = "Register";
// Enable this once you have account confirmation enabled for password reset functionality
// ForgotPasswordHyperLink.NavigateUrl = "Forgot";
//OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
if (!String.IsNullOrEmpty(returnUrl))
{
//RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
}
}
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = manager.Find(Email.Text, Password.Text);
if (user != null)
{
IdentityHelper.SignIn(manager, user, RememberMe.Checked);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
FailureText.Text = "Invalid username or password.";
ErrorMessage.Visible = true;
}
}
}
}
}
I would like to take all information stored in a repeater and place it in the body of an email message for sending. Basically, it's a product order form (which also makes use of a repeater) that sends users to an order review page with a form at the bottom that allows them to send the order information to someone else. I am allowed to set up the order information as a table. I have everything working, and my code successfully sends emails. However, I am not sure how to pull the order review repeater's contents into the message body for an email.
Any suggestions/tips are appreciated! Thanks!
Designer code:
<asp:Repeater ID="orderRepeater" runat="server" >
<itemtemplate>
<%# Eval("LocationName") %>
<div class="headerRow">
<div class="header">
<div class="thumb">
<p></p>
</div>
<div class="headerField name"><p class="hField">Product</p></div>
<div class="headerField sku"><p class="hField">GOJO SKU</p></div>
<div class="headerField size"><p class="hField">Size</p></div>
<div class="headerField case"><p class="hField">Case Pack</p></div>
<div class="headerField qty"><p class="hField">Quantity</p></div>
</div>
</div>
<div class="table">
<div class="row">
<div class="thumb"><%# Eval("Thumbnail") %></div>
<div class="field name"><p class="pField"> <%#Eval("ProductName") %> </p></div>
<div class="field sku"><p class="pField"> <%#Eval("Sku") %></p></div>
<div class="field size"><p class="pField"> <%#Eval("Size") %></p></div>
<div class="field case"><p class="pField"><%#Eval("CasePack") %></p></div>
<div class="field qty"><p class="pField"><%#Eval("Qty") %></p></div>
</div>
</div>
</itemtemplate>
</asp:Repeater>
<asp:placeholder id="form" runat="server">
<asp:label id="msgLbl" runat="server" text=""></asp:label>
<asp:hyperlink id="link" runat="server" visible="false" NavigateUrl="/united-states/market/office-buildings/obproductmap/ProductList" >Product Listing</asp:hyperlink><br />
<asp:hiddenfield id="emailTbl" runat="server"></asp:hiddenfield>
<div id="emailForm">
<asp:ValidationSummary ID="vsEmailForm" runat="server" ForeColor="red" DisplayMode="BulletList" /><br />
<div id="yourFields">
<div id="yNameInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvYName" ForeColor="red"
ControlToValidate="yName" errormessage="You must enter your name" Text="*"
Display="Dynamic" SetFocusOnError="True"></asp:requiredfieldvalidator>
Your Name:<br /> <asp:TextBox runat="server" id="yName" size="40"></asp:TextBox>
</div>
<div id="yEmailInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvYEmail" ForeColor="red"
ControlToValidate="yEmail" Display="Dynamic"
errormessage="You must enter your email" Text="*" SetFocusOnError="True"></asp:requiredfieldvalidator>
<asp:regularexpressionvalidator runat="server" id="revYEmail" ForeColor="red"
ControlToValidate="yEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
errormessage="Your email address is not valid. Please try again." Text="*"
Display="Dynamic" SetFocusOnError="True"></asp:regularexpressionvalidator>
Your Email: <br /> <asp:TextBox runat="server" id="yEmail" size="40"></asp:TextBox><br /><br />
</div>
</div>
<div id="reFields">
<div id="rNameInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvRName" ForeColor="red"
ControlToValidate="rName" Text="*"
errormessage="You must enter a recipient's name" Display="Dynamic"
SetFocusOnError="True"></asp:requiredfieldvalidator>
Recipient's Name: <br /><asp:TextBox runat="server" id="rName" size="40"></asp:TextBox>
</div>
<div id="rEmailInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvREmail" ForeColor="red"
ControlToValidate="rEmail" Display="Dynamic" Text="*"
errormessage="You must enter a recipient's email" SetFocusOnError="True"></asp:requiredfieldvalidator>
<asp:regularexpressionvalidator runat="server" id="revREmail" ForeColor="red"
ControlToValidate="rEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
errormessage="The recipient's email address is not valid. Please try again."
Text="*" Display="Dynamic" SetFocusOnError="True"></asp:regularexpressionvalidator>
Recipient's Email:<br /> <asp:TextBox runat="server" id="rEmail" size="40"></asp:TextBox><br /><br />
</div>
</div>
<div id="buttons">
<asp:Button id="submit" Text="Submit" runat="server" CausesValidation="true"
onclick="submitBtn" />
<asp:Button id="cancel" Text="Cancel" runat="server" CausesValidation="false" /><br /><br />
<asp:Button id="print" Text="Print" runat="server" CausesValidation="false "/>
<asp:Button id="pdf" Text="Save as PDF" runat="server" CausesValidation="false" />
</div>
</div>
</asp:placeholder>
<asp:placeholder id="sentMsg" visible="false" runat="server">
<asp:Label id="lbl" runat="server" Text="Your message has been sent!"></asp:Label>
</asp:placeholder>
Code behind:
protected void getOrder(Item CurrentItem)
{
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (Session["orderComplete"] != null && Session["orderComplete"] != "")
{
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoOrderReview']");
Database db = Sitecore.Context.Database;
DataSet dset = new DataSet();
if (ProductGroup != null)
{
string InFromSession = Session["orderComplete"].ToString();
try
{
DataTable summary = dset.Tables.Add("summary");
summary.Columns.Add("LocationName", Type.GetType("System.String"));
summary.Columns.Add("Thumbnail", Type.GetType("System.String"));
summary.Columns.Add("ProductName", Type.GetType("System.String"));
summary.Columns.Add("Sku", Type.GetType("System.String"));
summary.Columns.Add("Size", Type.GetType("System.String"));
summary.Columns.Add("CasePack", Type.GetType("System.String"));
summary.Columns.Add("Qty", Type.GetType("System.String"));
summary.Columns.Add("Location", Type.GetType("System.String"));
Label qL = (Label)FindControl("qty");
string[] orders = InFromSession.Split(';');
string tempheader = "";
foreach (string order in orders)
{
DataRow drow = summary.NewRow();
if (order != "")
{
string[] things = order.Split(',');
string skus = things.GetValue(0).ToString();
if (skus != "")
{
Item locName = db.Items[skus];
Item LocationItem = ScHelper.FindAncestor(locName, "gojoProductLocation");
if (LocationItem != null)
{
string LocationName = LocationItem.Fields["Header"].ToString();
if (tempheader != LocationName)
{
drow["LocationName"] = "<div><h1>" + LocationName + "</h1></div>";
tempheader = LocationName;
}
}
}
}
string purchase = order;
int total = orders.GetUpperBound(0);
if (purchase != "")
{
string[] infos = purchase.Split(',');
string ids = infos.GetValue(0).ToString();
string qtys = infos.GetValue(1).ToString();
if (ids != "")
{
Item anItem = db.Items[ids];
Item orderItem = db.Items[anItem.Fields["Reference SKU"].Value];
if (orderItem != null)
{
Item marketItem = db.Items[orderItem.Fields["Master Product"].Value];
if (marketItem != null)
{
Item CPNItem = db.Items[marketItem.Fields["Complete Product Name"].Value];
drow["Thumbnail"] = "";
Sitecore.Data.Fields.XmlField fileField = marketItem.Fields["Thumbnail"];
drow["Thumbnail"] = "<image src=\"" + ScHelper.GetCorrectFilePath(fileField) + "\" border=\"0\" alt=\"\">";
if (CPNItem != null)
{
var name = CPNItem["Complete Name"];
drow["ProductName"] = name;
}
drow["Sku"] = marketItem.Fields["SKU"].Value;
drow["CasePack"] = marketItem.Fields["Case Pack"].Value;
if (marketItem.Fields["Size"] != null)
{
drow["Size"] = marketItem.Fields["Size"].Value;
}
else
{
drow["Size"] = "N/A";
}
drow["Qty"] = qtys.ToString();
summary.Rows.Add(drow);
}
}
}
}
}
orderRepeater.DataSource = dset;
orderRepeater.DataMember = "summary";
orderRepeater.DataBind();
}
catch (Exception x)
{
//
}
}
}
}
else
{
HyperLink none = (HyperLink)FindControl("link");
Label msg = (Label)FindControl("msgLbl");
none.Visible = true;
msg.Text = "You have not selected any items for purchase. To purchase items, please visit our complete product listing: ";
}
}
protected void sendEmail()
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoOrderReview");
if (HomeItem != null)
{
TextBox rTxt = (TextBox)FindControl("rEmail");
TextBox fName = (TextBox)FindControl("yName");
try
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.To.Add(rTxt.Text);
msg.Subject = "GOJO product order summary";
msg.From = new System.Net.Mail.MailAddress("donotreply#GOJO.com");
msg.Body = "Here is a list of the products your friend, " + fName.Text + ", has selected: ";
msg.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient("mail.innismaggiore.com");
sc.Send(msg);
}
catch (Exception EX)
{
GOJOHelper.WriteLog("GOJO Order Review - sendEmail()", EX.ToString());
}
}
}
protected void submitBtn(object sender, EventArgs e)
{
if (Page.IsValid)
{
Database db = Factory.GetDatabase("master");
PlaceHolder form = (PlaceHolder)FindControl("form");
PlaceHolder sent = (PlaceHolder)FindControl("sentMsg");
using (new SecurityDisabler())
{
sendEmail();
form.Visible = false;
sent.Visible = true;
}
}
}
}
I think this answer has what you're looking for. Basically, you can use javascript to send the html to the server in order to include it in your email:
asp.net get html controls in code behind
Also, make sure you include a ValidateRequest="false" on the page in order to post back html
if someone else has same problem and the repeater object has no image this solution is simple and easy instead of trust to a client javascript feedback !!
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =new HtmlTextWriter(stringWrite);
Repeater1.RenderControl(htmlWrite);string emailContent = stringWrite.ToString();
I'm trying to receive an email once my form is submitted on my webpage. At the moment it submits fine without any errors but I don't receive the email. Does anyone know what code I have to add in the code behind page to make this work?
Here is the html;
<h2>Contact Us</h2>
<br />
<table>
<tr>
<td style="align-items:center">
Name:</td>
<td>
<asp:TextBox ID="txtName"
runat="server"
Columns="40"></asp:TextBox>
</td>
</tr>
<tr>
<td style="align-items:center">
email:</td>
<td>
<asp:TextBox ID="txtEmail"
runat="server"
Columns="40"></asp:TextBox>
</td>
</tr>
<!-- Message -->
<tr>
<td style="align-items:center">
What are you looking for?
</td>
<td>
<asp:TextBox ID="txtMessage"
runat="server"
Columns="40"
Rows="6"
TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td style="align-items:center">
What would you be willing to pay for this app?</td>
<td>
<asp:TextBox ID="txtPay"
runat="server"
Columns="40"></asp:TextBox>
</td>
</tr>
<!-- Submit -->
<tr style="align-items:center">
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" /><br />
</td>
</tr>
<!-- Results -->
<tr style="align-items:center">
<td colspan="2">
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td>
</tr>
</table>
this is the code behind;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Telluswhatyouwant : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("ronan.byrne#mhlabs.net");
//Send the msg
client.Send(msg);
This is a perfectly working code for localhost where mailing option is enabled. You can change the port number.fromWho, toWho are mailing addresses in string format (ie: david#yahoo.com)
string sMailServer = "127.0.0.1";
MailMessage MyMail = new MailMessage();
MyMail.From = fromWho;
MyMail.To = toWho;
if (toCC != "" || toCC != null)
{
MyMail.Cc = toCC;
}
if (toBCC != "" || toBCC != null)
{
MyMail.Bcc = toBCC;
}
MyMail.Subject = Subject;
MyMail.Body = Body;
//MyMail.BodyEncoding = Encoding.UTF8;
MyMail.BodyFormat = MailFormat.Html;
SmtpMail.SmtpServer = sMailServer;
try
{
SmtpMail.Send(MyMail);
}
catch (Exception ex)
{
return ex;
}
You can try this and make sure you are using valid login credential and you have proper internet connection:
MailMessage mail = new MailMessage();
mail.Subject = "Your Subject";
mail.From = new MailAddress("senderMailAddress");
mail.To.Add("ReceiverMailAddress");
mail.Body = "Hello! your mail content goes here...";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
NetworkCredential netCre =
new NetworkCredential("SenderMailAddress","SenderPassword" );
smtp.Credentials = netCre;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
// Handle exception here
}
Where you have configured your client Object. Give complete detail.
Then go through the following post answered by me. You should configure your SmtpClient properly.
How to send email in ASP.NET C#