How do you format a date variable in a GridView?

<asp:BoundField DataField="CreatedOn" DataFormatString="{0:M/dd/yyyy}" HtmlEncode="false" />
######Other Resources:

Registering Server Controls in Web.Config

A useful addition to ASP .NET 2.0 is the ability to register web controls in web.config. In ASP .NET 1.1, if you wanted to use a custom server control on twenty different pages, you had to register it on all twenty of those pages:

  1. <%@ Register tagprefix="tagprefix" Namespace="Namespace" Assembly="Assembly" %>

In ASP .NET 2.0, you can register the server control in the controls section of web.config once and use it in whatever page you want of the web application.

  1. <pages>
  2. <controls>
  3. <add
  4. tagPrefix="MyTagPrefix"
  5. namespace="My.Namespace"
  6. assembly="MyAssembly"/>
  7. </controls>
  8.  
  9. <!-- Other elements go here -->
  10.  
  11. </pages>

Read more on MSDN

Two Cents On Access Modifiers in C#

Access Modifiers

Access modifiers, as their name suggests, control who sees what in an application. C# has 4 basic access modifiers (there’s also a 5th one, but more on that later). Here they are, listed from least restrictive to most restrictve.

  1. public: accessible anywhere.
  2. protected: accessible to current class and all derived classes.
  3. internal: accessible to any class in the current assembly.
  4. private: accessible to current class only.

Easy enough to understand.

Some Things to Keep In With Access Modifiers

  1. Namespaces can’t have access modifiers. They’re always public. So: public namespace AwesomeNewNamespace { … } will produce a compile-time error.
  2. Classes can be either public or internal but not protected or private. So: private class AwesomeNewClass { … } will produce a compile-time error. This makes sense if you think about it — how exactly would you use a private or a protected class??
  3. Interfaces, like classes, can be either public or internal but not protected or private.
  4. Methods defined in interfaces can’t have access modifiers.
  5. Enums are always public. They can’t have access modifiers either.
  6. By default, classes are internal. So: class NotSoCool { … } is equivalent to internal class NotSoCool { … }.
  7. By default, methods in class are private. So void SomeAwesomeMethod() { … } is equivalent to private void SomeAwesomeMethod() { … }.
  8. Same goes for variables (fields): private unless specified otherwise.
  9. Needless to say, you can’t use access modifiers on variables inside a method: public voidMethod() { protected string someString; will produce a compile-time error.
  10. Derived classes can either have the same restriction level or can be more restrictive than the base class but not less restrictive. So: internal class Base { … } public class Child : Base { } will produce a compile-time error.

Now that we got that out of the way, let’s take a look at that 5th modifier that I mentioned at the beginning. This would be the compound modifier protected internal. After looking at it for a minute, you would think that it does what other compound modifiers in .NET do. For example, protected virtual void AwesomeMethod() makes AwesomeMethod both virtual and protected, so you’d think that protected internal AwesomeClass { … } would make the class both protected and internal (i.e., it is only accessible to derived classes in the assembly) but you would be wrong. For some bizarre reason that I have yet to fathom, the powers-to-be have decided that protected internal means protected or internal (so that the method is available to all derived classes as well as all classes in the current assembly).

Granting EXECUTE Permissions on All Stored Procedures

Something I’ve had to do often. Until now, I’ve gone through the “laborous” (hehe) process of remembering what stored procedures I’ve added and granting EXECUTE permissions to whatever user for each procedure. I was sure that there was an easier way to grant the permission on all stored procedures, and there is!

GRANT EXECUTE TO [Insert the name of the user here]

If you’re using SQL Server 2000, you don’t have it so easy. However, here’s an article on how to create a stored procedure to do the same.

The Obsolete Attribute

A quickie. The Obsolete attribute marks a class or method as (pardon the redundancy) obsolete. Usage:

  1. [System.Obsolete("This is an obsolete class; use NonObsoleteClassInstead")]
  2. public class ObsoleteClassExample
  3. {
  4. // Internals of the class
  5. }
Marking a Method Obsolete
  1.  
  2. public class NormalClass
  3. {
  4. // …
  5.  
  6. [System.Obsolete("This method is absolute; use NonObsoleteMethodInSomeClass")]
  7. public void ObsoleteMethodExample(string blah)
  8. {
  9. // Internals of the method
  10. }
  11.  
  12. // …
  13. }

No, there isn’t any difference in marking a class vs. method as obsolete. I just wanted to create two code blocks, go figure. :p

When you use a class/method marked as obsolete, VS 2005 shows you a nice warning in the “Error List” pane.

Static Constructors

The Problem

Suppose you have a static readonly string whose value you don’t know until runtime. Maybe you have to read it from FileAbcdefgh.txt when certain condition is true and read it from FileXyz.txt when it’s not. But once set, the value should never be modified again.

The Solution

I’m assuming you guessed that the solution to the problem is static constructors. You guessed right. ;) Static constructors, like the null coalescing operator, are a C# feature I was not aware of until fairly recently.

Static constructors look fairly similar to normal (default) constructors:

  1. public class StaticConstructorTestClass
  2. {
  3. private static readonly string someStaticString = string.Empty;
  4.  
  5. static StaticConstructor()
  6. {
  7. someStaticString = GetFromDatabaseOrWhatever();
  8. }
  9.  
  10. private static string GetFromDatabaseOrWhatever()
  11. {
  12. // Do the processing here
  13.  
  14. return "This is a string I got from database";
  15. }
  16. }

The Rules:

When creating static constructors, keep these rules in mind:

  1. Only one static constructor per class.
  2. The constructor can’t have any parameters.
  3. The constructor can’t have an access modifier (public/private/etc).
  4. The constructor executes before any instance constructor.
  5. The constructor executes only one time per class.

The ?? Operator

The Problem

Database access has to be my least favorite activity to code, right up there with coding public data access (to private fields). The worst thing about coding database access is — easily — the need to check for null values. I recently found a nugget in .NET that makes the process a bit less painless, and I’m putting it out here in the hopes that it will help somebody avoid this:

  1. public void Read()
  2. {
  3. // …
  4.  
  5. System.Data.SqlClient.SqlDataReader rdr = new System.Data.SqlClient.SqlDataReader();
  6.  
  7. if (!rdr.IsDBNull(0))
  8. {
  9. // Yay! It’s not null.
  10. }
  11.  
  12. if (!rdr.IsDBNull(1))
  13. {
  14. // Wow, the second field is not null either.
  15. }
  16.  
  17. if (!rdr.IsDBNull(3))
  18. {
  19. // And neither is this one; I’m so excited.
  20. }
  21.  
  22. if (!rdr.IsDBNull(4))
  23. {
  24. // This one isn’t either? Really?
  25. }
  26.  
  27. // …
  28.  
  29. if (!rdr.IsDBNull(723498234))
  30. {
  31. // And this one’s not null either. Oh, what joy.
  32. }
  33. }

The Solution

Enter ??. Wait, what? ?? is an actual operator in C# and not a spelling mistake on your part? I’ve never heard of it in my entire life (okay, so maybe you did hear of it before, but I haven’t, not ’til yesterday!).

You’d code the ?? like this:

  1. AwesomeObject someAwesomeObject = new AwesomeObject();
  2.  
  3. someAwesomeObject.AwesomeField = rdr.GetString(10) ?? string.Empty;

To read more on the ?? operator, try this MSDN article.

I finally found out that the operator is called null coalescing operator and is available in C# 2005 only. Another reason C# rocks. ; -) Any questions?

Render CheckBoxList as an Unordered List

Introduction

The CheckBoxList, like most other web controls, makes my life a whole lot easier by automating what used to be a lot of drudge work. The CheckBoxList also, like most other web controls, spits out ugly, ugly markup that makes me incredibly pissed off. But the good thing in ASP .NET is that if you don’t like the way something works, you can almost always inherit from the class and override the behavior, which is what we’re going to be doing with CheckBoxList.

Web Custom Controls vs. User Controls

Web custom controls have several benefits over user controls. To use a user control, you need to copy the .ascx file to each and every project that you you want to use it in, whereas web controls are compiled into .dll files, which means that to use them you just add a reference to the .dll file. There’s also the fact that user controls don’t have designer support (admittedly not a big deal for me, since I work almost exclusively in the “Source View,” but I know lots of other people swear by the “Design View”); web custom controls, on the other hand, do.

Web Custom Controls

Creating web custom controls can look like an untamable beast, but actually it’s quite easy. Start by clicking File » New » Project » Visual C# » Windows » Web Control Library. You can just as easily create a web custom control in whatever web project you happen to be working on, but because we’re interested in easy reuse, we’ll put our extended CheckBoxList file in a web control library. Name it whatever you want.

Visual Studio will automatically create a file called WebCustomControl1.cs for you. Delete everything inside the class — we don’t need it. Rename the file to something more appropriate, like UlCheckBoxList, and change all instances of WebCustomControl1 in the file to UlCheckBoxList (Visual Studio will probably automatically change the class name for you, but you also need to change the ToolboxData).

Base Class

All web custom controls need to inherit from the WebControl class either directly or indirectly. The CheckBoxList control already inherits from this class. Since we’re interested in only the rendering part of the CheckBoxList we’ll inherit from this one.

The Code

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Text;
  5. using System.Web;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8.  
  9. namespace XhtmlWebControls
  10. {
  11. [ToolboxData("<{0}:UlCheckBoxList runat=server></{0}:UlCheckBoxList>")]
  12. public class UlCheckBoxList : CheckBoxList
  13. {
  14. protected override void Render(HtmlTextWriter writer)
  15. {
  16. Controls.Clear();
  17.  
  18. string input = "<input id={0}{1}{0} name={0}{2}{0} type={0}checkbox{0} value={0}{3}{0}{4} />";
  19. string label = "<label for={0}{1}{0}>{2}</label>";
  20.  
  21. writer.WriteLine("<ul>");
  22.  
  23. for (int index = 0; index < Items.Count; index++)
  24. {
  25. writer.Indent++;
  26. writer.Indent++;
  27.  
  28. writer.WriteLine("<li>");
  29.  
  30. writer.Indent++;
  31.  
  32. StringBuilder sbInput = new StringBuilder();
  33. StringBuilder sbLabel = new StringBuilder();
  34.  
  35. sbInput.AppendFormat(
  36. input,
  37. """,
  38. base.ClientID + "_" + index.ToString(),
  39. base.ClientID + "$" + index.ToString(),
  40. Items[index].Value,
  41. (Items[index].Selected ? " checked" : ""));
  42.  
  43. sbLabel.AppendFormat(
  44. label,
  45. """,
  46. base.ClientID + "_" + i.ToString(),
  47. Items[index].Text);
  48.  
  49.  
  50. writer.WriteLine(sbInput.ToString());
  51. writer.WriteLine(sbLabel.ToString());
  52.  
  53. writer.Indent–;
  54.  
  55. writer.WriteLine("</li>");
  56.  
  57. writer.WriteLine();
  58.  
  59. writer.Indent–;
  60. writer.Indent–;
  61. }
  62.  
  63. writer.WriteLine("</ul>");
  64. }
  65. }
  66. }
  67.  

Explained

Line 11: [ToolboxData("<{0}:UlCheckBoxList runat=server></{0}:UlCheckBoxList>")]

This tells Visual Studio what to write in the “Source View” of the .aspx page in which we’re going to use the control. That is, if you drag and drop the control from the Toolbox onto the .aspx page.

Line 16: Controls.Clear(); The CheckBoxList has a single child control of type CheckBox, which is used to render all the checkboxes in the list. But as we’re going to be writing the HTML ourselves, we don’t care about this control. So I cleared it, just in case having it around screws up something.

Line 18: string input = “<input id={0}{1}{0} name={0}{2}{0} type={0}checkbox{0} value={0}{3}{0}{4} />”;

Line 19: string label = “<label for={0}{1}{0}>{2}</label>”;

The html that’s going to be outputted with some “string format variables” thrown in. The formats are going to be replaced with the actual values later on (lines 35 - 47).

Line 25: writer.Indent++;

Makes the <li> tags and everything underneath appear one tab to the right (in the HTML source code) of the <ul> tag.

Line 38: base.ClientID + “_” + i.ToString(),

Line 39: base.ClientID + “$” + i.ToString(),

If your CheckBoxList’s name was “CheckBoxList1,” then the id and the name you see in the HTML source code would be “CheckBoxList1_x” and “CheckBoxList1$x,” where x is the number of the checkbox in the list. I saw no reason to change this.

Adding Our Class to the Toolbox

Compile the Web Control Library you just created. Go to the Toolbox, right-click on “General” (or whichever tab you want to put the class under) and select “Choose Items” — In “Choose Toolbox Items,” under “.NET Framework Components,” select “Browse” and point to the .dll file of the class (should be located in the “Debug” folder in the “Bin” folder of your Web Control Library folder). Click OK. And you’re good to go.

4 of 6 pages « First  <  2 3 4 5 6 >

On the Side