Tuesday, August 10, 2010

Building a FindControl

There are times in any semi-advanced ASP.NET developer's life when they’re working with databound templated controls (such as the Repeater) and they need to find a control without knowing where it is, or even if it's there.
Normally, you’re reduced to using the standard FindControl method available on any control. But this only finds controls with a given id within the same NamingContainer.
So now take a look for finding the control some another way.

Get All Child Controls of a Given Type:
public static IEnumerable<T> GetAllChildControlsOfType<T>
    (this Control parent) where T : Control
 {
    if (parent == null) throw new ArgumentNullException("parent");
    foreach (Control c in parent.Controls)
    {
        if (typeof(T).IsInstanceOfType(c)) yield return (T)c;
        foreach (T tc in c.GetAllChildControlsOfType<T>())
            yield return tc;
    }
    yield break;
 }

Get All Child Controls that Implement a Given Interface:

For when you don’t care what the control is, as long as it can do a particular thing….try it with IButtonControl.
public static IEnumerable<T> GetAllChildControlsWithInterface<T>(this Control parent)
 {
    if (!typeof(T).IsInterface) throw new NotSupportedException
    (string.Format(CultureInfo.InvariantCulture,"Type '{0}'
    is not an interface".ToFormattedString(typeof(T).ToString()));
    if (parent == null) throw new ArgumentNullException("parent");
    foreach (object c in parent.Controls)
    {
        if (typeof(T).IsInstanceOfType(c))
            yield return (T)c;
        Control ctrl = c as Control;
        if (ctrl != null)
            foreach (T tc in ctrl.GetAllChildControlsWithInterface<T>())
                yield return tc;
    }
    yield break;
 }

Find All Controls With a Given ID:
Find every Textbox with an Id of ‘FirstName’ within a repeater….
public static IEnumerable<T> FindAllControl<T>
    (this Control parent, string id) where T : Control
 {
    if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id");
    return parent.GetAllChildControlsOfType<T>()
        .Where(c => string.Equals(c.ID, id, StringComparison.OrdinalIgnoreCase));
 }

Find The First Control with an ID:
public static T FindControl<T>(this Control parent, string id) where T : Control
 {
    return parent.FindAllControl<T>(id).FirstOrDefault();
 }

Change The OutputCache Provider During Runtime

One of the changes in ASP.NET 4 is the ability to override the OutputCache provider name in the Global.asax file. This enables us to create logic that stores the OutputCache in more then one type of cache according to some state or behavior. When you do that you need to supply the name of the OutputCache provider by overriding the GetOutputCacheProviderName method.

Changes in Web.Config File:
<caching>
<outputCache>
<providers>
<add name="InMemory" type="InMemoryOutputCacheProvider"/>
</providers>
</outputCache>
</caching>

If I’ll run the application now the default OutputCache will be the ASP.NET supplied OutputCache. If I would like to override it then the following code which will be written in the Global.asax file will help me achieve it:

public class Global : System.Web.HttpApplication
{
public override string GetOutputCacheProviderName(HttpContext context)
{
return "InMemory";
}
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}

Pay attention: I return the provider name that was registered earlier in the configuration file. Also, I could have provided whatever behavior that I want in order to return my needed provider per some situation.
The scope of the GetOutputCacheProviderName method is per request which means that every request can get it’s own OutputCache provider.

Thursday, August 5, 2010

10 HTML tags which are not used as often as they deserve

1. <fieldset> is a way to group a set of form fields such as inputs or textareas. It's not a usability advantage to have long forms, but when you must you can divide the form in several sections using this block element.

2. <legend> goes hand in hand with <fieldset>: when you insert it into a fieldset, its content will be displayed as the title of the group of fields:
Code : <form><fieldset><legend>My fields<legend><p>Enter your name... <input type="text" name="nickname" /></p></fieldset></form>

3. <label> has both a semantic and practical power which I commonly never seen employed for the good. A label should be associated with a form field in one of the two ways I will show. When the label is linked to the field this way, it acts as an extension for it; for example, clicking on the label of the checkbox will turn on and off the box itself. Instead, clicking on the label of a text field would give the focus to it and put the cursor in it, making the user ready to write. Thus, labels extend the clickable area available to the users.
But that's not all. Labels have also a semantic association with form elements, and as such are read out by screen readers when they access a form. There's no reason to invent styled <div> tags for your forms: put in labels instead.
You can link a label to a field by including the field in the label itself:
Code : <label><input type="checkbox" name="agree" /> I agree to the terms and conditions</label>
Or you can use an id on the input tag which you refer to in the label. Which method you should use is a matter of simplifying the application of styles to both elements.
Code : <label for="nickname">Nickname</label>
<input type="text" id="nickname" name="nickname" />

4. The <button> block element is by far more flexible than its cousin <input type="button"> and <input type="submit">. The reason is you can nest other tags in <button>'s content.
Thus you can go from a simple button:
Code : <input type="button" value="A button" />
To a more complex one:
Code : <button><strong>A strong button</strong></button>

5. <dl> stands for Definition List. It is the equivalent of <ol> and <ul> when the basic element is a tuple composed of two values: name and content. This were originally used for glossaries, but you can find many more creative solutions in the web.

6. <dt> is the definition term, used in the definition list above. Stay tuned for three rows to see a code sample which involves both.

7. <dd> is the definition content.
Code : <form><dl><dt>Nickname:</dt><dd><input type="text" name="nickname" /></dd></dl></form>
And it's indeed a way to delete some of the <div class="label"> rules.

8. <optgroup> is used to group options inside a select element. When there are many <option> tags, a simple layer of hierarchy can go a long way in aiding the user in its choice. Only the options themselves would be selectable, but the optgroup labels would acts as a title for the group.
<select name="enemy">
    <optgroup label="Milky Way">
        <option value="Apophis">Apophis</option>
        <option value="Anubis">Anubis</option>
        <option value="Replicators">Replicators</option>
    </optgroup>
    <optgroup label="Pegasus galaxy">
        <option value="Wraith">Wraith</option>
        <option value="Genii">Genii</option>
    </optgroup>
</select>

9. <blockquote> is a block element dedicated to quoting other sources. It's probably one of the most adopted of the tags described in this article. You can saygoodbye to <div class="quote"> if you haven't already.

10. <col> and <colgroup>, when inserted between a <table> tag and its contents, respectively act as placeholders for a column or a columns set. Whenever you want to apply column-based styles, instead of repeating classes on all the cells of the table you can simply organize them around columns:
<table>
    <col style="background-color: grey;" />
    <col style="background-color: blue;" />
    <tr>
        <td>A</td>
        <td>B</td>
    </tr>
</table>
I hope you have gained some tips which you weren't aware of - feel free to add your commonly neglected HTML tags in the comments if you feel they would be actually useful.

Tuesday, August 3, 2010

Common Windows issues you can fix with a registry hack

In this article, I want to share with you 10 handy registry hacks for Windows XP and Vista.

1: Disable AutoPlay
I always find it a bit annoying to insert a TechNet CD and have Windows open Internet Explorer and display a bunch of information I don’t care about. I would rather just be able to navigate through the disc’s file system and go directly to what I need. Fortunately, it’s easy to create a registry setting that disables AutoPlay:
  1. 1. Navigate through the Registry Editor to HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer.
  2. 2. Create a DWORD named NoDriveTypeAutoRun.
  3. 3. Set the value to 000000FF.

2: Increase the maximum number of simultaneous downloads
As a technical writer, I’m constantly downloading files. Sometimes I need to download a lot of files, and Windows’ limit on the number of files that can be downloaded simultaneously gets in the way. If you’re in the same boat, you can tweak the registry so that Windows will let you download 10 files at a time:
  1. 1. Navigate through the Registry Editor to HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings.
  2. 2. Create a new DWORD named MaxConnectionsPerServer and assign it a value of 0000000a.
  3. 3. Create a new DWORD named MaxConnectionsPer1_0Server and assign it a value of 0000000a.

3: Change the name of the registered user
When you install Windows, you’re prompted to enter a username and a company name. But since it’s fairly common for companies to merge, you may want to change the name of the company Windows is registered to by using this hack:
  1. 1. Navigate through the Registry Editor to HKLM\Software\Microsoft\Windows NT\CurrentVersion.
  2. 2. Change the values that are assigned to the RegisteredOwner and RegisteredOrganization keys to reflect the new ownership information.
4: Prevent the Recycle Bin from being deleted
If you’ve ever right-clicked on the Windows Recycle Bin, you know there’s a Delete option, which can be used to get rid of it. If you want to prevent the Recycle Bin from accidental deletion, follow these steps:
  1. 1. Navigate through the Registry Editor to HKCR\CLSID\{645FF040-5081-101B-9F08-00AA002F954E}.
  2. 2. Create a new registry key called Shell.
  3. 3. Create a new registry key named Delete and put it beneath the Shell key. The path should look like this: HKCR\CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\Shell\Delete.
  4. 4. Modify the Default key and assign it a value of Recycle Bin.
5: Eliminate cached logons
Windows is designed to allow users to log on using cached logins if no domain controller is available to authenticate the request. If you want to make sure that a login request is always authenticated by a domain controller, you could change the number of cached logons that are allowed from 10 to 0 (or you could increase the number of cached logins allowed to 50). To do so, follow these steps:
  1. 1. Navigate through the Registry Editor to HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\winlogon.
  2. 2. Create a new REG_SZ setting named CachedLogonsCount.
  3. 3. Assign this new setting a value that reflects how many concurrent cached logins you want to allow.
6: Encrypt and decrypt from a shortcut menu
Normally, when you want to encrypt or decrypt a file in XP Pro or Vista, you just right-click on the file or folder and choose the Properties command from the shortcut menu. When the properties sheet appears, click the Advanced button on the General tab and then use either the Encrypt or the Decrypt option.
If all that seems like a lot of work, you can add those options to the shortcut menu you see when you right-click on a file:
  1. 1. Navigate through the Registry Editor to HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced.
  2. 2. Create a new DWORD called EncryptionContextMenu and assign it a value of 1.
7: Delay Windows Activation
Typically, when an organization deploys Vista, it will create a master image, run SYSPREP, and deploy the image. The problem is that it might be a while between the time that SYSPREP is run and when Vista is actually deployed.
Microsoft will allow you to extend the activation period by 30 days, but you can do that only three times. You can, however, use a registry hack to get around this limitation:
  1. 1. Navigate through the registry to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SL.
  2. 2. Change the value associated with the SkipRearm key to 1.
  3. 3. Open a Command Prompt window and enter the following command: slmgr -rearm.
8: Relocate your offline files
When you use Vista’s Offline Files feature, the offline file cache is automatically placed on your C: drive. But my laptop has two hard drives in it, and I wanted to configure Vista to place my offline files onto my secondary hard drive. I accomplished the task by following these steps:
  1. 1. Open the Control Panel and click on the Network and Internet link, followed by the Offline Files link. Windows will display the Offline Files properties sheet.
  2. 2. Disable offline files if they are currently enabled.
  3. 3. Click OK and reboot the machine.
  4. 4. When the computer reboots, open the Registry Editor and navigate to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\CSC.
  5. 5. Create a new string value named Parameters.
  6. 6. Assign this value to the Parameters key: \??\e:\csc, where e: is the drive letter you want to use.
  7. 7. Exit the Registry Editor and reboot the computer.
  8. 8. When the machine reboots, enable offline files.
  9. 9. Reboot the computer one last time. Now, you can start making folders available offline.
9: Disable User Account Control
One of the things about Vista that seems to irritate a lot of people is the User Account Control feature. In essence, an administrator is treated as a standard user. Administrators who attempt to perform an administrative action receive a prompt asking whether they initiated the action. I think that this prompt is a valuable safeguard against malware, but since a lot of people don’t like it, here’s how to use the registry editor to suppress the prompt:
  1. 1. Navigate through the registry editor to HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System.
  2. 2. Change the value of the ConcentPromptBehaviorAdmin key to 00000000.
10: Don’t display the last user who logged in
Windows Vista is designed so that when you press Ctrl+Alt+Delete to log in, it will display the name of the user who logged in most recently. This can be a bit of a problem if multiple users share a common PC. They may forget to check to see who was logged in previously and key in their own password in association with another user’s login name. If they try this enough times, they could lock the other user out. You can get around this problem by using a simple registry tweak to tell Windows not to display the name of the user who was logged in previously:
  1. 1. Navigate through the Registry Editor to HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System.
  2. 2. Set the DontDisplayLastName key to a value of 1.