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);
}
}
}
}
Related
here is my code :
var allEles = webBrowser1.Document.All;
foreach (HtmlElement item in allEles)
{
if (item.TagName.ToLower() == "div")
{
if(//Here i want to check if div has a background-image css property)
{
//do anything
}
}
}
i searched a lot to no avail :(
I wrote my own extension method :
public static class Extensions
{
public static bool hasBackgroundImage(this HtmlElement ele, string cssFolderPath)
{
string styleAttr = ele.Style.ToLower();
if (styleAttr.IndexOf("background-image") != -1 || styleAttr.IndexOf("background") != -1)
{
if (styleAttr.IndexOf("url") != -1)
{
return true;
}
}
string[] classes = ele.GetAttribute("className").Split(' ');
foreach (string className in classes)
{
if (className.Trim() == "")
{
continue;
}
System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(cssFolderPath);
foreach (System.IO.FileInfo item in d.GetFiles().Where(p => p.Extension == ".css"))
{
string cssFile = System.IO.File.ReadAllText(item.FullName);
int start = cssFile.IndexOf(className);
if (start != -1)
{
string sub = cssFile.Substring(start + className.Length);
int end = sub.IndexOf('}');
string cssProps = sub.Substring(1, end).Replace("{", "").Replace("}", "").ToLower();
if (cssProps.IndexOf("background-image") != -1 || cssProps.IndexOf("background") != -1)
{
if (cssProps.IndexOf("url") != -1)
{
return true;
}
}
}
}
}
return false;
}
}
and now i can call my method :
var allEles = webBrowser1.Document.All;
foreach (HtmlElement item in allEles)
{
if (item.TagName.ToLower() == "div")
{
if(item.hasBackgroundImage("myCssFolderPathHere"))
{
//do anything
}
}
}
but this working only if am running a local html file .... because you must throw the css folder path as a parameter in my extension method , and thats what i was looking for :)
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'm trying to implement a form validation with ASP.net and I have tried every solution suggested here but the best one was on aspsnippets.com so far.
My code is like below:
<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tTitle"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tEMail"/>
<asp:RegularExpressionValidator runat="server" ControlToValidate="tEMail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit"/>
Javascript
<script type="text/javascript">
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
{
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
} return false;
} return true;
}
function WebForm_OnBlur() {
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
} return false;
}
</script>
The problem is the e-mail field only validates for the regular expression. If I change the order of the validators, it only validates for required expression.
The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.
The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.
Yes, this is indeed the problem. To fix it, you can do the following:
In the WebForm_OnBlur function, loop through the validators associated with the control that lost focus (rather than all the validators on the page), and clear the className property only if all the validators are valid:
function WebForm_OnBlur(control) {
for (var i = 0; i < control.Validators.length; i++) {
if (!control.Validators[i].isvalid) {
control.className = "error";
return;
}
}
control.className = "";
}
In the onblur attribute of the TextBox controls, pass this as the argument to WebForm_OnBlur:
<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur(this)"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur(this)"/>
In the WebForm_OnSubmit function, call WebForm_OnBlur for each control that has associated validators:
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) === "function" && ValidatorOnSubmit() === false) {
for (var i = 0; i < Page_Validators.length; i++) {
var control = document.getElementById(Page_Validators[i].controltovalidate);
if (Page_Validators[i] === control.Validators[0]) // minor optimization
WebForm_OnBlur(control);
}
return false;
}
return true;
}
In addition to #MichaelLiu, You can make your own validators that inherit from the CustomValidator class and alter the rendering of the validators to make them a little easier to work with.
For example:
Validators.cs
Take notice of how we add a property of CssControlErrorClass. We will use this when applying a class with the invalid input in question.
We also set other properties so you don't have to set them everytime, ClientValidationFunction and ValidateEmptyText.
public class RequiredFieldValidator : CustomValidator
{
public string CssControlErrorClass { get; set; }
public RequiredFieldValidator()
{
ClientValidationFunction = "validators.required";
ValidateEmptyText = true;
}
public string InitialValue
{
get
{
object o = ViewState["InitialValue"];
return ((o == null) ? String.Empty : (string)o);
}
set
{
ViewState["InitialValue"] = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
//Have to add attributes BEFORE the beginning tag is written to the stream
writer.AddAttribute("data-errorClass", CssControlErrorClass);
writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
base.Render(writer);
}
protected override bool EvaluateIsValid()
{
//Default implementation of the RequiredFieldValidation validator
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null)
{
return true;
}
var result = (!controlValue.Trim().Equals(InitialValue.Trim()));
//Check to see if validation failed, if it did, add the class to the control to validate
if (!result)
{
var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
//Didn't look into it too much, but the validators fire twice for some reason
if(!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
}
return result;
}
}
public class RegularExpressionValidator : CustomValidator
{
public string CssControlErrorClass { get; set; }
public string ValidationExpression
{
get
{
object o = ViewState["ValidationExpression"];
return ((o == null) ? String.Empty : (string)o);
}
set
{
try
{
Regex.IsMatch(String.Empty, value);
}
catch (Exception e)
{
throw new HttpException(string.Format("{0} - {1}", "Validator_bad_regex", value), e);
}
ViewState["ValidationExpression"] = value;
}
}
public RegularExpressionValidator()
{
ClientValidationFunction = "validators.regex";
}
protected override void Render(HtmlTextWriter writer)
{
//Have to add attributes BEFORE the beginning tag is written to the stream
writer.AddAttribute("data-errorClass", CssControlErrorClass);
writer.AddAttribute("data-regex", ValidationExpression);
writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
base.Render(writer);
}
protected override bool EvaluateIsValid()
{
//Default implementation of the RegularExpressionFieldvalidator
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null || controlValue.Trim().Length == 0)
{
return true;
}
try
{
Match m = Regex.Match(controlValue, ValidationExpression);
var result = (m.Success && m.Index == 0 && m.Length == controlValue.Length);
//Check to see if validation failed, if it did, add the class to the control to validate
if (!result)
{
var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
//Didn't look into it too much, but the validators fire twice for some reason
if (!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
}
return result;
}
catch
{
return true;
}
}
}
Validators.js
Since in the previous classes we pre-defined the javascript functions, we can add a simple script like so:
var v = window.validators = window.validators || {
errorControlAttributeName: "data-for",
errorClassAttributeName: "data-errorClass",
regexAttributeName: "data-regex",
required: function(src, args) {
var controlId = src.getAttribute(v.errorControlAttributeName),
errorClass = src.getAttribute(v.errorClassAttributeName),
input = document.getElementById(controlId);
var isValid = (args.Value !== "");
v._toggleInputErrorState(input, errorClass, isValid);
args.IsValid = isValid;
return;
},
regex: function(src, args) {
var controlId = src.getAttribute(v.errorControlAttributeName),
errorClass = src.getAttribute(v.errorClassAttributeName),
regexString = src.getAttribute(v.regexAttributeName),
input = document.getElementById(controlId),
regex = new RegExp(regexString);
var isValid = regex.test(args.Value);
v._toggleInputErrorState(input, errorClass, isValid);
args.IsValid = isValid;
return;
},
/************* Helper functions ***********/
_toggleInputErrorState: function (inputEl, errorClass, isValid) {
if (!isValid) {
if (!v._hasClass(inputEl, errorClass)) {
inputEl.className += " " + errorClass;
}
} else {
if (v._hasClass(inputEl, errorClass)) {
//Not the most performant, but is sure is easiest
inputEl.className = inputEl.className.replace(" " + errorClass, "");
}
}
},
_hasClass: function(el, className) {
return el.className.indexOf(className) != -1 ? true : false;
},
}
Very simple validation library that you can easily extend with things you are actually interesting in.
Default.aspx
After than you can put the controls into your page:
<Validators:RequiredFieldValidator runat="server" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED BRO!"></Validators:RequiredFieldValidator>
<Validators:RegularExpressionValidator runat="server" ValidationExpression="[0-9]" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED RegEx BRO!"></Validators:RegularExpressionValidator>
Is this the best way? Probably not, (these two use the default implementation that is given by Microsoft) there are way smarter people out there than I and I don't work with WebForms much. The biggest benefit I see is that you get some reusable code, using a familiar syntax, that will eventually contain all your validation needs versus messing around with js everytime to get the validation "rules" how you want them.
The issue is resolved by replacing the code snippet below. To correct we must loop through all the validators for a control, then we should decide whether it has to marked with the error class. After this, your code will work as expected.
Replace the loop
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
}
with the below code
for (var j in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[j].controltovalidate);
var IsError = false;
for (var i in control.Validators) {
if (!control.Validators[i].isvalid) {
IsError = true;
}
}
if (IsError)
control.className = "error";
else
control.className = "";
} catch (e) { }
}
I just ran it and this is working excellently :) Try this solution!
you can try Page_ClientValidate() in javascript instead of looping across validator.
I believe this will validate all the validators on the page.
It also takes in parameter which "Validation group name" if you want to validate specific controls bound by particular validation group.
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 am facing the following problem: I want to add dynamically a mobile site for specific templates, I specified the mobile layout in the standard values of the specific item. This all works fine but when I changed a field of the Item the layout and renderings of the default site is gone! Does anyone has a solution/suggestion for this problem?
I am working with Sitecore 6.4.
Thanx in advance!
The code that I am currently using (this is to add hardcoded a layout to an item, the next step is (when I fixed this problem) to get the layout from the standard_values item)
public class CheckMobileLayout
{
public void Process([NotNull] SaveArgs args)
{
try
{
foreach (Sitecore.Pipelines.Save.SaveArgs.SaveItem saveItem in args.Items)
{
Item orgItem = Context.ContentDatabase.Items[saveItem.ID, saveItem.Language, saveItem.Version];
if(orgItem.Name != "Content Editor")
{
TemplateItem testTemplate = orgItem.Template;
foreach (Field orgField in orgItem.Fields)
{
if (orgField != null)
{
if (orgField.GetTemplateField().Type == "Mobile Checkbox")
{
foreach (Sitecore.Pipelines.Save.SaveArgs.SaveField saveField in saveItem.Fields)
{
if (saveField.ID == orgField.ID)
{
if (saveField.Value != orgField.Value)
{
if (saveField.Value == "1") AddMobileLayout(orgItem);
else RemoveMobileLayout(orgItem);
}
}
}
}
}
}
}
}
}
catch (NullReferenceException)
{
}
}
private void RemoveMobileLayout(Item orgItem)
{
using (new SecurityDisabler())
{
Database masterDatabase = Database.GetDatabase("master");
orgItem = masterDatabase.GetItem(orgItem.Paths.Path);
string renderingXml = orgItem[Strings.Renderings];
LayoutDefinition layoutDefinition = new LayoutDefinition();
layoutDefinition.LoadXml(renderingXml);
string mobileDeviceId = Strings.mobileDeviceID;
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(mobileDeviceId);
deviceDefinition.Layout = String.Empty;
string outputXml = layoutDefinition.ToXml();
Log.Info(outputXml, this);
orgItem.Editing.BeginEdit();
orgItem[Strings.Renderings] = outputXml;
orgItem.Editing.EndEdit();
}
}
private void AddMobileLayout(Item orgItem)
{
using (new SecurityDisabler())
{
Database masterDatabase = Database.GetDatabase("master");
Item testItem = masterDatabase.GetItem(orgItem.Paths.Path);
string renderingXml = testItem[Strings.Renderings];
LayoutDefinition layoutDefinition = new LayoutDefinition();
layoutDefinition.LoadXml(renderingXml);
string mobileDeviceId = Strings.mobileDeviceID;
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(mobileDeviceId);
deviceDefinition.Layout = Strings.mobileLayoutID;
string outputXml = layoutDefinition.ToXml();
testItem.Editing.BeginEdit();
testItem[Strings.Renderings] = layoutDefinition.ToXml();
testItem.Editing.EndEdit();
}
}
}
I've fixed this with the following to methods:
protected void RemoveMobileLayout(Item item)
{
using (new SecurityDisabler())
{
LayoutDefinition layoutDefinition = Sitecore.Layouts.LayoutDefinition.Parse(item[Sitecore.FieldIDs.LayoutField]);
DeviceDefinition mobileDevice = layoutDefinition.GetDevice(Resources.mobileDeviceID);
if (mobileDevice.Layout != null) mobileDevice.Layout = null;
if (mobileDevice.Renderings != null) mobileDevice.Renderings = null;
item.Editing.BeginEdit();
item[Sitecore.FieldIDs.LayoutField] = layoutDefinition.ToXml();
item.Editing.EndEdit();
}
}
protected void AddMobileLayout(Item item)
{
using (new SecurityDisabler())
{
LayoutDefinition layoutDefinition = Sitecore.Layouts.LayoutDefinition.Parse(item[Sitecore.FieldIDs.LayoutField]);
DeviceDefinition mobileDevice = layoutDefinition.GetDevice(Resources.mobileDeviceID);
TemplateItem itemTemplate = item.Template;
if (itemTemplate != null)
{
if (itemTemplate.StandardValues != null)
{
Item standardValues = itemTemplate.StandardValues;
foreach (DeviceItem deviceItem in Sitecore.Configuration.Factory.GetDatabase("master").Resources.Devices.GetAll())
{
if (deviceItem.ID.ToString() == Resources.mobileDeviceID)
{
mobileDevice.Layout = standardValues.Visualization.GetLayout(deviceItem).ID.ToString();
RenderingReference[] sublayouts = standardValues.Visualization.GetRenderings(deviceItem, true);
foreach (RenderingReference sublayout in sublayouts) mobileDevice.AddRendering(new RenderingDefinition() { ItemID = sublayout.RenderingItem.ID.ToString(), Placeholder = sublayout.RenderingItem.Placeholder });
}
}
}
}
item.Editing.BeginEdit();
item[Sitecore.FieldIDs.LayoutField] = layoutDefinition.ToXml();
item.Editing.EndEdit();
}
}