Dynamic controls, viewstate and postback

When using dynamic controls, many people will encounter all sorts of different problems that can take hours or days to solve. It is therefore essential to understand how asp.net handles events, postback and viewstate.

Dynamic control disappears on postback

If you have a user control which contains a text box, a literal control and a submit and you add the control programmatically, chances are that when the user control’s submit button is clicked, the user control will disappear instead of showing the value of the textbox in the literal. This happens because the user control (.ascx) is hosted by the page (.aspx) and the parent page does know of its existence unless you have used the declarative syntax in your markup. Here’s the html for  a page called Slave.aspx

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master" EnableViewState="true" CodeFile="Slave.aspx.cs" Inherits="Slave" %>
<%@ Register Src="~/FirstControl.ascx" TagName="FirstControl" TagPrefix="gis" %>
<%@ Reference Control="~/WebUserControl.ascx" %>
<asp:Content ID="content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<hr />
<h2>slave page</h2>
For the slave...
<gis:FirstControl ID="FirstControl" runat="server" />
<asp:HiddenField ID="hf" Value="0" runat="server" />
<asp:PlaceHolder ID="ControlHolder" runat="server" />
<hr />

<gis:FirstControl ID=”FirstControl” runat=”server” /> is the declarative syntax here but that’s not dynamic loading. FirstControl has a button and a checkbox and when the checkbox is checked and the submit button clicked, it will load dynamically another user control, in this case, WebUserControl.ascx. Below is the markup for FirstControl.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="FirstControl.ascx.cs" Inherits="FirstControl" %>
<<%@ Reference Control="~/WebUserControl.ascx" %>
<hr />
<h3>First Control</h3>
<asp:CheckBox ID="chkMaster" runat="server" />&nbsp;&nbsp;<asp:Button ID="btnFirstSubmit" Text="First Submit" OnClick="btnFirstSubmit_Click" runat="server" />
<hr />

And here’s the code behind for FirstControl.ascx:

protected void btnFirstSubmit_Click(object sender, EventArgs e)
 if (chkMaster.Checked)
 // show the other control
 WebUserControl wuc = (WebUserControl)LoadControl(typeof(ASP.gis), null);
 PlaceHolder holder = (PlaceHolder)FindControlRecursive(Page, "ControlHolder");

When the submit button on the FirstControl.ascx (provided the checkbox is checked), the user control will dynamically load the WebUserControl.ascx which contains a textbox, a submit button and a literal to print out the name in th e textbox. The WebUserControl is loaded properly but when its submit button is clicked, it will disappear on postback.

Solution: The reason for this is that the parent page (Slave.aspx) does not know of its existence. Therefore we need to make the page aware of it. When you load a dynamic control, you need to keep track of it, whether through ViewState or Hidden Form Field. I’ve used a hidden form field in this instance and here’s the code in the FirstControl.ascx file:

protected void btnFirstSubmit_Click(object sender, EventArgs e)
 if (chkMaster.Checked)
 // show the other control
 WebUserControl wuc = (WebUserControl)LoadControl("~/WebUserControl.ascx");
 wuc.ID = "wuc";
 PlaceHolder holder = (PlaceHolder)FindControlRecursive(Page, "ControlHolder");

 HiddenField hf = (HiddenField)FindControlRecursive(Page, "hf");
 hf.Value = "1";

Important thing to note here is that we need to make sure that we assign a unique ID to the dynamic control. And here’s the code behind for Slave.aspx:

protected void Page_Load(object sender, EventArgs e)
 if (hf.Value == "1")
 WebUserControl wuc = (WebUserControl)LoadControl("~/WebUserControl.ascx");
 wuc.ID = "wuc";

So to prevent the dynamic control from disappearing, you need to keep track of whether you’ve added it or not and load it if you have.

Loading a dynamic user control without specifying the path

If we want to load our control when some action is performed and not have it sit there and go through the asp.net life cycle for no reason, then we need to add a reference to the user control in the parent page. Now LoadControl is the method we’re after and it has 2 overloads. The first one requires a path to the user control and that works flawlessly. The second one takes a strong type and a parameterised object.

Casting the control to the right type

If you have properties on the control, you will need to cast it to the right type. Otherwise your properties won’t be available to you. The following code does not give me the intellisense for the public properties on WebUserControl because it’s been casted as a generic UserControl.

UserControl myUserControl = (UserControl)LoadControl(“~/WebUserControl.ascx”);

To access these public properties, you will need the following code:

WebUserControl myUserControl = (WebUserControl)LoadControl(“~/WebUserControl.ascx”);

Remember that you need to reference the WebUserControl in the parent page, otherwise you’ll get a compile time error:

<%@ Reference Control=”~/WebUserControl.ascx” %>

Dynamically loading the control by type

If you want to do the following, you will not see your control loaded:

WebUserControl myUserControl = (WebUserControl)LoadControl(typeof(WebUserControl), null);

This is because when you use the path to the user control, asp.net will fire off all the events that the control has missed until it catches with the current event. So if you’re adding a user control in the button click event, the init and load event have already passed, so the newly added control need to catch with the events until it is in sync. The workaround is to strongly type the user control and you do this by adding the ClassName attribute to the control’s markup as follows:

<%@ Control Language="C#" AutoEventWireup="true" ClassName="gis" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<hr />
<h3>Web User Control</h3>
<asp:Literal ID="litSomething" runat="server" /><br />
<asp:Literal ID="litText" runat="server" /><br />
<asp:TextBox ID="txtName" runat="server" />
<asp:Button ID="btnSubmit" Text="Submit from user control" runat="server" OnClick="btnSubmit_Click" />
<hr />

Notice the ClassName=”gis” in the code above. Now you would assume that you can do something like this:

WebUserControl myUserControl = (WebUserControl)LoadControl(typeof(gis), null);

But that won’t work because the ClassName “gis” cannot be found as it resides in the ASP namespace. Here’s how to do it properly:

WebUserControl myUserControl = (WebUserControl)LoadControl(typeof(ASP.gis), null);

You will get “System.MissingMethodException: Constructor on type ‘ASP.gis’ not found.” if you try to pass in parameters though:

WebUserControl wuc = (WebUserControl)LoadControl(typeof(ASP.gis), new object[] { “hey you” });

For some reason asp.net is unable to get the overloaded constructor for the user control even though it’s private. From what I’ve read, only the parameterless constructor is called.

Where to add dynamic controls? Page_Init, Page_Load?

You can add them whenever you want but if you don’t add it in Page_Init, the control will not be able to participate in ViewState as the loading of view state comes before page load.

Events available to User Control

You can use Init, Load and PreRender.

Buying expired domain names and making money from them

Going into the expired domain names business can be very rewarding if you know what you’re doing. Most people purchase expired domains as a quick way to make money from them while a few just want to get hold of a particular domain. Here we’ll be talking about how to get the most of expired domains.

How long after a domain expires do you have to wait until you can purchase it?

There are hundreds and hundreds of domains which get expired everyday because they are not renewed by their owners. However I’ll be concentrating my efforts on the .uk domains here. After a domain expires, there’s a 30 day grace period where the owner can still renew the domain. If the domain is not renewed, it goes into a 60 day suspension period where the name servers do not resolve. After that, there’s an additional 2-9 days before the domain becomes available again. So basically, you’re looking at 92-99 days before you can grab an expired .uk domain name.

Why would you choose an expired domain name over another?

There are two essential things to take into consideration when buying a domain that has expired. First is the Google PageRank (PR) and second is the traffic that it receives. There are ways for you to get a glimpse of the traffic for a particular domain like hitwise.co.uk but unless you keep all of the website’s content, the traffic will soon vanish. The problem with reconstructing the same content is that you will end up infringing intellectual property rights. That being said, traffic can also come in terms of referrals from other websites. For example, if there’s a link to that expired domain on a popular website, then you can get a lot of traffic from that.

Most people find it easier to work with PageRank though. The higher the PR of the expired domain, the better it will be for you because we will be able to sell links on that domain at a much higher price and that’s what a lot of link sellers do, ie, grab expired domains, and sell links on them. Link buyers will look at the PR and think there’re getting a really good deal when it’s not really.

If you can see the PR of the expired domain just before it expired, you can make your own decision on whether to get it or not. However PR is just a reflection of the quantity and quality of backlinks. So if the important backlinks are removed, the PR of the website will decrease as well. The best way to know if an expired domain is really worth buying is going to Yahoo Site Explorer and looking at the backlinks. Go to the webpages where the link is placed and check the corresponding PR of the webpage, if it has a high PR, then it’s good. Also check how far down the bottom the backlink is placed. The higher up the webpage, the better the backlink and the fewer the number of outgoing links, the greater link juice you will get.

Backlinks from .ac.uk or .org.uk or gov.uk websites are likely to have a higher PR than others. However sometimes sites with other extensions have high PR as well and that’s why you will need to check them all to make sure you’re not missing out. Somestimes you’ll get a decent backlink from bbc.co.uk and other newspaper as well.

How to maintain the PR of an expired domain?

Once you’ve got a expired domain with a decent number of backlinks, you can pretty much guess what PR it will get during the next PageRank update. This will depend on the quantity and quality of the backlinks. However there are some steps that you will need to take to ensure that the PR is not reset for that domain. Some people just buy the expired domain and throw in content which is completely different to what was on that domain before and then wonder why the PR has been reset to zero and become N/A (not applicable). If you want to preserve the PR, you will need to have a similar theme to what was there before. Go to archive.org and look at the website when it was live. Make sure you write content similar to what was there before and try to keep the title tag of the homepage as closely as it was before. It is important that you do not just copy the same exact text from archive.org as this would be infringing copyrights. And do not attempt to ressurect the website by reconstructing the website from archive.org’s copy.

How to get revenue from your expired domain?

You can get a decent income from buying an expired domain by selling blogroll (sitewide links), blog posts with links to sponsor sites or placing banners on it. You can also put relavant ads by using Adsense, in-text advertising like Kontera/Infolinks or Adsense for Domain. You will find a lot of interest on forums.digitalpoint.com Link Sales section and most people will prefer to pay through Paypal.

Expired domains and SEO

Many seo professionals will say that it is useless to buy expired domains but that’s not entirely true. For a Search Engine Optimisation (SEO) point of view, the domain will lose its authority once it is dropped. That is why it is better to transfer ownership before a domain get dropped if you still want it to rank for its search terms afterwards. In the case of expired domains, what I’ve seen is that you will still get traffic from referring sites where your backlinks are placed and some organic search as well if you keep the same theme. You will need to check the raw log file access and see which deep pages are being requested from referring sites and try to ressurect these ones to preserve the pagerank and possibly get organic search traffic from it as well.

It is more difficult to make an expired domain rank for its search terms as it was before but you could try link building for the site and keeping the same content. And if you just want to make quick cash from it, then all you need is a high PR and some naive link buyers who do not take the time to research the domain onto which they’re buying links to see if it has been dropped before.

Application pool recycling – The not so obvious reason

If your application pool is recycling for no reason, it could be a problem for your visitors because the loading time of your webpages will be increased. Nobody likes slow websites and this can discourage people from coming to your site and this is why you need to fix the problem as soon as possible.

On one of my sites hosted on a Windows 2008 R2 server, I’ve got a dedicated app pool for a website. However I’ve noticed that the application was recycling quite often and this impacted the load time of the website. When any page from the website is loaded for the first time, the web app does a number of things including caching of certain data and loading some necessary classes for it to function properly. This needs to be done only once and any further HTTP requests should be fast from then onwards.

Drilling down into the problem, I found that the application pool has a default timeout setting of 20 mins. This means that if no requests are made within 20 mins, the app pool will be shut down. This is only good if you have a lot of app pools running and running low on memory. However for a low traffic site where you don’t necessarily have visitors within every 20 min interval, your app pool will recycle and the next visitor that you get will see the page load really slowly because startup methods are being called by your web app. To prevent this from happening, you need to set the Idle Time-out (minutes) property in the app pool to zero (0).

You should also set the Regular Time Interval (minutes) to 0 to avoid your application from recycling at specific period of times. It’s also a good idea to enable Event logging for when your application pool is being recycled so that you can easily know if there’s any problem with your website.

Configuring IIS 7.5 logging in Windows 2008

Raw log file for your website gives you the facility to see who’s been accessing your webpages with information on the client IP address, the time the request was made, the referrer, time taken to process the request and so much more. That’s why it is essential to have logging enabled for your site.

In Windows 2008, you can choose among different log file formats (IIS, NCSA, W3c and Custom). If you go to the IIS Management Console, you will see “Logging” under IIS features and when you double click on it, you will have a couple of options to choose from. IIS and NCSA do not allow you to change what is being logged but with the other two formats you can. W3C format is the preferred format for many people. With that format chosen for your log files, you can select which fields you want to get logged for each HTTP request by clicking on the “Select Fields” button next to the file Format. The log files are saved in the following directory by default:


You can also choose how often a new log file is created by selecting the best option for Log File Rollover. For high traffic sites, you can have it daily or hourly but if you have a moderate traffic, going with the monthly log is the way forward. You should also check the option for “Use local time for file naming and rollover” to make it easier for you to distinguish between the various log files created.

Custom IIS logging

If you want to re-arrange the fields in your log file, you will have to go with Custom logging. For example, if you wanted the client IP address to come before the date and time of the http request, then only custom logging will allow you to do that. You cannot also change the name of the log file name, it is in the format of u_exYYMMDD.

Although custom logging for IIS gives you a lot of flexibility in terms of what gets logged and many more, there’s a major drawback to that approach and that is performance.  The IIS worker process handles custom logging and the HTTP.sys kernel-mode cache is disabled for IIS which degrades performance (see this link for more information).

Changed from pay monthly to pay as you go tariff with o2

Seeing that I was only using a fraction of the allowance on my pay monthly contract, I decided to downgrade to a pay as you go tariff on my iPhone. I opted for the text and web plan because that made more sense for me. I wanted to keep my mobile number and o2 said that they would send me another sim card through the post as the other one would not work when it was time for the switch over.

Couple of days after the call to 02 to switch plans, I received the Pay as you go sim card. I was told that I would need to switch the sim cards on the date that the switch over would happen which was 2 weeks from my initial call to 02. All they told me was that I would just need to remove my old sim card and insert the new one and everything would work fine. They also mentioned that it could take several hours before I would be able to use the new sim card.

On the switchover date which was yesterday, I changed sim cards because my pay monthly sim showed “No service” at the top instead of showing me the 02 mobile service operator. I tried to call my cell phone but I received “The person you are calling is not accepting anonymous calls” message. I thought that the new sim card was not ready to use. Since the switch over happens at midnight, I expected things to start working back to normal within 12 hours but I still could not get through at 7pm in the evening.

So my mobile phone was not working and I was getting nervous now. I tried switching it off and back on a couple of times but that did not work. Although I knew I couldn’t make calls because I have not topped up yet, I tried that as well and it prompted me to top up which I denied. I wanted to know that everything was working fine before I spend my money. O2 send me a couple of messages and they said that switching the mobile on and off until it connects is the way to go but obviously that did not work. I decided I was going to call 02 the next day if it does not work because if I call them on the same day, they would just say that it needs time and the switchover would happen sometime soon.

Well the next morning, the mobile was not working and I gave 02 a call and the agent told me that I need to top up first before I can use the phone. She said that it’s only when you top up for the first time that the pay as you go sim card gets activated. Well why did 02 not tell me anything about this in the first place? For a whole day I was not reachable, I could not make/receive calls and text messages and spent time looking on the net for a solution to the problem when o2 could just have told me this.

Instead of sending me text messages for extras that I can get, I would prefer them to tell me how to get my sim card to work. Anyway there was a new number on the new pay as you go sim card but that was overriden with my previous mobile phone number. For now everything is fine and I’ve associated my bank card with the sim for easy top up.