I have a UserControl ('AddressInfoGroup') within an updatepanel that dynamically loads user controls ('AddressInfo') via the loadControl method. I have two other such controls on the same page, both of which function correctly.
When the AddressInfoGroup control renders an AddressInfo control to the page, the text boxes in AddressInfo have id's unchanged from the ascx markup. These id's should have been dynamically generated by the .NET clientID process. Because of this, when a second AddressInfo control is added to AddressInfoGroup, I get a runtime exception "An entry with the same key already exists". The two working controls produce proper clientID's and consequently don't return this error.
I should also mention that the AddressInfoGroup control has a few buttons which are correctly rendered with clientID so it seems to be an issue with the AddressInfo control itself. Any suggestions at all would be really helpful!
AddressInfoGroup markup
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddressInfoGroup.ascx.cs" Inherits="MFRI.Controls.Contact.AddressInfoGroup" %>
<h2>Address information</h2>
<div class="formGroup">
<asp:PlaceHolder ID="plc_infoCtrls" runat="server" />
<asp:Button id="btn_addAddress" CssClass="btn_add" Text="v" runat="server" OnClick="addAddress_click" UseSubmitBehavior="false" CausesValidation="false" />
<asp:Button id="btn_removeAddress" CssClass="btn_remove" Text="^" runat="server" OnClick="removeAddress_click" UseSubmitBehavior="false" CausesValidation="false" />
</div>
AddressInfoGroup codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MFRI.Common.Contact;
using MFRI.Common;
namespace MFRI.Controls.Contact
{
public partial class AddressInfoGroup : System.Web.UI.UserControl
{
private int _maxNumberOfControls = 3;
private int _minNumberOfControls = 1;
private List<Address> _controlListToBind = null;
public int NumberOfControls
{
get { return SafeConvert.ToInt(ViewState["NumberOfControls"] ?? 0); }
set { ViewState["NumberOfControls"] = value; }
}
public bool Editable
{
get { return (bool)(ViewState["InfoControlsEditable"] ?? false); }
set { ViewState["InfoControlsEditable"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (_controlListToBind != null && _controlListToBind.Count > 0)
{
NumberOfControls = _controlListToBind.Count;
foreach (Address address in _controlListToBind)
{
AddressInfo addressInfo = (AddressInfo)LoadControl("AddressInfo.ascx");
addressInfo.InitControl(Editable, address);
plc_infoCtrls.Controls.Add(addressInfo);
}
}
else
{
if (NumberOfControls <= 0)
NumberOfControls = 1;
for (int i = 0; i < NumberOfControls; i++)
{
AddressInfo addressInfo = (AddressInfo)LoadControl("AddressInfo.ascx");
addressInfo.InitControl(Editable, null);
plc_infoCtrls.Controls.Add(addressInfo);
}
}
RefreshButtons();
}
public void BindAddressList(List<Address> addressList)
{
_controlListToBind = addressList;
}
public List<Address> GetAddressList()
{
List<Address> returnList = new List<Address>();
foreach (AddressInfo addressInfo in plc_infoCtrls.Controls.OfType<AddressInfo>())
{
returnList.Add(addressInfo.GetAddress());
}
return returnList;
}
private void RefreshButtons()
{
btn_addAddress.Enabled = false;
btn_removeAddress.Enabled = false;
if (Editable)
{
if (NumberOfControls > _minNumberOfControls)
btn_removeAddress.Enabled = true;
if (NumberOfControls < _maxNumberOfControls)
btn_addAddress.Enabled = true;
}
}
protected void addAddress_click(object sender, EventArgs e)
{
if (NumberOfControls < _maxNumberOfControls)
{
AddressInfo addressInfo = (AddressInfo)LoadControl("AddressInfo.ascx");
addressInfo.InitControl(Editable, null);
plc_infoCtrls.Controls.Add(addressInfo);
NumberOfControls++;
}
RefreshButtons();
}
protected void removeAddress_click(object sender, EventArgs e)
{
if (_minNumberOfControls < NumberOfControls)
{
plc_infoCtrls.Controls.RemoveAt(plc_infoCtrls.Controls.Count - 1);
NumberOfControls--;
}
RefreshButtons();
}
}
}
AddressInfo markup
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddressInfo.ascx.cs" Inherits="MFRI.Controls.Contact.AddressInfo" %>
<div>
<asp:Label ID="lbl_line1" AssociatedControlID="txt_line1" runat="server">Line 1:</asp:Label><asp:TextBox ID="txt_line1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="val_line1" runat="server" ErrorMessage="Please include a street address" ControlToValidate="txt_line1" Display="Dynamic">*</asp:RequiredFieldValidator>
</div>
<div>
<asp:Label ID="lbl_line2" AssociatedControlID="txt_line2" runat="server">Line 2:</asp:Label><asp:TextBox ID="txt_line2" runat="server"></asp:TextBox>
</div>
<div>
<asp:Label ID="lbl_zip" AssociatedControlID="txt_zip" runat="server">Zip code:</asp:Label><asp:TextBox ID="txt_zip" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="val_zip" runat="server" ErrorMessage="Please include a zip code" ControlToValidate="txt_zip" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator id="regVal_zip" ControlToValidate="txt_zip" ErrorMessage="Zip code must be made up of integers in the format xxxxx" ValidationExpression="^\d{5}$" Runat="server" Display="Dynamic">*</asp:RegularExpressionValidator>
</div>
<div>
<asp:Label ID="lbl_city" AssociatedControlID="txt_city" runat="server">City:</asp:Label><asp:TextBox ID="txt_city" runat="server" CssClass="disabled"></asp:TextBox>
</div>
<div>
<asp:Label ID="lbl_state" AssociatedControlID="ddl_state" runat="server">State:</asp:Label><asp:DropDownList ID="ddl_state" runat="server" Enabled="false"></asp:DropDownList>
</div>
<div>
<asp:Label ID="lbl_edit" AssociatedControlID="chk_edit" runat="server">Edit City/State:</asp:Label><asp:CheckBox ID="chk_edit" runat="server" />
</div>
AddressInfo codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MFRI.Common.Contact;
using System.Text;
using System.Globalization;
using System.Threading;
using MFRI.Common;
namespace MFRI.Controls.Contact
{
public partial class AddressInfo : System.Web.UI.UserControl
{
private bool _editable = false;
private bool _allowStateCityEdit = false;
protected bool AllowStateCityEdit{
set { _allowStateCityEdit = value; }
}
protected ClientScriptManager clientScriptManager
{
get { return Page.ClientScript; }
}
protected void Page_Load(object sender, EventArgs e)
{
txt_city.Attributes.Add("readonly", "readonly");
RegisterEditCityStateScript();
if (_editable)
RegisterZipCodeScript();
}
public void InitControl(bool editable, Address address)
{
InitStateDropDown();
if (!_allowStateCityEdit)
{
lbl_edit.Visible = false;
chk_edit.Visible = false;
}
_editable = editable;
if (!_editable)
{
txt_line1.Enabled = false;
val_line1.Enabled = false;
txt_line2.Enabled = false;
txt_city.Enabled = false;
txt_zip.Enabled = false;
val_zip.Enabled = false;
regVal_zip.Enabled = false;
ddl_state.Enabled = false;
chk_edit.Enabled = false;
}
else
{
txt_zip.Attributes.Add("onblur", "GetCityState('" + txt_city.ClientID + "','" + ddl_state.ClientID + "','" + txt_zip.ClientID + "');");
chk_edit.Attributes.Add("onClick", "ToggleCityState('" + txt_city.ClientID + "','" + ddl_state.ClientID + "','" + txt_zip.ClientID + "')");
}
if (address != null)
{
txt_line1.Text = address.Line1;
txt_line2.Text = address.Line2;
txt_city.Text = address.City;
txt_zip.Text = SafeConvert.ToString(address.Zip);
ddl_state.SelectedValue = SafeConvert.ToString((int)address.State);
}
}
private void RegisterZipCodeScript(){
if (!clientScriptManager.IsClientScriptBlockRegistered(this.GetType(), "zipCodeScript"))
{
StringBuilder script = new StringBuilder();
script.Append("function GetCityState(txtCityId,ddlStateId,txtZipId) {\n");
script.Append(" var textZip = document.getElementById(txtZipId);\n");
script.Append(" var zipCode = parseFloat(textZip.value);\n");
script.Append(" if(isNaN(zipCode)){\n");
script.Append(" var txtCity = document.getElementById(txtCityId);\n");
script.Append(" var ddlState = document.getElementById(ddlStateId);\n");
script.Append(" txtCity.value = '';\n");
script.Append(" ddlState.selectedIndex = 0;\n");
script.Append(" }\n");
script.Append(" else{\n");
script.Append(" MFRI.Controls.Contact.ZipCodeService.GetCityState(zipCode, txtCityId, ddlStateId, SucceededCallback);\n");
script.Append(" }\n");
script.Append("}\n");
script.Append("function SucceededCallback(result) {\n");
script.Append(" var txtCity = document.getElementById(result[0]);\n");
script.Append(" txtCity.value = result[2];\n");
script.Append(" var ddlState = document.getElementById(result[1]);\n");
script.Append(" var stateId = result[3];\n");
script.Append(" for(i=0; i<ddlState.options.length; i++){\n");
script.Append(" if(ddlState.options[i].value == stateId){\n");
script.Append(" ddlState.selectedIndex = i;\n");
script.Append(" }\n");
script.Append(" }\n");
script.Append("}\n");
clientScriptManager.RegisterClientScriptBlock(this.GetType(), "zipCodeScript", script.ToString(), true);
}
}
private void RegisterEditCityStateScript()
{
if (!clientScriptManager.IsClientScriptBlockRegistered(this.GetType(), "editCityState"))
{
StringBuilder script = new StringBuilder();
script.Append("function ToggleCityState(txtCityId, ddlStateId, txtZipId) {\n");
script.Append(" var txtCity = document.getElementById(txtCityId);\n");
script.Append(" var ddlState = document.getElementById(ddlStateId);\n");
script.Append(" if(ddlState.disabled == true){\n");
script.Append(" txtCity.removeAttribute('readonly');\n");
script.Append(" ddlState.disabled = false;\n");
script.Append(" }\n");
script.Append(" else{\n");
script.Append(" txtCity.setAttribute('readonly', 'readonly');\n");
script.Append(" ddlState.disabled = true;\n");
script.Append(" GetCityState(txtCityId,ddlStateId,txtZipId); \n");
script.Append(" }\n");
script.Append("}\n");
clientScriptManager.RegisterClientScriptBlock(this.GetType(), "editCityState", script.ToString(), true);
}
}
private void InitStateDropDown(){
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
ddl_state.Items.Add(new ListItem("Select a state","-1"));
foreach (StateType state in Enum.GetValues(typeof(StateType)))
{
string displayName = state.ToString().ToLower();
displayName = displayName.Replace('_', ' ');
ddl_state.Items.Add(new ListItem(textInfo.ToTitleCase(displayName), state.GetHashCode().ToString()));
}
}
public Address GetAddress()
{
Address address = new Address();
address.Line1 = txt_line1.Text;
address.Line2 = txt_line2.Text;
address.State = (StateType)Enum.ToObject(typeof(StateType), SafeConvert.ToInt(ddl_state.SelectedValue));
address.City = txt_city.Text;
address.Zip = SafeConvert.ToInt(txt_zip.Text);
return address;
}
}
}
I figured it out finally.
Each addressInfo Control is created on the fly by addressInfoGroup. After instantiation, addressInfoGroup calls the 'initControl' method of the newly created addressInfo control. Within that init function I retrieve a few clientID values:
txt_zip.Attributes.Add("onblur", "GetCityState('" + txt_city.ClientID + "','" + ddl_state.ClientID + "','" + txt_zip.ClientID + "');");
chk_edit.Attributes.Add("onClick", "ToggleCityState('" + txt_city.ClientID + "','" + ddl_state.ClientID + "','" + txt_zip.ClientID + "')");
Because of my reference to the clientID's, all of the controls within addressInfo retain the markup Id's. If I comment those lines out, .NET generates the proper Id's. This has something to do with WHEN these lines are called. When I moved the lines into addressInfo's postback, everything worked as expected.
So end result: If a parent control tells a child control to reference a clientID, all of the child controls clientID's seem to malfunction.
Have you thought about using a ListView control to dynamically create and display your Address controls on the fly? You would have one instance of the control hard-coded on the page and then in your ListView's ItemTemplate you would put in your Address control and databind it to the data in your ListView's DataSource property.
Have you tried explicitly setting the ID value of the dynamically added AddressInfo controls? For instance, in the Page_Load of the AddressInfoGroup:
protected void Page_Load(object sender, EventArgs e)
{
if (_controlListToBind != null && _controlListToBind.Count > 0)
{
NumberOfControls = _controlListToBind.Count;
int index = 0;
foreach (Address address in _controlListToBind)
{
AddressInfo addressInfo = (AddressInfo)LoadControl("AddressInfo.ascx");
addressInfo.ID = String.Format("AddressInfo{0}", index++);
addressInfo.InitControl(Editable, address);
plc_infoCtrls.Controls.Add(addressInfo);
}
}
else
{
if (NumberOfControls <= 0)
NumberOfControls = 1;
for (int i = 0; i < NumberOfControls; i++)
{
AddressInfo addressInfo = (AddressInfo)LoadControl("AddressInfo.ascx");
addressInfo.ID = String.Format("AddressInfo{0}", i);
addressInfo.InitControl(Editable, null);
plc_infoCtrls.Controls.Add(addressInfo);
}
}
RefreshButtons();
}
Related
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);
}
}
Having trouble understanding this error below in vs.net.
I'm trying to grab a logged in user account on the domain and allow them to be able to edit their phone number.
Another guy setup the AD Access, but I can't event get a logged in user name.
Pasted the code VS.NET errors on every time with the exception that I found in an online article and worked for everyone else except me.
I've verified it works using powershell but I could use some help.
THANKS!!!
//parse the current user's logon name as search key
string sFilter = String.Format(
"(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))",
User.Identity.Name.Split(new char[] { '\\' })[1]
);
Exception User-Unhandled
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
<%# Import Namespace="System.DirectoryServices.ActiveDirectory" %>
<%# Import Namespace="System.DirectoryServices.AccountManagement" %>
<!DOCTYPE html>
<head>
<script language="c#" runat="server">
static string adsPath = "LDAP://dc=DOMAIN,dc=com";
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
SearchResult sr = FindCurrentUser(new string[] { "allowedAttributesEffective" });
if (sr == null)
{
msg.Text = "User not found...";
return;
}
int count = sr.Properties["allowedAttributesEffective"].Count;
if (count > 0)
{
int i = 0;
string[] effectiveAttributes = new string[count];
foreach (string attrib in sr.Properties["allowedAttributesEffective"])
{
effectiveAttributes[i++] = attrib;
}
sr = FindCurrentUser(effectiveAttributes);
foreach (string key in effectiveAttributes)
{
string val = String.Empty;
if (sr.Properties.Contains(key))
{
val = sr.Properties[key][0].ToString();
}
GenerateControls(key, val, parent);
}
}
}
else
{
UpdateControls();
}
}
private SearchResult FindCurrentUser(string[] attribsToLoad)
{
//parse the current user's logon name as search key
string sFilter = String.Format(
"(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))",
User.Identity.Name.Split(new char[] { '\\' })[1]
);
DirectoryEntry searchRoot = new DirectoryEntry(
adsPath,
null,
null,
AuthenticationTypes.Secure
);
using (searchRoot)
{
DirectorySearcher ds = new DirectorySearcher(
searchRoot,
sFilter,
attribsToLoad,
SearchScope.Subtree
);
ds.SizeLimit = 1;
return ds.FindOne();
}
}
private void GenerateControls(string attrib, string val, Control parent)
{
parent.Controls.Add(new LiteralControl("<div>"));
TextBox t = new TextBox();
t.ID = "c_" + attrib;
t.Text = val;
t.CssClass = "txt";
Label l = new Label();
l.Text = attrib;
l.AssociatedControlID = t.ID;
l.CssClass = "lbl";
parent.Controls.Add(l);
parent.Controls.Add(t);
parent.Controls.Add(new LiteralControl("</div>"));
}
private void UpdateControls()
{
SearchResult sr = FindCurrentUser(new string[] { "cn" });
if (sr != null)
{
using (DirectoryEntry user = sr.GetDirectoryEntry())
{
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("c_"))
{
string attrib = key.Split(new char[] { '_' })[1];
string val = Request.Form[key];
if (!String.IsNullOrEmpty(val))
{
Response.Output.Write("Updating {0} to {1}<br>", attrib, val);
user.Properties[attrib].Value = val;
}
}
}
user.CommitChanges();
}
}
btnSubmit.Visible = false;
Response.Output.Write("<br><br>< Back", Request.Url);
}
</script>
<style>
.lbl
{
margin-left: 25px;
clear: left;
width: 250px;
}
.txt
{
width: 250px;
}
</style>
</head>
<body>
<form id="main" runat="server">
Data for user:
<%=User.Identity.Name%>
<br>
<br>
<asp:Label ID="msg" runat="server" />
<asp:Panel ID="parent" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Update" />
</form>
</body>
</html>
Basically I have a webform with a scriptmanager and a button to update the results returned from the class webspider (web spider that searches for broken links for a given url). I am trying to convert the code to mvc and have achieved most of this except for the code that is highlighted in bold as I do not have a scriptmanager in the mvc view, can some please give me some pointers on how I can do this, many thanks. -
default.aspx -
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_check404._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %>.</h1>
<h2>Modify this template to jump-start your ASP.NET application.</h2>
</hgroup>
<p>
To learn more about ASP.NET, visit http://asp.net.
The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET.
If you have any questions about ASP.NET visit
our forums.
</p>
</div>
</section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h3>Search results:</h3>
<asp:Label ID="lblTot" runat="server" />
<asp:Label runat="server" ID="lblStatus" />
<asp:UpdatePanel runat="server" ID="pnlLinks">
<ContentTemplate> -->
<asp:GridView runat="server" ID="grvLinks" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="NavigateUrl" HeaderText="Url" />
<asp:ButtonField DataTextField="Status" HeaderText="Status" />
</Columns>
</asp:GridView>
<asp:Button runat="server" ID="btnUpdateResults" Text="Update Results" />
</ContentTemplate>
</asp:UpdatePanel>
default.aspx.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using _check404.Spider;
using System.Net;
namespace _check404
{
public partial class _Default : Page
{
private string script = #"setTimeout(""__doPostBack('{0}','')"", 5000);";
private WebSpider WebSpider
{
get { return (WebSpider)(Session["webSpider"] ?? (Session["webSpider"] = new WebSpider())); }
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!this.WebSpider.IsRunning)
{
string url = "http://bbc.co.uk";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
this.WebSpider.Execute(url);
lblTot.Text = WebSpider.Tot.ToString();
}
//////////////////////////the following code is what I am trying to convert
if (this.WebSpider.IsRunning)
{
this.lblStatus.Text = "Processing...";
ScriptManager.RegisterStartupScript(this, this.GetType(),
this.GetType().Name, string.Format(script, this.btnUpdateResults.ClientID), true);
}
///////////////////////////////////////////////////////////////////////////////////////
this.grvLinks.DataSource = this.WebSpider.Links;
this.grvLinks.DataBind();
}
}
}
spider.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
namespace _check404.Spider
{
public class WebSpider
{
public int Tot { get; set; }
const int LIMIT = 10;
string[] invalidTypes = { ".zip", ".doc", ".css", ".pdf", ".xls", ".txt", ".js", ".ico" };
public List<Link> Links;
public bool IsRunning { get; set; }
public WebSpider()
{
this.Links = new List<Link>();
}
public void Execute(string url)
{
this.Links.Clear();
this.Links.Add(new Link() { Status = HttpStatusCode.OK, NavigateUrl = url });
this.IsRunning = true;
WaitCallback item = delegate(object state) { this.FindLinks((UrlState)state); };
ThreadPool.QueueUserWorkItem(item, new UrlState() { Url = url, Level = 0 });
Tot = Links.Count();
}
public void FindLinks(UrlState state)
{
try
{
string html = new WebClient().DownloadString(state.Url);
MatchCollection matches = Regex.Matches(html, "href[ ]*=[ ]*['|\"][^\"'\r\n]*['|\"]");
foreach (Match match in matches)
{
string value = match.Value;
value = Regex.Replace(value, "(href[ ]*=[ ]*')|(href[ ]*=[ ]*\")", string.Empty);
if (value.EndsWith("\"") || value.EndsWith("'"))
value = value.Remove(value.Length - 1, 1);
if (!Regex.Match(value, #"\((.*)\)").Success)
{
if (!value.Contains("http:"))
{
Uri baseUri = new Uri(state.Url);
Uri absoluteUri = new Uri(baseUri, value);
value = absoluteUri.ToString();
}
if (this.Links.Exists(x => x.NavigateUrl.Equals(value))) continue;
try
{
bool validLink = true;
foreach (string invalidType in invalidTypes)
{
string v = value.ToLower();
if (v.EndsWith(invalidType) || v.Contains(string.Format("{0}?", invalidType)))
{
validLink = false;
break;
}
}
if (validLink)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(value);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
this.Links.Add(new Link() { Status = response.StatusCode, NavigateUrl = value });
if (response.StatusCode == HttpStatusCode.OK && state.Level < LIMIT)
{
WaitCallback item = delegate(object s) { FindLinks((UrlState)s); };
ThreadPool.QueueUserWorkItem(
item, new UrlState() { Url = value, Level = state.Level + 1 });
}
}
}
catch
{
this.Links.Add(new Link()
{
Status = HttpStatusCode.ExpectationFailed,
NavigateUrl = value
});
}
}
}
}
catch
{
///
/// If downloading times out, just ignore...
///
}
}
}
}
It looks like you are trying to automatically click a button after 5 seconds if the your spider job is running.
All the script manager is doing is embedding a tag containing your javascript when the markup is generated.
Id say the easiest way to do this is to add an attribute to your model.
class MyModel
{
public bool SpiderRunning { get; set; }
}
Then set this in your controller:
model.SpiderRunning = this.WebSpider.IsRunning
Then in your view, only add the script to the page if this value is true:
#if(Model.SpiderRunning)
{
<script>setTimeout(function(){document.getElementById("btnUpdateResults").click();}, 5000);</script>
}
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 the following code in my MasterPageBase.cs file:
protected override void OnLoad(EventArgs e)
{
string url = Request.Path;
var page = _ContentPageRepository.GetContentPageByUrl(url, ConfigurationManager.GetSiteID());
if (page != null)
{
PageBase.SetTitle(page.Title);
PageBase.SetDescription(page.Description);
PageBase.SetKeywords(page.Keywords);
}
else
{
this.ProcessSiteMap();
}
this.AddGACode();
base.OnLoad(e);
}
I need this.AddGACode(); to get added to the head section of the page, but when I view the source of the page as I am running the solution, I see that this is adding it to the body section of the page.
I have tried Page.Header.Controls.Add(AddGACode()); and get the following errors:
The best overloaded method match has some invalid arguments and cannot convert from 'void' to 'System.Web.UI.Control'
What can I do to get this code added to the head? TIA
EDIT: Request to see the AddGACode method:
private void AddGACode()
{
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
if (!ConfigurationManager.EnableUniversalGATracking)
{
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\">");
csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
}
else
{
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<!-- Universal GA Code --><script type=\"text/javascript\">");
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
}
}
}
EDIT:
This code is in the AddGACode method. There is still this.AddGACode(); in the OnLoad of the page that seems to duplicate the code with this edit, but both codes will disappear if I delete this.AddGACode(); from OnLoad
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<!-- Universal GA Code --><script type=\"text/javascript\">");
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
LiteralControl lc = new LiteralControl(csText.ToString());
Page.Header.Controls.Add(lc);
This adds the script into the head tag:
LiteralControl lt = new LiteralControl("<script type='text/javascript'>alert('test');</script>");
Header.Controls.Add(lt);
UPDATE
LiteralControl lt = new LiteralControl(AddGACode());
Header.Controls.Add(lt);
...
private string AddGACode()
{
var result = string.Empty;
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\">");
if (!ConfigurationManager.EnableUniversalGATracking)
{
csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
}
else
{
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
}
csText.Append("</script>");
result = csText.ToString();
}
return result;
}
I'd keep your markup, in this instance your ga scripts, on mastpage itself. In the head tag add two literals, gaGaq and gaUniversal an then use you logic to contol the visibility of them.
<head runat="server"><script type="text\javascript">
<asp:Literal id="gaGaq" runat="server">
<!-- Put you gaq code here-->
<!-- Keep {0} as a place holder for gaqCode -->
</script>
</asp:Literal>
<asp:Literal id="gaUniveral" runat="server">
<script type="text\javascrtip">
<!-- Put you universal code here-->
<!-- Keep {0} as a place holder for gaqCode -->
</script>
</asp:Literal>
</head>
C#
private void AddGACode()
{
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
if(ConfigurationManager.EnableUniversalGATracking)
{
//Set gaCode
gaUniversal.Text = string.Fomat(gaUniveral.Text, gaCode);
}
else
{
//Set gaCode
gaGaq.Text = string.Format(ga.Text, gaCode);
}
gaUniversal.Visible = ConfigurationManager.EnableUniversalGATracking;
gaGaq.Visible = !ConfigurationManager.EnableUniversalGATracking;
}
else
{
//Hide Both literals if no gaCode
gaUniversal.Visible = gaGaq.Visible = false;
}
}
You could also look at putting all this into a custom control. If you're interested in taking that route I wrote a blog article on exactly that for the gaq style google analytics so I could drop it onto my many asp.net websites. The code in that article owuld need to be modified to suite your needs but should be enough to get you stared.