Send information stored in a repeater to email recipient? - c#

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();

Related

Cannot add class to aspx.cs file

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().

Session on Textbox with asp.net and c#

I'am try to make a session on a Textbox in asp.net, that textbox allows the user to enter values from 1-4, but whenever I click on button "book", it gives me an null pointer exception, I am using FindControl function from my c# backend.
Here's my code
.aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/Main.Master" AutoEventWireup="true" CodeBehind="hotels_main.aspx.cs" Inherits="Hotel_Mangement.hotels_main" %>
<asp:Content ID="Content1" ContentPlaceHolderID="hotels_main" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="free website templates, hotel and travel, CSS, XHTML, design layout" />
<meta name="description" content="Hotel and Travel - free website template provided by templatemo.com" />
<link href="/css/templatemo_style.css" rel="stylesheet" type="text/css" />
<div id="templatemo_container">
<!-- Free Website Template by www.TemplateMo.com -->
<div id="templatemo_content">
<div id="content_left" style="background-color:#2C3E50">
<div class="content_left_section">
<div class="content_title_01">Confirm Your Booking</div>
<form id="form1" >
<div class="form_row">
<br /><br />
<big>Check in:</big>
<asp:Calendar ID="checkin" runat="server" OnDayRender="checkin_DayRender" ></asp:Calendar>
<br /><br />
<big>Check out:</big> <asp:Calendar ID="checkout" runat="server" OnDayRender="checkout_DayRender1" ></asp:Calendar>
<br /><br />
<big>Number of room:</big> <asp:TextBox ID="rooms" runat="server" ForeColor="black" placeholder="Number of rooms" type="number" min="1" max="2"></asp:TextBox>
<br /><br />
<big>Number of members per room:</big> <asp:TextBox ID="members" runat="server" ForeColor="black" placeholder="Number of members" type="number" min="1" max="4"></asp:TextBox>
<br /> <br />
<asp:Button ID="book" runat="server" Text="Book" ForeColor="Black" Width="200px" Height="30px" OnClick="book_Click"></asp:Button>
</div>
<div class="cleaner"> </div>
</div> <!-- end of booking -->
<div class="cleaner_h30"> </div>
<div class="cleaner_horizontal_divider_01"> </div>
<div class="cleaner_h30"> </div>
<div class="content_left_section">
<div class="content_title_01">Contact Details</div>
<div class="news_title">Address</div>
<p>The Taj Mahal Palace<br />Apollo Bunder, Near Gateway Of India, Colaba , Mumbai , Maharashtra , India<br />Pincode- 400001</p>
<div class="cleaner_h30"> </div>
<div class="news_title">Phone</div>
<p>022 6665 3366 </p>
<div class="cleaner_h20"> </div>
<div class="news_title">Email Support</div>
<p>reservations#tajhotels.com</p>
</div> <!-- end of news section -->
<div class="cleaner_h30"> </div>
<div class="cleaner_horizontal_divider_01"> </div>
<div class="cleaner_h30"> </div>
<div class="cleaner_h30"> </div>
</div> <!-- end of content left -->
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div id="content_right">
<div class="content_right_section">
<div class="content_title_01">Welcome to The <asp:Label ID="lblhotelname" runat="server" Text='<%#Eval("hotel_name") %>'></asp:Label> </div>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("ImagePath") %>' Height="200px" width="200px"/>
<p><%#Eval("d_desc") %>. </p>
</div>
<div class="cleaner_h40"> </div>
<div class="content_right_2column_box">
<div class="content_title_01">Hotel Facilities</div>
<p> <%#Eval("hotel_facilties") %></p>
</div>
<div class="content_right_2column_box">
<div class="content_title_01">Policies</div>
<ul>
<asp:Label ID="lblpolicies" runat="server" Text='<%#Eval("hotel_policies") %>'></asp:Label>
</ul>
<div class="cleaner_h10"> </div>
</div>
<div class="cleaner_h40"> </div>
<div class="content_right_section">
<div class="content_title_01">Hotel location</div>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("hotel_location") %>'></asp:Label>
<div class="cleaner_h20"> </div>
<div class="cleaner"> </div>
</div>
<div class="content_right_section">
<div class="content_title_01">Hotel price per room</div>
<asp:FormView ID="FormView1" runat="server"></asp:FormView>
<asp:Label ID="lblhotelprice" runat="server" Text='<%#Eval("price")%>'></asp:Label>
<div class="cleaner_h20"> </div>
<div class="cleaner"> </div>
</div>
<div class="cleaner_h20"> </div>
</div> <!-- end of content right -->
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</asp:Content>
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace Hotel_Mangement
{
public partial class hotels_main : System.Web.UI.Page
{
int id;
int t1main, t2main, totalmain;
public static List<DateTime> list = new List<DateTime>();
SqlConnection con = new SqlConnection(#"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("hotels.aspx");
}
else
{
id = Convert.ToInt32(Request.QueryString["id"].ToString());
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from hotels_main where hotel_id=" + id + "";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
con.Close();
}
}
protected void checkin_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < DateTime.Now.Date)
{
e.Day.IsSelectable = false;
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Strikeout = true;
}
Session["checkinmain"] = list;
}
protected void checkout_DayRender1(object sender, DayRenderEventArgs e)
{
if ((e.Day.Date < DateTime.Now.Date) || (e.Day.Date < checkin.SelectedDate))
{
e.Day.IsSelectable = false;
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Strikeout = true;
}
Session["checkoutmain"] = list;
}
protected void book_Click(object sender, EventArgs e)
{
if (Session["USER_ID"] == null)
{
Response.Redirect("login.aspx");
}
else
{
TextBox rooms = (TextBox)FindControl("rooms");
Session["roomsmain"] = rooms.Text;
TextBox members = (TextBox)FindControl("members");
Session["membersmain"] = members.Text;
Label lblhotelprice = (Label)FindControl("lblhotelprice");
Session["initialprice"] = lblhotelprice.Text;
t1main = Convert.ToInt32(Session["roomsmain"].ToString());
t2main = Convert.ToInt32(Session["initialprice"].ToString());
totalmain = t1main * t2main;
Session["totalpricemain"] = totalmain;
con.Open();
string insertQuery = "insert into hotel_booking_details(username,hotel_name,hotel_location,check_in,check_out,members,rooms,initial_price,total_price) values('" + Session["USER_ID"].ToString() + "','" + Session["hotel_name"].ToString() + "','" + Session["hotel_location"].ToString() + "','" + Session["checkinmain"].ToString() + "','" + Session["checkoutmain"].ToString() + "','" + Session["membersmain"].ToString() + "','" + Session["roomsmain"].ToString() + "','" + Session["initialprice"].ToString() + "','" + Session["totalpricemain"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(insertQuery, con);
cmd1.ExecuteNonQuery();
con.Close();
Response.Redirect("pay.aspx");
}
}
}
}
First of all, you cannot use another form tag in ASP.Net. You will need to remove <form id="form1" >.
it gives me an null pointer exception, I am using FindControl function
from my c# backend.
TextBox rooms = (TextBox)FindControl("rooms");
About code tries to find rooms textbox inside Page control. rooms control is not a direct child of Page control.
You will need to the find control recursively. Here is the helper method -
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
Usage
TextBox rooms = (TextBox)FindControlRecursive(Page, "rooms");

Why is my smtp SendMail prohibiting Log in fuctions, on site master?

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;
}
}
}
}
}

Drag-Drop item from one data group to another data group in Telerik RadListView

I am trying to use the Telerik RadListView Drag-Drop feature:
http://demos.telerik.com/aspnet-ajax/listview/examples/datagrouping/defaultcs.aspx
The code below works fine but loops through all the items to find the "e.DestinationHtmlElement" which is not efficient. I want to be able to drag an item from one data group to another data group for Telerik RadListView with a better algorithm. How can I do that?
ASPX Code:
<telerik:RadListView runat="server" ID="Lsv_Vis" AllowPaging="True" PageSize="50"
ItemPlaceholderID="Phi_Vis_I" GroupPlaceholderID="Phi_Vis_G"
DataKeyNames="url_id, lst_id, url_name, url_address"
ClientDataKeyNames="url_id, lst_id, url_name, url_address"
OnItemDrop="CsVisItemDrop" OnItemDataBound="CsVisIDB" DataSourceID="Sql_Vis">
</telerik:RadListView>
<DataGroups>
<telerik:ListViewDataGroup GroupField="lst_id" DataGroupPlaceholderID="Phi_Vis_G">
<DataGroupTemplate>
<div class="Div_Vis_Grp"><span class="Spn_Vis"><%# (Container as RadListViewDataGroupItem).AggregatesValues["lst_name"].ToString() %></span></div>
<asp:Panel ID="Pnl_Vis" runat="server" CssClass="Pnl_Vis" ToolTip='<%# (Container as RadListViewDataGroupItem).DataGroupKey %>' onmouseover='this.className += " Vis_Sel";' onmouseout='this.className = this.className.split(" Vis_Sel").join("");'>
<asp:PlaceHolder ID="Phi_Vis_I" runat="server" />
</asp:Panel>
</DataGroupTemplate>
<GroupAggregates>
<telerik:ListViewDataGroupAggregate Aggregate="Max" DataField="lst_name" />
</GroupAggregates>
</telerik:ListViewDataGroup>
</DataGroups>
<ItemTemplate>
<div class="Div_Vis_Item rlvI">
<asp:Panel ID="Pnl_Vis" runat="server" ToolTip='<%# Eval("lst_id") %>' CssClass="Div_Vis_Item" onmouseover='this.className += " Vis_Sel";' onmouseout='this.className = this.className.split(" Vis_Sel").join("");'>
<a class="Hyp_Vis" runat="server" href='<%# Eval("url_address") %>' target="_blank">
<div class="Div_Vis_Body">
<div class="Div_Vis_Con">
<asp:Panel ID="Div_Vis_Con" runat="server" class="Div_Vis_Con" ToolTip='<%# Eval("lst_id") %>' ></asp:Panel>
</div>
</div>
<div class="Div_Vis_Link">
<asp:Label ID="Lbl_VisI" runat="server" Text='<%# Eval("url_name_short") %>' ToolTip='<%# Eval("url_name") %>'/>
</div>
</a>
</asp:Panel>
</div>
</ItemTemplate>
C# Code:
protected void CsVisItemDrop (object sender, RadListViewItemDragDropEventArgs e)
{
if (e.DestinationHtmlElement.IndexOf("Div_Vis_Con") < 0)
{
return;
}
foreach (RadListViewDataItem di in Lsv_Vis.Items)
{
Panel pnl = di.FindControl("Div_Vis_Con") as Panel;
if (pnl != null && pnl.ClientID == e.DestinationHtmlElement)
{
string uid = e.DraggedItem.GetDataKeyValue("url_id").ToString();
string lid = pnl.ToolTip.ToString();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Con_Str"].ToString()))
{
using (SqlCommand cmd = new SqlCommand("UPDATE [MyTable] SET lst_id = #lst_id WHERE url_id = #url_id", conn))
{
cmd.Parameters.Add("#lst_id", SqlDbType.VarChar).Value = lid;
cmd.Parameters.Add("#url_id", SqlDbType.VarChar).Value = uid;
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch { }
}
}
}
}
Lsv_Vis.Rebind();
}

Contact form in SiteFinity C#

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.

Categories