I am using c# and I have a Hidden Field
<asp:HiddenField runat="server" ID="hidJsonHolder" ClientIDMode="Static" />
How do I add a alert, so that I can check for empty data object obj get from Hidden Field ?
I have tried with RegularExpressionValidator but reply error
<asp:HiddenField runat="server" ID="hidJsonHolder" ClientIDMode="Static" />
<asp:RegularExpressionValidator Display="Dynamic"
ControlToValidate="hidJsonHolder"
ID="RegularExpressionValidator1"
runat="server" ErrorMessage="error"
ValidationGroup="Validation2"></asp:RegularExpressionValidator>
This other code not alert
protected void btnFinal_Click(object sender, EventArgs e)
{
JavaScriptSerializer jsSer = new JavaScriptSerializer();
object obj = jsSer.DeserializeObject(hidJsonHolder.Value);
if (obj != null)
{
Movie[] listMovie = jsSer.ConvertToType<Movie[]>(obj);
foreach (Movie p in listMovie)
{
string pattern = #"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*";
Regex re = new Regex(pattern);
if (p.ToString() != null)
{
MatchCollection matches = re.Matches(p.ToString());
if (matches.Count > 0)
{
for (int i = 0; i < matches.Count; i++)
{
Response.Write(matches[i] + "; ");
}
}
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('Error.');", true);
}
}
Edit #1
Like this:
protected void btnFinal_Click(object sender, EventArgs e)
{
string val = hidJsonHolder.Value.Replace("[]","");
if (!String.IsNullOrEmpty(val.ToString()))
{
JavaScriptSerializer jsSer = new JavaScriptSerializer();
object obj = jsSer.DeserializeObject(hidJsonHolder.Value);
if (obj != null)
{
Movie[] listMovie = jsSer.ConvertToType<Movie[]>(obj);
foreach (Movie p in listMovie)
{
string pattern = #"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*";
Regex re = new Regex(pattern);
if (p.ToString() != null)
{
MatchCollection matches = re.Matches(p.ToString());
if (matches.Count > 0)
{
for (int i = 0; i < matches.Count; i++)
{
Response.Write("<br />" + matches[i] + "; ");
}
}
}
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('Error.');", true);
}
}
Related
I'm having an issue in some of my code, i cannot seem to think of the best way to do this, all i want to do is extract a URL from a pop3 email message depending on if the domain is in the "to check" array, for example if "stackoverflow.com" is in the email message, i would extract all urls in the message body that contains "stackoverflow.com" in it, and just perform a quick WebClient() request with that url.
Code:
private void BgwEmails_DoWork_1(object sender, DoWorkEventArgs e)
{
try
{
bool finished = false;
Pop3Client pop3 = new Pop3Client();
if (pop3.Connected)
{
pop3.Disconnect();
}
pop3.Connect(txtBoxMailServer.Text, int.Parse(txtBoxPort.Text), chkSSL.Checked);
pop3.Authenticate(txtBoxUsername.Text, txtBoxPassword.Text, AuthenticationMethod.UsernameAndPassword);
int messageCount = pop3.GetMessageCount();
if (messageCount == 0)
{
return;
}
Helpers.ReturnMessage("[ " + messageCount + " ] Message(s) in your inbox.");
int count = 0;
for (int d = 1; d <= messageCount; d++)
{
bgwEmails.WorkerSupportsCancellation = true;
if (bgwEmails.CancellationPending)
{
e.Cancel = true;
Helpers.ReturnMessage($"Cancelling link activator ...");
return;
}
if (finished)
{
return;
}
OpenPop.Mime.Message message = null;
message = pop3.GetMessage(d);
if (null == message || null == message.MessagePart || null == message.MessagePart.MessageParts) {
continue;
}
string textFromMessage = null;
try
{
textFromMessage = message?.MessagePart?.MessageParts[0]?.GetBodyAsText();
} catch (Exception) {
continue;
}
MessagePart messagePart = message.MessagePart.MessageParts[0];
if (null == messagePart || null == messagePart.BodyEncoding || null == messagePart.Body || null == messagePart.BodyEncoding.GetString(messagePart.Body)) {
continue;
}
string linkToCheck;
using (var wc = new WebClient())
{
linkToCheck = wc.DownloadString("https://www.thesite.com/api.php?getActivationLinks=1");
}
var linksToClickArray = linkToCheck.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
//Helpers.ReturnMessage(textFromMessage);
for (var i = 0; i < linksToClickArray.Length; i++)
{
var regex = new Regex(linksToClickArray[i], RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
var matches = regex.Matches(textFromMessage);
foreach (Match match in matches)
{
if (match.Success)
{
count++;
Invoke(new MethodInvoker(() => { listBoxEmailsClicked.Items.Add("Clicked: " + match.Value); }));
using (WebClient wc = new WebClient())
{
Helpers.ReturnMessage(match.Value);
wc.DownloadString(match.Value);
}
}
}
}
if (null != textFromMessage)
{
Invoke(new MethodInvoker(() => { txtStatusMessages.AppendText(textFromMessage); }));
}
}
Helpers.ReturnMessage($"Emails downloaded successfully! You clicked [ " + count + " ] activation links.");
} catch (Exception ex) {
Helpers.ReturnMessage($"POP3 Error: " + ex.Message + ".");
}
}
I do a request here: https://www.thesite.com/api.php?getActivationLinks=1 which contains a list of domains to check for in the messages, they just come back one line at a time like:
thesite1.com
thesite2.com
etc
The code works as far as connetcing and downloading, i just cannot seem to think of a way to parse of the urls only if it matches a domain in the target list, any help or advice would be appreciated.
I have a page in C# on .NET that has a dropdown menu that is populated from a database the dropdown contains dialing codes for mobile phone numbers and defaults to 'United Kingdom (+44)'
However I also have a mobile number box where user can enter there mobile number. At the moment if the user saves without a mobile number (which is allowed) the dialing code will still get passed to the SP and ultimately be saved.
I want to find a way to stop this happening so if a user does not enter a mobile number the dialing code is set to null when entered in the database.
What is the best way to do this?
This is the C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Dnuk.Core.DataAccess.UserOptIn;
using Dnuk.Core.Entities2;
using Dnuk.Core.DataAccess.CommonData;
using Dnuk.Core.DataAccess.Framework;
namespace Registration
{
/// <summary>
/// Summary description for Step2.
/// </summary>
public partial class Step2 : Basepage
{
protected int countryid = 240;
protected AJAXFunctions m_AJAXFunctions;
protected void Page_Load(object sender, System.EventArgs e)
{
StringBuilder helptext = new StringBuilder();
helptext.AppendLine("<span class='bluetext2'>Your password must:-</span>");
helptext.AppendLine("");
helptext.AppendLine("<ul class='bluetext2'>");
helptext.AppendLine(" <li>Have at least 9 characters</li>");
helptext.AppendLine(" <li>Contain mixed case letters</li>");
helptext.AppendLine(" <li>Contain at least 1 number OR a special character</li>");
helptext.AppendLine("</ul>");
helptext.AppendLine("");
helptext.AppendLine("<p class='bluetext2'>Allowed characters are: a-z, A-Z, 0-9, and these special characters: !##$*^().,{}[]~-</p>");
helptext.AppendLine("");
helptext.AppendLine("<span class='bluetext2'>Not accepted:-</span>");
helptext.AppendLine("");
helptext.AppendLine("<ul class='bluetext2'>");
helptext.AppendLine(" <li>the word 'password'</li>");
helptext.AppendLine(" <li>using your username</li>");
helptext.AppendLine("</ul>");
Helpicon11.Text = helptext.ToString();
m_AJAXFunctions = new AJAXFunctions();
m_AJAXFunctions.Register();
if (!Page.IsPostBack)
{
ddlSpecialityList.Attributes.Add("onchange", "SpecialityList_Change();");
lsbSubSpecialityUser.Style.Add("width", "200px");
imbNext.Attributes.Add("onclick", "return Validation();");
ddlProfessionalStatusList.Attributes.Add("onchange", "CheckProfStatusSeniority();");
ddlSeniorityList.Attributes.Add("onchange", "CheckProfStatusSeniority();");
ddlCountry.Attributes.Add("onchange", "ChangeCountry();");
FillData();
FillUserData();
}
}
protected void ddlSeniorityList_Fill()
{
ddlSeniorityList.DataTextField = "name";
ddlSeniorityList.DataValueField = "seniorityid";
using (DBAccess db = new DBAccess())
{
ddlSeniorityList.DataSource = (db.GetSpecialitySeniorityList(countryid)).Tables[0];
}
ddlSeniorityList.DataBind();
ddlSeniorityList.Items.Insert(0, new ListItem("please select", "0"));
}
protected void ddlSpecialityList_Fill()
{
ddlSpecialityList.DataTextField = "name";
ddlSpecialityList.DataValueField = "specialityid";
using (DBAccess db = new DBAccess())
{
ddlSpecialityList.DataSource = (db.GetSpecialitySeniorityList(countryid)).Tables[1];
}
ddlSpecialityList.DataBind();
ddlSpecialityList.Items.Insert(0, new ListItem("please select", "0"));
}
protected void ddlProfessionalStatusList_Fill()
{
ddlProfessionalStatusList.DataTextField = "title";
ddlProfessionalStatusList.DataValueField = "ProfStatusId";
using (DBAccess db = new DBAccess())
{
ddlProfessionalStatusList.DataSource = db.GetProfessionalStatusList();
}
ddlProfessionalStatusList.DataBind();
}
protected void ddlCountry_Fill()
{
ddlCountry.DataTextField = "countryname";
ddlCountry.DataValueField = "countryid";
using (DBAccess db = new DBAccess())
{
ddlCountry.DataSource = db.GetCountryList();
}
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, new ListItem("please select", "0"));
}
protected void cLVOptins_Fill()
{
UserOptInDAO userOptInDAO = new UserOptInDAO();
cLVOptins.DataSource = userOptInDAO.GetRegistrationOptInList();
cLVOptins.DataBind();
}
private void FillData()
{
ddlSeniorityList_Fill();
ddlSpecialityList_Fill();
ddlProfessionalStatusList_Fill();
ddlCountry_Fill();
cLVOptins_Fill();
}
protected void FillUserData()
{
if (Session["Registration_RegInfo"] != null)
{
RegInfo ri = (RegInfo)Session["Registration_RegInfo"];
if (ddlSeniorityList.Items.FindByValue(Convert.ToString(ri.SeniorityID)) != null)
ddlSeniorityList.SelectedValue = Convert.ToString(ri.SeniorityID);
if (ddlSpecialityList.Items.FindByValue(Convert.ToString(ri.SpecialityID)) != null)
ddlSpecialityList.SelectedValue = Convert.ToString(ri.SpecialityID);
ddlProfessionalStatusList.SelectedValue = Convert.ToString(ri.ProfessionalStatusID);
hdnPCT_NHSID.Value = Convert.ToString(ri.PCT_NHSID);
hdnGP_TrustID.Value = Convert.ToString(ri.GP_TrustID);
using (DBAccess helper = new DBAccess())
{
if (ri.HPOTypeIDs != null)
{
hdnHPOTypeIDs.Value = Convert.ToString(ri.HPOTypeIDs);
}
else
{
//the default HPO types should be "All"
DataTable dt = helper.GetHPOTypes();
foreach (DataRow dr in dt.Rows)
{
hdnHPOTypeIDs.Value += Convert.ToString(dr["OrgnTypeID"]) + ",";
}
if (hdnHPOTypeIDs.Value.Length > 0)
hdnHPOTypeIDs.Value = hdnHPOTypeIDs.Value.Substring(0, hdnHPOTypeIDs.Value.Length-1);
}
this.lblSelectedOrgTypes.Text = helper.GetHPOTypeNames(hdnHPOTypeIDs.Value);
}
ddlDialingCode.Text = ri.DialingCodeText;
txbPostcode.Text = ri.Postcode;
txbLocality.Text = ri.Locality;
txbAddress1.Text = ri.Address1;
txbAddress2.Text = ri.Address2;
txbCity.Text = ri.City;
txbCounty.Text = ri.County;
if (ri.CountryID != 0)
ddlCountry.SelectedValue = Convert.ToString(ri.CountryID);
else
ddlCountry.SelectedValue = "240";
txt_username.Value = ri.Username;
txbAltEMail.Text = ri.AltEMail;
if (ri.DialingCodeID != 0)
ddlDialingCode.SelectedValue = Convert.ToString(ri.DialingCode);
else
ddlDialingCode.SelectedValue = "240";
txbPhoneNumber.Text = ri.PhoneNumber;
if (ri.SubSpecialityIDs != null)
SubSpecialityIDs = ri.SubSpecialityIDs;
txbSecWord1.Text = ri.SecWord1;
txbSecWord2.Text = ri.SecWord2;
if (ri.OptIns != null)
{
foreach (KeyValuePair<Int32, bool> entry in ri.OptIns)
{
foreach (ListViewItem item in cLVOptins.Items)
{
CheckBox chkBox = (CheckBox)item.FindControl("cCbOptIn");
Int32 optInId = Convert.ToInt32(chkBox.InputAttributes["optId"]);
if (optInId == entry.Key)
{
chkBox.Checked = entry.Value;
break;
}
}
}
}
}
}
private void PutRegInfo()
{
if (Session["Registration_RegInfo"] != null)
{
RegInfo ri = (RegInfo)Session["Registration_RegInfo"];
ri.SeniorityID = Convert.ToInt32(ddlSeniorityList.SelectedValue);
ri.SpecialityID = Convert.ToInt32(ddlSpecialityList.SelectedValue);
ri.SubSpecialityIDs = SubSpecialityIDs;
ri.PCT_NHSID = Convert.ToInt32(hdnPCT_NHSID.Value);
ri.GP_TrustID = Convert.ToInt32(hdnGP_TrustID.Value);
ri.HPOTypeIDs = Convert.ToString(hdnHPOTypeIDs.Value);
ri.ProfessionalStatusID = Convert.ToInt32(ddlProfessionalStatusList.SelectedValue);
ri.Postcode = txbPostcode.Text.Trim();
ri.Locality = txbLocality.Text.Trim();
ri.Address1 = txbAddress1.Text.Trim();
ri.Address2 = txbAddress2.Text.Trim();
ri.City = txbCity.Text.Trim();
ri.County = txbCounty.Text.Trim();
ri.CountryID = Convert.ToInt32(ddlCountry.SelectedValue);
ri.Username = txt_username.Value.Trim();
ri.Password = txt_newpassw.Value.Trim();
ri.AltEMail = txbAltEMail.Text.Trim();
ri.PhoneNumber = txbPhoneNumber.Text.Trim();
ri.DialingCodeID = Convert.ToInt32(ddlDialingCode.SelectedValue);
ri.DialingCode = ddlDialingCode.SelectedValue;
ri.DialingCodeText = ddlDialingCode.SelectedItem.Text;
ri.SecWord1 = txbSecWord1.Text.Trim();
ri.SecWord2 = txbSecWord2.Text.Trim();
// string fields
ri.Seniority = ddlSeniorityList.SelectedItem.Text;
ri.Speciality = ddlSpecialityList.SelectedItem.Text;
ri.SubSpecialities = SubSpecialities;
ri.PCT_NHS = hdnPCT_NHS.Value;
ri.GP_Trust = hdnGP_Trust.Value;
ri.ProfessionalStatus = ddlProfessionalStatusList.SelectedItem.Text;
ri.Country = ddlCountry.SelectedItem.Text;
if (ri.OptIns == null)
ri.OptIns = new Dictionary<int, bool>();
ri.OptIns.Clear();
foreach (ListViewItem item in cLVOptins.Items)
{
CheckBox chkBox = (CheckBox)item.FindControl("cCbOptIn");
Int32 optInId = Convert.ToInt32(chkBox.InputAttributes["optId"]);
ri.OptIns.Add(optInId, chkBox.Checked);
}
Session.Add("Registration_RegInfo", ri);
}
}
protected void imbNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
// check passwords
using (DBAccess da = new DBAccess())
{
UP_Validation_Username.Username upv_uname = new UP_Validation_Username.Username();
UP_Validation_Password.Password upv_pass = new UP_Validation_Password.Password();
string codes = string.Empty;
string codes1 = string.Empty;
string codes2 = string.Empty;
System.Configuration.AppSettingsReader _configReader = new System.Configuration.AppSettingsReader();
string skey = _configReader.GetValue("UP_SecurityKey", typeof(string)).ToString();
codes1 = upv_pass.Password_Validation_Lite(skey, txt_username.Value, txt_newpassw.Value, txt_newpassw1.Value);
codes2 = upv_uname.Username_Validation(skey, txt_username.Value, 0);
if (codes1 == "1" && codes2 == "1")
{
codes = "1";
}
else
{
codes = codes1 + "," + codes2;
char[] comma = new char[] { ',' };
codes = codes.TrimEnd(comma);
codes = codes.TrimStart(comma);
}
if (codes != "1")
{
err_username.InnerHtml = "";
err_newpassw.InnerHtml = "";
err_newpassw1.InnerHtml = "";
DataSet ds = new DataSet();
ds = upv_pass.GetErrorMessages(skey, codes);
if (ds.Tables.Count > 0)
{
DataTable dt = new DataTable();
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
switch (dr["type"].ToString())
{
case "username":
err_username.InnerHtml = err_username.InnerHtml + dr["message"].ToString() + "<br/>";
break;
case "newpassword":
err_newpassw.InnerHtml = err_newpassw.InnerHtml + dr["message"].ToString() + "<br/>";
break;
case "newpassword1":
err_newpassw1.InnerHtml = err_newpassw1.InnerHtml + dr["message"].ToString() + "<br/>";
break;
}
}
}
}
else
{
PutRegInfo();
if (Request.QueryString["redirecttoansaedu"] != null)
Response.Redirect("Step3.aspx?redirecttoansaedu=1", true);
else Response.Redirect("Step3.aspx", true);
}
}
}
protected int[] SubSpecialityIDs
{
get
{
const char DELIMITER = '\x0001';
string[] sArray;
if (hdnSubSpecialityIDs.Value == "")
sArray = new string[0];
else
sArray = hdnSubSpecialityIDs.Value.Split(DELIMITER);
return ConvertArray_ToInt(sArray);
}
set
{
const char DELIMITER = '\x0001';
hdnSubSpecialityIDs.Value = String.Join(Convert.ToString(DELIMITER), ConvertArray_ToString(value));
}
}
protected string[] SubSpecialities
{
get
{
const char DELIMITER = '\x0001';
if (hdnSubSpecialityIDs.Value == "")
return new string[0];
else
return hdnSubSpecialities.Value.Split(DELIMITER);
}
set
{
const char DELIMITER = '\x0001';
hdnSubSpecialities.Value = String.Join(Convert.ToString(DELIMITER), value);
}
}
protected int[] ConvertArray_ToInt(object[] array)
{
int[] result = new int[array.Length];
for (int i = 0; i < array.Length; i++)
result[i] = Convert.ToInt32(array[i]);
return result;
}
protected string[] ConvertArray_ToString(int[] array)
{
string[] result = new string[array.Length];
for (int i = 0; i < array.Length; i++)
result[i] = Convert.ToString(array[i]);
return result;
}
protected void cLVOptins_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem || e.Item.ItemType == ListViewItemType.EmptyItem)
{
UserOptIn optIn = (UserOptIn)e.Item.DataItem;
//Hide the help icon when there is no helptext
if (optIn.HelpText == string.Empty)
{
Registration.Controls.HelpIcon helpIcon = (Registration.Controls.HelpIcon)e.Item.FindControl("cHelpIconOptIn");
helpIcon.Visible = false;
}
//Remove indent where there is no parent
if (optIn.ParentId == 0)
{
Label cLblIndent = (Label)e.Item.FindControl("cLblIndent");
cLblIndent.Visible = false;
}
CheckBox chkBox = (CheckBox)e.Item.FindControl("cCbOptIn");
chkBox.Checked = optIn.Default;
chkBox.InputAttributes.Add("optId", optIn.Id.ToString());
//bit of a hack
if (optIn.Description.IndexOf("Market Research invitations") > -1)
{
chkBox.Text = chkBox.Text + "<div class=\"greytext1 optInIndent\" optparentid=\"1\">You will receive invitations through the Doctors.net.uk website or by e-mail. Some surveys are also conducted by telephone. To ensure you are invited to these surveys as well, please indicate this below.</div>";
}
}
}
protected void DialingCodeDropDown_Init(object sender, EventArgs e)
{
CommonDataSource cds = new CommonDataSource();
cds.SQLExecutorSource = new SQLHelperExecutorSource();
List<RefCountry> countries = cds.RefCountries();
List<ListItem> adjustedCountriesList = new List<ListItem>();
foreach (RefCountry country in countries)
{
if (country.DiallingCode.Trim() == "")
continue;
ListItem item = new ListItem();
item.Value = country.CountryID.ToString();
item.Text = String.Format("{0} (+{1})", country.CountryName, country.DiallingCode.Trim());
adjustedCountriesList.Add(item);
}
ddlDialingCode.DataSource = adjustedCountriesList;
ddlDialingCode.DataBind();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
}
}
This is the mobilephone number text box defined in the HTML
<tr>
<td align="right" valign="middle" class="bluetext2b">Mobile phone number</td>
<td><uc:HelpIcon id="Helpicon14" runat="server" Title="Mobile phone number" Text="Add your mobile number including the '0' and with no spaces. If you are not resident in the UK, please ensure you change the international dialling code to the appropriate country. Please note: Your mobile number will not be shared with a third party. If you opt in to take part in Market Research telephone surveys, this field will be mandatory. ."></uc:HelpIcon> </td>
<td><asp:DropDownList DataTextField="Text" DataValueField="Value" ID="ddlDialingCode" Runat="server" CssClass="myinput1" OnInit="DialingCodeDropDown_Init"></asp:DropDownList></td>
</tr>
<tr>
<td></td>
<td></td>
<td><asp:TextBox ID="txbPhoneNumber" Runat="server" onkeypress="return /\d/.test(String.fromCharCode(((event||window.event).which||(event||window.event).which)));" MaxLength="11"></asp:TextBox></td>
</tr>
Just check if the mobile number field is empty or not. If it is empty stop the execution of the Save operation and return some message. You can check it like that:
In the DialingCodeDropDown_Init you can add a default ListItem with Value = 0 and Text = "" ( if you can, because sometimes the client must not have this option to select). Then in PutRegInfo method on the line containing : ri.PhoneNumber = txbPhoneNumber.Text.Trim(); add the following code:
if(!string.IsNullOrEmpty(txbPhoneNumber.Text))
{
ri.DialingCodeID = Convert.ToInt32(ddlDialingCode.SelectedValue);
ri.DialingCode = ddlDialingCode.SelectedValue;
ri.DialingCodeText = ddlDialingCode.SelectedItem.Text;
}
else
{
ri.DialingCodeID = 0;
ri.DialingCode = "0";
ri.DialingCodeText = "";
}
I have situation where I have a number of validators with the same error message on a page, when the page is validated these duplicates are shown in the validation summary.
I would like to remove these duplicates from the validation summary server side.
Here's some pseudo code of what I'd like to do.
validationSummery.ErrorMessages = validationSummery.ErrorMessages.DistinctBy(x=>x.ErrorText);
Having looked into the validation control it appears there is no access to the messages it displays.
I could iterate over all of the page validators which are invalid before the validation summary gets to them and set only one of each message type to valid but then I would not get the error message next to each control.
Does anyone know a way to do this?
It's not pretty but with the use of dotPeek to get the source for the ValidationSummary along with a bit of reflection I created a UniqueMessageValidationSummary control.
/// <summary>
/// Extended version of Validation Summary which overrides OnRender and re-implements get error
/// messages method to ensure the control only renders unique error messages.
///
/// Utilizes .NET code cleaned from .Peek and reflection to access subclass
/// </summary>
public class UniqueMessageValidationSummary : ValidationSummary
{
internal string[] GetErrorMessages(out bool inError)
{
var strArray = (string[])null;
inError = false;
var length = 0;
var validators = Page.GetValidators(ValidationGroup);
for (var index = 0; index < validators.Count; ++index)
{
var validator = validators[index];
if (!validator.IsValid)
{
inError = true;
if (validator.ErrorMessage.Length != 0)
++length;
}
}
if (length != 0)
{
strArray = new string[length];
var index1 = 0;
for (var index2 = 0; index2 < validators.Count; ++index2)
{
var validator = validators[index2];
if (!validator.IsValid && !string.IsNullOrEmpty(validator.ErrorMessage))
{
strArray[index1] = string.Copy(validator.ErrorMessage);
++index1;
}
}
}
var uniqueErrors = new List<string>();
if (strArray != null)
{
var objRegExp = new Regex("<(.|\n)+?>");
foreach (var error in strArray)
{
if (uniqueErrors.All(x => objRegExp.Replace(error, string.Empty) != objRegExp.Replace(x, String.Empty)))
{
uniqueErrors.Add(error);
}
}
}
return uniqueErrors.ToArray();
}
protected override void Render(HtmlTextWriter writer)
{
var renderUplevelCopy = true;
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var baseType = GetType().BaseType;
if (baseType != null)
{
var field = baseType.GetField("renderUplevel", flags);
if (field != null)
renderUplevelCopy = (bool)field.GetValue(this);
}
string[] strArray;
bool flag1;
if (DesignMode)
{
flag1 = true;
renderUplevelCopy = false;
strArray = new[]
{
"ValSummary_error_message_1",
"ValSummary_error_message_2"
};
}
else
{
if (!Enabled)
return;
bool inError;
strArray = GetErrorMessages(out inError);
flag1 = ShowSummary && inError;
if (!flag1 && renderUplevelCopy)
Style["display"] = "none";
}
if (Page != null)
Page.VerifyRenderingInServerForm(this);
var flag2 = renderUplevelCopy || flag1;
if (flag2)
RenderBeginTag(writer);
if (flag1)
{
string text1;
string str1;
string str2;
string text2;
string text3;
switch (DisplayMode)
{
case ValidationSummaryDisplayMode.List:
text1 = "b";
str1 = string.Empty;
str2 = string.Empty;
text2 = "b";
text3 = string.Empty;
break;
case ValidationSummaryDisplayMode.SingleParagraph:
text1 = " ";
str1 = string.Empty;
str2 = string.Empty;
text2 = " ";
text3 = "b";
break;
default:
text1 = string.Empty;
str1 = "<ul>";
str2 = "<li>";
text2 = "</li>";
text3 = "</ul>";
break;
}
if (HeaderText.Length > 0)
{
writer.Write(HeaderText);
WriteBreakIfPresent(writer, text1);
}
if (strArray != null)
{
writer.Write(str1);
foreach (var t in strArray)
{
writer.Write(str2);
writer.Write(t);
WriteBreakIfPresent(writer, text2);
}
WriteBreakIfPresent(writer, text3);
}
}
if (!flag2)
return;
RenderEndTag(writer);
}
private static void WriteBreakIfPresent(HtmlTextWriter writer, string text)
{
if (text == "b")
{
writer.WriteBreak();
}
else
writer.Write(text);
}
}
I've created a custom BoundField for use with a DetailsView in Edit and Insert modes to utilize Twitter Bootstrap.
The control works fine, except when I add in extra LiteralControls to surround the TextBox with some HTML during InitializeDataCell(...). Code related to this toward the end.
The HTML generated is below seems to be identical to what is generated with a TemplateField. But when I fire an Update, anytime it adds the extra div / span seen here, the value in the TextBox is blank upon PostBack.
<div class="input-prepend">
<span class="add-on">$</span>
<input name="ctl00$ctl00$MainContent$MainContent$pi$dvPackage$tbPrice" type="text" value="0" size="5" id="MainContent_MainContent_pi_dvPackage_tbPrice" title="Price">
</div>
Here is some examples of what I'm doing within the front ASP.NET code and what HTML is generated.
Doesn't work - custom field
Value inside text box is unset after submitting via Update command, ONLY when I add the input-append and add-on part.
Field inside DetailsView
<my:ValidationField DataField="Price" HeaderText="Price" TextPrepend="$" />
HTML generated
<td>
<div class="input-prepend">
<span class="add-on">$</span>
<input name="ctl00$ctl00$MainContent$MainContent$pi$dvPackage$tbPrice" type="text" value="0" size="5" id="MainContent_MainContent_pi_dvPackage_tbPrice" title="Price">
</div>
</td>
Does work - normal TemplateField
Works fine
Field inside DetailsView
<asp:TemplateField>
<EditItemTemplate>
<div class="input-prepend">
<span class="add-on">$</span>
<asp:TextBox ID="tbCost" runat="server" Text='<%# Bind("Cost") %>'></asp:TextBox>
</div>
</EditItemTemplate>
</asp:TemplateField>
HTML generated - identical to what is above
<td>
<div class="input-prepend">
<span class="add-on">$</span>
<input name="ctl00$ctl00$MainContent$MainContent$pi$dvPackage$tbPrice" type="text" value="0" size="5" id="MainContent_MainContent_pi_dvPackage_tbPrice" title="Price">
</div>
</td>
Does work - HTML generated with custom field
Value inside text box is correctly submitted via Update command when I don't add the TextPrepend field.
Field inside DetailsView
<my:ValidationField DataField="Price" HeaderText="Price" />
HTML generated without extra span / div
<td>
<input name="ctl00$ctl00$MainContent$MainContent$pi$dvPackage$tbPrice" type="text" value="0" size="5" id="MainContent_MainContent_pi_dvPackage_tbPrice" title="Price">
</td>
InitializeDataCell parts related to this code creation
I believe this is due to something with the InitializeDataCell(...) implementation.
protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
base.InitializeDataCell(cell, rowState);
// Find the text box to validate
TextBox text = FindTextBox(cell);
if (text != null)
{
text.ID = "tb" + DataField;
text.MaxLength = MaxLength;
text.TextMode = TextMode;
text.Text = DataField;
string cellCss = string.Empty;
bool prepend = !string.IsNullOrEmpty(this.TextPrepend);
bool append = !string.IsNullOrEmpty(this.TextAppend);
bool addon = prepend || append;
if (prepend == true)
cellCss = this.ConcatenateCss(cellCss, "input-prepend");
if (append == true)
cellCss = this.ConcatenateCss(cellCss, "input-append");
if (addon == true)
{
int textIndex = cell.Controls.IndexOf(text);
Literal container = new Literal();
container.Text = "<div class=\"" + cellCss + "\">";
cell.Controls.AddAt(textIndex, container);
}
if (prepend == true)
{
int textIndex = cell.Controls.IndexOf(text);
Literal units = new Literal();
units.Text = "<span class=\"add-on\">" + this.Prepend() + "</span>";
cell.Controls.AddAt(textIndex, units);
}
if (append == true)
{
Literal units = new Literal();
units.Text = "<span class=\"add-on\">" + this.Append() + "</span>";
cell.Controls.Add(units);
}
if (addon == true)
{
Literal container = new Literal();
container.Text = "</div>";
cell.Controls.Add(container);
}
}
}
Entire code in case it's useful to anyone trying to use Twitter Bootstrap, or if my code is wrong elsewhere.
public class ValidationField : BoundField
{
#region Properties
public virtual string EditTextCssClass
{
get
{
return (string)(ViewState["EditTextCssClass"] ?? string.Empty);
}
set
{
ViewState["EditTextCssClass"] = value;
OnFieldChanged();
}
}
public virtual ValidatorDisplay ErrorDisplay
{
get
{
return (ValidatorDisplay)(ViewState["ErrorDisplay"] ?? ValidatorDisplay.Dynamic);
}
set
{
ViewState["ErrorDisplay"] = value;
OnFieldChanged();
}
}
public virtual string ErrorMessage
{
get
{
return (string)(ViewState["ErrorMessage"] ?? "Invalid value entered");
}
set
{
ViewState["ErrorMessage"] = value;
OnFieldChanged();
}
}
public virtual string HelpText
{
get
{
return (string)(ViewState["HelpText"] ?? string.Empty);
}
set
{
ViewState["HelpText"] = value;
OnFieldChanged();
}
}
public virtual TwitterBootstrap.WebControls.TextBox.HelpTextDisplayMode HelpDisplay
{
get
{
return (TwitterBootstrap.WebControls.TextBox.HelpTextDisplayMode)(ViewState["HelpDisplay"] ?? TwitterBootstrap.WebControls.TextBox.HelpTextDisplayMode.Block);
}
set
{
ViewState["HelpDisplay"] = value;
OnFieldChanged();
}
}
public virtual int MaxLength
{
get
{
return (int)(ViewState["MaxLength"] ?? 0);
}
set
{
ViewState["MaxLength"] = value;
OnFieldChanged();
}
}
public virtual string PlaceHolder
{
get
{
return (string)(ViewState["PlaceHolder"] ?? string.Empty);
}
set
{
ViewState["PlaceHolder"] = value;
OnFieldChanged();
}
}
public virtual bool Required
{
get
{
return (bool)(ViewState["Required"] ?? false);
}
set
{
ViewState["Required"] = value;
OnFieldChanged();
}
}
public virtual TextBoxMode TextMode
{
get
{
return (TextBoxMode)(ViewState["TextMode"] ?? TextBoxMode.SingleLine);
}
set
{
ViewState["TextMode"] = value;
OnFieldChanged();
}
}
public virtual string ValidationExpression
{
get
{
return (string)(ViewState["ValidationExpression"] ?? string.Empty);
}
set
{
ViewState["ValidationExpression"] = value;
OnFieldChanged();
}
}
public virtual string ValidationGroup
{
get
{
return (string)(ViewState["ValidationGroup"] ?? string.Empty);
}
set
{
ViewState["ValidationGroup"] = value;
OnFieldChanged();
}
}
public virtual string TextAppend
{
get
{
object value = ViewState["TextAppend"];
if (value != null)
return value.ToString();
return string.Empty;
}
set
{
ViewState["TextAppend"] = value;
OnFieldChanged();
}
}
public virtual string TextPrepend
{
get
{
object value = ViewState["TextPrepend"];
if (value != null)
return value.ToString();
return string.Empty;
}
set
{
ViewState["TextPrepend"] = value;
OnFieldChanged();
}
}
#endregion
public ValidationField()
{
}
protected override DataControlField CreateField()
{
return new ValidationField();
}
protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
base.InitializeDataCell(cell, rowState);
// Find the text box to validate
TextBox text = FindTextBox(cell);
if (text != null)
{
text.ID = "tb" + DataField;
text.MaxLength = MaxLength;
text.TextMode = TextMode;
text.CssClass = EditTextCssClass;
text.Text = DataField;
if (PlaceHolder != string.Empty)
text.Attributes.Add("placeholder", PlaceHolder);
string cellCss = string.Empty;
bool prepend = !string.IsNullOrEmpty(this.TextPrepend);
bool append = !string.IsNullOrEmpty(this.TextAppend);
bool addon = prepend || append;
if (prepend == true)
cellCss = this.ConcatenateCss(cellCss, "input-prepend");
if (append == true)
cellCss = this.ConcatenateCss(cellCss, "input-append");
if (addon == true)
{
int textIndex = cell.Controls.IndexOf(text);
Literal container = new Literal();
container.Text = "<div class=\"" + cellCss + "\">";
cell.Controls.AddAt(textIndex, container);
}
if (prepend == true)
{
int textIndex = cell.Controls.IndexOf(text);
Literal units = new Literal();
units.Text = "<span class=\"add-on\">" + this.Prepend() + "</span>";
cell.Controls.AddAt(textIndex, units);
}
if (append == true)
{
Literal units = new Literal();
units.Text = "<span class=\"add-on\">" + this.Append() + "</span>";
cell.Controls.Add(units);
}
if (addon == true)
{
Literal container = new Literal();
container.Text = "</div>";
cell.Controls.Add(container);
}
if (Required == true)
{
Literal required = new Literal();
required.Text = "<span class=\"required\">*</span>";
cell.Controls.Add(required);
}
if (HelpText != string.Empty)
{
Label lblHelpText = new Label();
if (HelpDisplay == TwitterBootstrap.WebControls.TextBox.HelpTextDisplayMode.Block)
lblHelpText.CssClass = "help-block";
else
lblHelpText.CssClass = "help-inline";
lblHelpText.Text = HelpText;
cell.Controls.Add(lblHelpText);
}
if (Required == true)
{
// Add a RequiredFieldValidator
RequiredFieldValidator required = new RequiredFieldValidator();
required.ErrorMessage = ErrorMessage;
required.Display = ErrorDisplay;
required.ControlToValidate = text.ID;
required.Text = "";
if (ValidationGroup != string.Empty)
required.ValidationGroup = ValidationGroup;
cell.Controls.Add(required);
}
if (ValidationExpression != string.Empty)
{
// Add a RequiredFieldValidator
RegularExpressionValidator regex = new RegularExpressionValidator();
regex.ErrorMessage = ErrorMessage;
regex.Display = ErrorDisplay;
regex.ControlToValidate = text.ID;
regex.ValidationExpression = ValidationExpression;
if (ValidationGroup != string.Empty)
regex.ValidationGroup = ValidationGroup;
cell.Controls.Add(regex);
}
}
}
#region Methods
private string ConcatenateCss(params string[] classes)
{
string result = string.Empty;
foreach (string s in classes)
result += s + " ";
return result.TrimEnd().TrimStart();
}
private static TextBox FindTextBox(Control parent)
{
TextBox result = null;
foreach (Control control in parent.Controls)
{
if (control is TextBox)
{
result = control as TextBox;
break;
}
}
return result;
}
protected virtual string Prepend()
{
return this.TextPrepend;
}
protected virtual string Append()
{
return this.TextAppend;
}
#endregion
}
I managed to figure out why this was happening. Since the Control collection was altered in the field, you must also override _ExtractValuesFromCell(...)to get theTextBox` value.
I have used a slightly altered implementation from ASP.NET Boundfield overridden to support Dropdownlist is missing one final feature and haven't optimized for my use case. However, it works fine now.
public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
Control control = null;
string dataField = DataField;
object text = null;
string nullDisplayText = NullDisplayText;
if (((rowState & DataControlRowState.Insert) == DataControlRowState.Normal) || InsertVisible)
{
if (cell.Controls.Count > 0)
{
foreach (Control c in cell.Controls)
{
control = cell.Controls[0];
if (c is TextBox)
{
text = ((TextBox)c).Text;
}
}
}
else if (includeReadOnly)
{
string s = cell.Text;
if (s == " ")
{
text = string.Empty;
}
else if (SupportsHtmlEncode && HtmlEncode)
{
text = HttpUtility.HtmlDecode(s);
}
else
{
text = s;
}
}
if (text != null)
{
if (((text is string) && (((string)text).Length == 0)) && ConvertEmptyStringToNull)
{
text = null;
}
if (((text is string) && (((string)text) == nullDisplayText)) && (nullDisplayText.Length > 0))
{
text = null;
}
if (dictionary.Contains(dataField))
{
dictionary[dataField] = text;
}
else
{
dictionary.Add(dataField, text);
}
}
}
}
I am getting lot of errors for HttpRequestValidationException in my event log.
Is it possible to HTMLEncode all the inputs from override of ProcessRequest on web page. I have tried this but it gives context.Request.InputStream.CanWrite == false always.
Is there any way to HTMLEncode all the feilds when request is made?
public override void ProcessRequest(HttpContext context)
{
if (context.Request.InputStream.CanRead)
{
IEnumerator en = HttpContext.Current.Request.Form.GetEnumerator();
while (en.MoveNext())
{
//Response.Write(Server.HtmlEncode(en.Current + " = " +
//HttpContext.Current.Request.Form[(string)en.Current]));
}
long nLen = context.Request.InputStream.Length;
if (nLen > 0)
{
string strInputStream = string.Empty;
context.Request.InputStream.Position = 0;
byte[] bytes = new byte[nLen];
context.Request.InputStream.Read(bytes, 0, Convert.ToInt32(nLen));
strInputStream = Encoding.Default.GetString(bytes);
if (!string.IsNullOrEmpty(strInputStream))
{
List<string> stream = strInputStream.Split('&').ToList<string>();
Dictionary<int, string> data = new Dictionary<int, string>();
if (stream != null && stream.Count > 0)
{
int index = 0;
foreach (string str in stream)
{
if (str.Length > 3 && str.Substring(0, 3) == "txt")
{
string textBoxData = str;
string temp = Server.HtmlEncode(str);
//stream[index] = temp;
data.Add(index, temp);
index++;
}
}
if (data.Count > 0)
{
List<string> streamNew = stream;
foreach (KeyValuePair<int, string> kvp in data)
{
streamNew[kvp.Key] = kvp.Value;
}
string newStream = string.Join("", streamNew.ToArray());
byte[] bytesNew = Encoding.Default.GetBytes(newStream);
if (context.Request.InputStream.CanWrite)
{
context.Request.InputStream.Flush();
context.Request.InputStream.Position = 0;
context.Request.InputStream.Write(bytesNew, 0, bytesNew.Length);
//Request.InputStream.Close();
//Request.InputStream.Dispose();
}
}
}
}
}
}
base.ProcessRequest(context);
}
you have to ser the property validateRequest = false and do the necessary validations over user input manually.
<%# Page language="c#" validateRequest="false" Codebehind="TestForm.aspx.cs" AutoEventWireup="false" Inherits="TestForm" %>