Saturday, September 02, 2006 7:33:50 PM UTC :: Filed Under ASP.NET | C# | Web Design

When trying to test a long web form, it gets really annoying having to manually populate the form with information only to submit the form to see your error and then have to do the whole thing over again once you think you’ve fixed the problem.

Since I don’t own a copy of Visual Studio .NET 2005 Testing Edition, I haven’t had much luck with finding good ways to test the UI (i.e., good ways to pre-populate forms for testing.) Of course, one way to test a form is to actually set all the values in a form on the ASPX page and then hope you remember to delete all those values once you publish the site. However, this becomes very annoying if you don’t get things right the first time.

To make my life easier and make UI testing less painful, I came-up with a nifty way to "cheat"... I’ve started using conditional compilation to populate my forms when Visual Studio is in DEBUG mode, but leave the forms blank when in RELEASE mode. So far, it works pretty slick, provided that I remember to compile my code in release mode before publishing it!

I wish I would’ve know about conditional compilation a while ago… it’s a really neat feature. It took me a while to get it working properly, and here is how.

  1. Start with a Visual Studio 2005 Web Application Project instead of the Visual Studio 2005 Web Site Project.  Note that you’ll have to download the Web Application Project because created after Visual Studio was released.  The application project behaves more like the Visual Studio 2003 web project and gives you “Build” options in the project’s Properties menu.
  2. Once you have the web project created, right-click on the project title and select Properties and then the Build tab.  You should see a screen like this.

  3. While Configuration is set to Debug, leave Define DEBUG constant and Define TRACE constant checked.  Then switch Configuration is set to Release and uncheck Define DEBUG constant and Define TRACE constant.

  4. The rest is easy.  In your code, you can use the conditional compilation directive #if to make sure the code you use to pre-populate your forms only exists in your code when Visual Studio .NET is in Debug mode:

    protected void Page_Load(object sender, EventArgs e) {

            if (!Page.IsPostBack) {

    #if DEBUG

                this.txtFirstName.Text = "John Doe";

    #endif

    }
    }

  5. Run your site in Debug mode and you should see your textbox named txtFirstName populated with “John Doe”.  Run it in Release mode and your form should be blank.  Sweet!

Obviously, to keep your code a bit cleaner, you should probably create a method that contains all your form population code and you can mark that method with a conditional attribute by marking it with [Conditional(“DEBUG”)].  Note that you will have to add the System.Diagnostics namespace to your file in order for this attribute to work.

So there you have it!  Make your UI testing a bit easier and still keep your production code clean.

Wednesday, June 07, 2006 6:44:04 PM UTC :: Filed Under ASP.NET | C# | VB.NET | XML

One thing that was painfully lacking in Visual Studio 2003 was the ability to work with XML and XSLT.  Most people opted to purchase third party tools like XML Spy to deal with VS.NET's inadequacies.  However, Visual Studio .NET 2005 has a group of new tools that add things such as XSLT debugging and Intellisense that make working with XML related files much more tolerable.

In addition, the .NET Framework 2.0 has undergone some significant improvements in the System.XML namespace.  If you work with XML on a frequent basis, you'll want to be sure to read through these MSDN articles and see what's new in version 2:

Saturday, April 29, 2006 1:46:36 AM UTC :: Filed Under ASP.NET

Note to self: Bookmark this link! MSDN: 101 Samples for Visual Studio 2005

Wednesday, April 26, 2006 1:14:07 PM UTC :: Filed Under ASP.NET

It seems like such a simple thing.  You have a form.  You have one submit button.  Yet when you hit your Enter key, the form submits, the page posts back, and… well, nothing.  For some reason Internet Explorer doesn’t seem to understand that the Enter key should post the form.

Thanks to some handy-work by the ASP.NET 2.0 developers, there is a solution for this.  In your <form> tag, you now have a property called defaultbutton that can be used to make sure that the button you want to be ‘clicked’ when hitting the enter key actually is.

<form id="form1"  runat="server" defaultbutton="btnSearch">

But wait, there is more!  A new defaultbutton property also makes it super easy to make sure that the cursor auto-magically starts on the field of your choosing so you don’t have to write your own onload JavaScript event handler:

<form id="form1"  runat="server" defaultbutton="btnSearch" defaultfocus="txtSearch">

The more I learn about ASP.NET 2.0 and Visual Studio .NET 2005, the more I’m impressed.  It’s the little details like these that get me all excited!

Thursday, March 30, 2006 5:59:00 AM UTC :: Filed Under ASP.NET
If you have Visual Studio .NET and the IE7 Beta installed on your PC, you might have noticed that the CSS Style Builder window pops-up and then instantly disappears.  Apparently the glitch is caused by IE7 and a fix can be found on Marc Brown’s MDSN blog.
Tuesday, March 21, 2006 3:52:16 AM UTC :: Filed Under ASP.NET | Web Design
When ever a client requires that the application you are going to build for them must be backwards compatible, their old browser become you’re new problem.  Fortunately, if the old browser is Internet Explorer, you now have hope!  Thanks to a link forwarded to me by my friend Mark Schmidt, there are several ‘stand-alone’ versions of Internet Explorer available for download that can be run along with your currently installed version of IE.  Visit Evolt.org to download everything from IE 3 to IE 6.
Friday, March 17, 2006 10:52:32 PM UTC :: Filed Under ASP.NET | VB.NET

To customize the default VB file templates used in Visual Studio .NET 2003, modify the following files to your heart’s content:

C:\Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBWizards\DesignerTemplates\1033

Saturday, February 25, 2006 2:02:05 AM UTC :: Filed Under ASP.NET

Maruis Marais from CodeProject.com was nice enough to share is extensive library of Visual Studio 2005 Unit Testing Code Snippets (C#).  A VB.NET set would sure be nice!   Upon trying to install these code snippets, I realized that the Code Snippets Manager does not show-up on my Tools menu in Visual Studio 2005 and I have no idea why.  I can still access the manager by typing Ctrl+K then Ctrl+B, but it would be nice if I could just go to the Tools menu because I know I’ll forget that key combination! ;-)

Update: I was able to add the Code Snippets Manager back to the Tools menu by opening VS.NET 2005 and navigating to Tools > Customize... > Commands (Tab) > Category: Tools and then dragging the Code Snippet Manager back into the Tools menu.

Wednesday, February 15, 2006 9:39:36 PM UTC :: Filed Under ASP.NET | VB.NET

Abstract class – Defines the methods and common attributes of a set of classes that are conceptually similar.  Abstract classes are never instantiated.

Attribute - Data associated with an object (also called a data member.)

Class – Blueprint of an object - defines the methods and data of an object of its type.

Constructor - Procedure that is invoked when an object is created.

Concrete class – A class that implements a particular type of behavior for an abstract class. Concrete classes are specific, non-changing implementations of a concept.

Derived Class - A class that is specialized from a base class.  Contains all of the attributes and methods of the base class but may also contain other attributes or different method implimentations.

Destructor - Procedure that is invoked when a object is deleted.

Encapsulation – Typically defined as data hiding, but better thought of as any kind of hiding (type, implementation, design, and so on.) Objects encapsulate their data.  Abstract classes encapsulate their derived concrete classes.

Functional Decomposition - A method of analysis in which a problem is broken into smaller and smaller functions.

Inheritance – A way that a class is specialized, used to relate derived classes with their base classes. A class inherits from another class when it receives some or all of the qualities of that class.  The starting class is called the base, super, parent, or generalized class, whereas the inheriting class is called the derived, sub, child, or specialized class.

Instance – A particular example of a class. (It is always an object.) A particular instance or entity of a class.  Each object has its own state.  This enables me to have several objects of the same type (class).

Instantiation – The process of creating an instance of a class.

Interface – An interface is like a class, but only provides a specification – and not an implementation – for its members.  It is similar to an abstract class consisting only of abstract members.  When programming, you use interfaces when you need several classes to share some characteristics that are not present in a common base class and want to be sure that each class implements the characteristic on its own (because each member is abstract.)

Member - Either data ora procedure of a class.

Method - Procedures that are associated with a class.

Object - An entity with responsibilities.  A special, self-contained holder of both data and procedures that operate on that data.  An object's data is protected from external objects.

Perspectives – There are three different perspectives for looking at objects: conceptual, specification, and implementation.  These distinctions are helpful in understanding the relationship between abstract classes and their derivations.  The abstract class defines how to solve things conceptually.  It also gives the specification for communicating with any object derived from it. Each derivation provides the specific implementation needed.

Polymorphism – Being able to refer to different derivations of a class in the same way, but getting the behavior appropriate to the derived class being referred to.

Superclass - A class from which other classes are derived. Contains the master definitions of data nad procedures that all derived classes will use (and for procedures, possibly override.)

Friday, February 10, 2006 5:14:42 PM UTC :: Filed Under ASP.NET

I recently downloaded the Microsoft Internet Explorer 7 Beta 2 and to my surprise, one of my web site designs completely falls apart in IE 7 :-(  In my quest to figure-out the problem, I figured the first thing I need to know is whether or not IE 7 is displaying the web site in “quirks-mode” or not.  The browser doesn’t display this information anywhere (that I’m aware of), but I found a quick way to display this information.  In your browser’s address bar, paste the following code:

javascript:alert(document.compatMode)

Wednesday, February 08, 2006 2:30:42 PM UTC :: Filed Under ASP.NET

The CopySourceAsHtml VS.NET plug-in certainly won’t make you a better programmer, but it might help make your blog posts prettier :-)   The utility allows you to keep the code coloring that is present in Visual Studio so you can post code snippets into HTML documents without losing the coloring.  Get the plug-in by visiting Jason Haley’s blog.  You can download the plug-in here.

Thursday, January 26, 2006 11:12:23 PM UTC :: Filed Under ASP.NET

Have you ever wanted your own MSDN action figure? Well, probably not, but in case you do, visit the new MSDN Webcast Source Force web site and get yourself a set of MSDN Lego-man-looking characters just by watching webcasts!

Monday, January 16, 2006 3:34:32 PM UTC :: Filed Under ASP.NET

Once again, Scott Guthrie posted some more highly informative ASP.NET 2.0 information; this post being the first in a series featuring typed datasets.

Many people groan at the thought of using typed datasets because ‘purists’ feel that using them generates a lot of unnecessary code (among other things which I won’t discuss here.)  While this may be true, they are very useful for creating a very quick-n-dirty data access layer with almost no need to write SQL or ADO code.  In addition, getting ‘free’ strongly typed code (intellisense = good) makes me think that typed datasets are well worth looking at!

Friday, January 06, 2006 10:13:13 PM UTC :: Filed Under ASP.NET

The W3C has introduced a MIME type for XHTML documents. This new MIME type is application/xhtml+xml. The W3C recommends that you use the application/xhtml+xml MIME type when serving XHTML documents, because XHTML pages should be interpreted in a stricter way than legacy HTML pages.

You can serve an ASP.NET page with a particular MIME type by including the ContentType attribute in a page directive. For example, including the following directive at the top of an ASP.NET page causes the page to be served as application/xhtml+xml.

<%@ ContentType="application/xhtml+xml" %>

Doing so will force you to make sure your web pages are valid XHTML files because they’ll break if your code is sloppy.

Ok, that’s great… except for the fact that Internet Explorer will now display your web site as an XML file instead of an HTML file!  There are a few work-arounds for this, but the easiest one for ASP.NET 2.0 sites seems to be this simple addition to the Global.asax file:

<script runat="server">

    Sub Application_PreSendRequestHeaders(ByVal s As Object, _
      ByVal e As EventArgs)
        If Array.IndexOf(Request.AcceptTypes, _
          "application/xhtml+xml") > -1 Then
            Response.ContentType = "application/xhtml+xml"
        End If
    End Sub

</script>

Friday, January 06, 2006 8:14:13 PM UTC :: Filed Under ASP.NET | Web Design

I’ve had a small obsession with learning about web standards recently, mostly because a world of truly standards-compliant browsers is a world where web developers don’t have to test their web sites on all the latest (and very quirky) browsers.

Along with attaining standards compliance comes meeting the needs of those with disabilities, such as those who are visually impaired or blind.  The Internet is a wonderful place full of nearly unlimited amounts of information and it would be a shame if your web site was preventing people from tapping into part of it!

So how do you make your web site standards compliant and make sure it caters to the needs of those with disabilities?   Well, this MSDN article does a great job of explaining all of this:

MSDN: Building ASP.NET 2.0 Web Sites Using Web Standards

One thing I like about the article is that even though it is from Microsoft, it doesn’t hide the fact that Internet Explorer isn’t quite up-to-snuff when it comes to meeting some of the stricter standards (like XHTML Strict).  The article also offers some work-arounds for some of the problems one will encounter with trying to make a site fully standards compliant.

In addition to the MSDN article, these two articles may also come in handy when designing more usable web sites:

As you'll read in some of these web sites, there are laws that require a web site to be accessible (Section 508) when working with government agencies.

As a site designer (in addition to being a developer), one thing I’m finding challenging about creating accessible site designs for users with disabilities is that it greatly limits what I can do with my site in terms of formatting and using scripting technologies like DHTML.   It seems to me that when designing a site for a client that has business requirement for designing an accessible site, it may be best to either create a text-only version of the web site or make sure there is a CSS style sheet that can display the web site without all the glitz.  This also means that dynamic DHTML menus have to go away in favor of more static hyperlinks and sitemaps.

Thursday, December 29, 2005 5:09:47 PM UTC :: Filed Under ASP.NET

Click here to hear the Unit Test song by Tim O’Day.  As you might expect by his last name, it’s an Irish song ;-)

Thursday, December 29, 2005 4:29:38 PM UTC :: Filed Under ASP.NET

If you’re upgrading a lot of web projects from Visual Studio .NET 2003 to Visual Studio .NET 2005, you’ll want to be sure to install this latest update to the Web Project Conversion Wizard.

Thursday, December 29, 2005 4:16:30 PM UTC :: Filed Under ASP.NET

One of the annoying features of VisualStudio.NET 2003 is that it isn’t very easy to deploy a web project to a hosted web server via FTP.  Even if you use VS.NET’s Copy Project utility, it’s pretty much an ‘all or nothing’ tool.  What happens when you only want to post a few files?  Most of use end-up using some third-party FTP tool which is annoying.

Anyway, your prayers have been answered by Bobby DeRosa who spent the time solving this FTP problem by creating the Web Deployer Add-in for Visual Studio 2003 (for C# projects.)  It integrates nicely with VS.NET and allows you file-by-file control of what you want to upload. 

Because Bobby is such a nice guy, he also made a VB.NET flavor of this tool as well :-)

Thursday, December 29, 2005 2:55:58 PM UTC :: Filed Under ASP.NET

Note to self:  Do not add a reference to the assembly System.Data.SqlClient in a VisualStudio.NET 2005 project, it is only necessary to have a reference to System.Data.  If you reference both assemblies, you get this error in VisualStudio:

'SqlConnection' is ambiguous in the namespace 'System.Data.SqlClient'.

Why does this happen? According to Kevin Yu’s response in the Google microsoft.public.dotnet.framework newsgroup:

“The System.Data.SqlClient assembly under the PublicAssemblies is used by VS.NET IDE internally. It is a party of the IDE and only the product team knows the difference between this and the one under GAC.

This System.DataSqlClient is not intended to be called from the user code. Usage of this assembly is not supported and might lead to unexpected results.

So if you need to connect to SQL Server in your code. Please reference the System.Data assembly under GAC as MSDN refers to. It includes the namespace of System.Data.SqlClient.”

Tuesday, December 27, 2005 6:10:49 PM UTC :: Filed Under ASP.NET

One of my favorite words in the English language is “free” :-)  If you’re interested in learning more about the Agile Development, you be happy to learn that the book “Essential Skills for Agile Development” is available online… for free!

Essential Skills for Agile Development

Tuesday, December 27, 2005 6:07:29 PM UTC :: Filed Under ASP.NET

In today’s programming world, it seems like any article you read that is six months old or older is no longer relevant.  However, I recently found a very interesting article written in 2003 that addresses the topic of off-shoring developer jobs… and it discusses some things that we, as developers in the good ol’ US of A, can do about it:

Achieving Reuse in ASP.NET – Part1: Barriers to Reuse by Scott Bellware

It wasn’t until recently that I jumped on the Test Driven Development (TDD) bandwagon, as the article discusses, and I wish I would’ve done it sooner.  Making my code a bit more reusable still seems like something I could use a lot of work on as well.  I spend way too much time re-inventing the programmer wheel!

Thursday, December 22, 2005 5:18:10 PM UTC :: Filed Under ASP.NET | Web Design

One of the biggest pains is testing a web application is testing the User Interface (UI).  When you’re trying to track-down a bug that occurs after clicking through 20 different links on your site and having to fill-out multiple forms, you’ll soon start pulling your hair-out but might have thought there was no other way around doing this manual testing.

For those of you who can’t afford Visual Studio Team System 2005 (which has a UI recording tool), there is still hope!  Alex Furman created an incredible application called the SW Explorer Automation Designer that can automate UI tests for you and its free!

Click here to enlarge

I just downloaded it and ran through the same scenario that is shown in the online demonstration.  I must say that I’m impressed and I wish I would’ve discovered this tool a long time ago.  Granted, it only works with Internet Explorer, but that’s ok for me as most of the applications I build target IE as the primary browser.  I highly recommended going through the demo step-by-step (keep your cursor over the ‘pause’ button!) to learn how to use the tool.

Setting-up a test takes a little bit of time, but I think it’s worth taking a few minutes up-front to save you many minutes (or perhaps hours or days!) when testing your site. If you'd like to integrate your SWE tests with your NUnit tests, TestingReflections.com has an article explaining how to do that (in C#, of course :'( )

Wednesday, December 21, 2005 9:33:16 PM UTC :: Filed Under ASP.NET | Web Design

Seems that a new HTML tag pop-ups every once in a while that I wasn’t aware of.  Today it’s the <label> tag.

So what is the label tag for? Using the label allows the user to click on the text associated with a form control instead of having to click on the radio button, check box, select box, etc.

Granted, this isn’t likely to be hugely useful to you, but I know I’ve often found it convenient to simply click on text next to a check box (or similar form field) when I’m in a hurry, hence it increases the usability of your page.

However, if an accessible web site for the visually impaired, using the label tag helps those who visit your site with a screen reader to associate a fields label with the field that it belongs to.

How do you use it?  Here is how:

<label for="radio1">This Radio Button 1 has a label associated with it.</label>

<input type="radio" value="Selected" name="Radio" id="radio1">

One thing I find convenient about the label is that I can now create a CSS style for the HTML label tag and know that all the field labels will be formatted the same. I no longer have to create a <span> or <div> tag with a special CSS class for field labels.

However, in ASP.NET, I could envision the label not working as it’s supposed to in many cases because it’s often hard to predict the name of the field controls.  For example, if I have a textbox with an ID of “txtFirstName” which is nested in a User Control, which is nested in a Page, which is nested in a Master Page, ASP.NET will rename the control and it’s ID to something like “ctl001 MyMasterPage MyPage MyUserControl txtFirstName.”

With that in-mind, the functionality of the label control might be limited in ASP.NET applications, but at least it provides a new tag to bind CSS to! :-)

Update - 01/06/2006

Those guys at Microsoft are no dummies... they made sure the ASP.NET 2.0 Framework produces standards compliant and accessible code.  To assure that your ASP.NET 2.0 form fields are properly labeled, you must use the AssociatedId property for the ASP.NET Label control in order to make the .NET Framework spew the correct HTML:

    <table>
    <tr>
        <td><asp:Label AssociatedControlID="txtFirstName"
          runat="server">First Name:</asp:Label></td>
        <td><asp:TextBox ID="txtFirstName" runat="server" /></td>
    </tr>
    <tr>
        <td><asp:Label AssociatedControlID="txtLastName"
          runat="server">Last Name:</asp:Label></td>
        <td><asp:TextBox ID="txtLastName" runat="server" /></td>
    </tr>
    </table>

Tuesday, December 20, 2005 3:24:50 PM UTC :: Filed Under ASP.NET

With the release of the final version of Visual Studio Team Systems rapidly approaching (January of 2006), many of you are probably wondering if it’s time to bail on using NUnit for your ASP.NET 2.0 projects in favor of the VSTS unit testing tools.  Well, worry no longer as Jim Newkirk has created a NUnit Add-On that converts NUnit Test Code into tests compatible with Visual Studio 2005 Team System.

The converter is a free download available on the gotdotnet site:

NUnit Add-Ons: Workspace Home

Saturday, December 17, 2005 9:48:14 PM UTC :: Filed Under ASP.NET

The following is Fritz Onion’s posting on Complex data binding expressions in ASP.NET, converted into VB.NET:

I often find when using templated data-bound controls (in either ASP.NET 1.1 or 2.0) that my expressions become rather difficult to understand because of the need to fit all of your logic into a single expression. For example, I have seen databound expressions that look something like:

<asp:TemplateField HeaderText="SomeColumn">
  <
ItemTemplate>
    <%# ((bool)Eval("foo")) ? Eval("bar") : (((bool)Eval("quux")) ? Eval("a") : Eval("b")) %>
  </ItemTemplate>
</
asp:TemplateField>

Which is even worse in 1.1 because each Eval must be replaced with DataBinder.Eval(Container.DataItem, "xx"). There are also occasions where you just can't compress all the logic you need to into a single expression. An alternative, which I find myself using quite a bit, even when developing in 2.0, is to write a single method in your code behind class to generate the desired string. Have it take an object reference (which will be the bound row) and take as many lines as you like to construct the string to be generated in the template. Here's a method that returns the same string as the overly-complex expression above:

Protected Function GenerateFooString(ByVal dataItem As ObjectAs String
    Dim 
foo As Boolean = CType(DataBinder.Eval(dataItem, "foo"),Boolean)
    
Dim quux As Boolean = CType(DataBinder.Eval(dataItem, "quux"),Boolean)
    
Dim ret As String = string.Empty
    
If foo Then
        
ret = CType(DataBinder.Eval(dataItem, "bar"),String)
    
ElseIf quux Then
        
ret = CType(DataBinder.Eval(dataItem, "a"),String)
    
Else
        
ret = CType(DataBinder.Eval(dataItem, "b"),String)
    
End If
    Return 
ret
End Function

And the simplified template now looks like:

 <asp:TemplateField HeaderText="SomeColumn">
  <
ItemTemplate>
    <%# GenerateFooString(Container.DataItem) %>
  </ItemTemplate>
</
asp:TemplateField>

Once again, this is not my code or idea; it all belongs to Fritz Onion!

Saturday, December 17, 2005 9:37:49 PM UTC :: Filed Under ASP.NET

I haven’t quite figured-out what this plugin does, but it sounds like something I should use since I’m trying to work with standards compliant CSS files in my latest web apps:

CSS Properties Window Plugin

Wednesday, December 14, 2005 2:53:37 PM UTC :: Filed Under ASP.NET

Seems that most programmers are not good designers, and most designers are not good programmers.  However, Microsoft is making it easier for programmers to not worry so much about design by providing a set of new templates for VisualStudio.NET 2005.

The interesting part is that these templates are not only pretty nice looking, some of them conform to the XHTML 1.1 Strict standard; that’s something you couldn’t even dream of doing with VisualStudio.NET 2003!

In addition to being standards compliant, these templates make use of Master Pages, Themes, and Skins, so they should serve as good references on how to properly use these new features in VS.NET 2005.

MSDN: Design Templates

Thursday, December 08, 2005 5:17:30 PM UTC :: Filed Under ASP.NET

What? You don’t have any Microsoft certifications and you feel lonely?  Not to worry, Jason Mauss has created some new Microsoft MVP awards that you can add to your web site so that you’ll fit-in better ;-)

            
  
            

Tuesday, December 06, 2005 6:48:13 PM UTC :: Filed Under ASP.NET | Web Design

I like adding help messages to web forms, but I find that these help messages can often make the page very long.  Since a user won’t like need a help message once he has read it, it’s nice to be able to hide the message.

With that in-mind, the JavaScripts below are nice samples of scripts that will display or hide content that is within a specified <DIV> tag.  They can be called from a single button or hyperlink:

function toggleDiv(divName) {
    thisDiv = document.getElementById(divName);
    if (thisDiv) {
        if (thisDiv.style.display == "none") {
            thisDiv.style.display = "block";
        }
        else {
            thisDiv.style.display = "none";
        }
    }
    else {
        alert("Error: Could not locate div with id: " + divName);
    }
}

function toggleDiv(divName) {
    var thisDiv = document.getElementById(divName);
    if (thisDiv) thisDiv.style.display = !thisDiv.offsetWidth ? "block" :"none";
    else alert("Error: Could not locate div with id: " + divName);
}

Tuesday, November 29, 2005 10:33:12 PM UTC :: Filed Under ASP.NET | VB.NET

I recently took on the project of trying to create my own Business Logic Layer (BLL) and Data Access Layer (DAL) in a personal web project so I could understand how the various layers of n-tier architecture are supposed to work.  I didn’t get very far before I realized that allowing NULL database values (System.DBNull.Value) in various fields in my database was going to give me a large headache :'(

After doing a lot of research, I didn’t come-up with too many satisfactory methods for dealing with DBNulls.  At best, it seemed like I’d have to write all sorts of methods for converting DBNulls to either a default value for each data type (I.e., define an integer to default to zero, a string defaults to String.Empty, a date defaults to DateTime.MinValue, etc.) or use the new VB.NET 2.0 Nullable Types and set each data type to Nothing.  This sounded like a lot of work and a lot of code… more code = more errors!

I read a few articles on using Generic Types in VB.NET 2.0 and it appeared to me as though they could be the answer to my prayers:  Create one generic method that can check for DBNulls for all data types.  A blog post by Saravana Kumar shows a way to accomplish this using C#. However, C# has a keyword default which doesn’t exist in VB.NET (at least not that I could find.)  This keyword apparently returns the default value for each data type, just like I wanted!

After much tinkering, here is what I came-up after trying to convert Saravana’s code to VB.NET:

Public Shared Function ConvertDBNull(Of T)(ByVal obj As Object) As T
    If (obj Is System.DBNull.Value) Then
        obj = Nothing
    End If
    Return CType(obj, T)
End Function

So far, it seems to work!  For example, with the following code:

Dim oSomeTestObject As Object = System.DBNull.Value
Dim strResult As String = ConvertDBNull(Of Integer)(oSomeTestObject)

The value of strResult is returned as a zero.  Another example:

Dim oSomeTestObject As Object = System.DBNull.Value
Dim strResult As String = ConvertDBNull(Of Date)(oSomeTestObject)

The value of strResult is returned as a “12:00:00 AM”. For most dates that I display, I always format them as MM/dd/yyyy, so a date value only exposing time won't show.

I tested this new method on my BLL, and so far it works great! w00t! If you have a better method for dealing with DBNulls in your Business Logic, let me know… I’m all ears!

Tuesday, November 29, 2005 6:24:11 PM UTC :: Filed Under ASP.NET

The December issue of MSDN Magazine has a nice listing of add-ins for Visual Studio, most of which are free:
Visual Studio Add-Ins Every Developer Should Download Now

Monday, November 28, 2005 10:37:16 PM UTC :: Filed Under ASP.NET

One thing it took me way too long to learn with Visual Studio 2003 is how to customize the default file templates.  Well, it didn’t take me long to customize the templates once I knew where they were, it was finding them that was hard. ;-) 

For example, when you add a new web form to a project, you don’t have to put-up with all the garbage tags in the HTML page header that Visual Studio auto-magically generates. You can modify the ASPX page template to show what you want so you don’t have to modify each new file.  The same can be done with class files, XML, etc.

The template customization feature of VS.NET 2005 is pretty nice and the guys and gals at MSDN have already created a lot of documentation for template customization:

MSDN2: Visual Studio Templates

Monday, November 28, 2005 9:45:14 PM UTC :: Filed Under ASP.NET

There are a couple of web sites out there that cover exactly how I feel most of the time while programming… here’s one of them: http://thedailywtf.com/

Monday, November 28, 2005 4:12:43 PM UTC :: Filed Under ASP.NET
Tuesday, November 22, 2005 9:19:57 PM UTC :: Filed Under ASP.NET

Have you ever found it annoying that any time you download some sample code you had to configure a virtual directory in IIS just to see it work, only to delete it if it wasn’t of use to you?  Well, with the .NET 2.0 Framework and a little help from Robert McLaws, you can now browse web sites from anywhere using the new built-in web server feature of ASP.NET 2.0:

"ASP.NET 2.0 Web Server Here" Shell Extension

In the above blog post, Robert had a few issues with his solution which he apparently resolved with the .msi which can be downloaded here.

The coolest part is that it even works on ASP.NET 1.1 projects! w00t!

Tuesday, November 22, 2005 9:04:04 PM UTC :: Filed Under ASP.NET

I’m going to have to make reading Scott Guthrie’s blog part of my daily ritual because nearly every post is packed with useful information!  This article shows how to run a web application on your development PC as though it was running at the top-level (or “root”) web site, even if it’s configured to run in a virtual root:

How to Run a Root “/” Site with the VS/VWD 2005 Local Web Server

Why is this cool?  If you haven’t already figured it out, here’s my lame explanation:

When you configure a web site on a Windows 2003 Server using IIS 6, each site has its own root directory because IIS 6 on a web server allows for the creation of multiple web sites.  However, on a development machine running Windows XP Pro and IIS 5, you can only have one web site defined which means all other sites must be contained in virtual root folders below the main site.   The problem that this creates is that it becomes difficult to reference file paths to static files and folders.

For example, if your site contains an “images” folder and a “templates” folder (which contains your .ASCX user controls), you will likely want to reference images from within one of your user controls.  On a web server, you could reference an image path like this:

<img src=”/images/someimage.gif” alt="My Alt Tag" />

However, that won’t work on a development PC running IIS 5 with a site defined as a virtual root.  The path would then have to be:

<img src=”/myvirtualroot/images/someimage.gif” alt="My Alt Tag" />

Starting to see the problem here?  In the second example, all your images will break when you copy your files from your development PC to the live web server.   Using the “../” method to navigate to images used to work:

<img src=”../images/someimage.gif” alt="My Alt Tag" />

However, do to naughty people trying to run scripts through the address bar in the browser, IIS often won’t allow for the “../” notation.  One solution is to use the method ResolveURL along with the “~/” prefix:

<img src="<%# Control.ResolveUrl(“~/images/someimage.gif”) %>" alt="My Alt Tag" />

But that’s just plain ugly code!   Utilizing Scott’s trick, you can reference your file paths as though you were working on a live web server without having to do any ugly work-around. Schweet!

Tuesday, November 22, 2005 7:37:43 PM UTC :: Filed Under ASP.NET | VB.NET

The .NET 2.0 Framework supports a new string method for VB that should prove to be useful:

returnValue = String.IsNullOrEmpty(value)

IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is a null reference (Nothing in Visual Basic) or its value is Empty.

 

Tuesday, November 22, 2005 6:55:28 PM UTC :: Filed Under ASP.NET

Note that if you are trying to configure Profiles in ASP.NET 2.0, there no longer is a ‘Profile’ tab in the ASP.NET Web Site Administration Tool.  This tab appears in the Beta 1 and found it’s way into a lot of documentation and web casts, but was apparently removed in Beta 2 and the final release.  As a result, if you want to configure custom Profile Properties or use a custom Profile Provider, you must do so manually in the web.config file.

Monday, November 21, 2005 10:21:18 PM UTC :: Filed Under ASP.NET | SQL | VB.NET

When writing SQL statements, it's a good practice to always use "AS" after calling each field. This will allow for column name changes that won't break your code.  For example, the following is a simple SELECT statement:

SELECT Id AS UserId, FirstName AS FirstName, LastName AS LastName FROM Users

If some of the column names change, such as the FirstName and LastName columns, my code won't break:

SELECT Id AS UserId, FirstName AS NameFirst, NameLast AS LastName FROM Users

Thanks to Jelle Druyts for this useful tip.

Friday, November 11, 2005 9:12:22 PM UTC :: Filed Under ASP.NET | VB.NET

Who says that developers are boring and weird?  Well, they are weird, but sometimes they can be fun:

VSTSRap_small1.jpg

http://www.microsoft.com/korea/events/ready2005/vs_song.asp

I’m not sure if I think the video is funny because of the content or because of the Korean language that I don’t understand!

The lyrics are very good too when translated into English... they seem to relate to my job pretty well!

Wednesday, November 09, 2005 12:28:13 AM UTC :: Filed Under ASP.NET

In a quest to make my client web site’s XHTML compliant yet still highly configurable by my client, I went on a search to replace the free RichTextBox editor I was using in favor of one that supported XHTML.   Lucky for me, I found one that did that and much more: FCKeditor.



FCKeditor is on open-source rich textbox editor that works on nearly every major platform.  To use it in an ASP.NET web page, as a user control, there is an additional download which provides the necessary .dll.

Configuring the textbox was relatively easy.  The only issue I had was trying to get the file browser to work. The file browser is a very cool tool that allows the user to browser to a specific folder on the hard drive and upload or link to files and images to put into the content window.  This saves the end user from having direct access to the web server to upload files and then having to guess at the URL to those files to create links to them.

The issue I had related to the path of the folder where users can store his files.  That path is different on my workstation than it is on the live web server because my workstation is running Windows XP and each web site is in a virtual directory where as the live server is a Windows 2003 Server and each web site is in its own IIS site. 

For my workstation, I defined the file upload folder as:

<appSettings file="user.config">
 <add key="FCKeditor:UserFilesPath" value="/MYVIRTUALSITE/userfiles" />
</appSettings>

… where as I had to define the path as follows on the live server:

<appSettings file="user.config">
 <add key="FCKeditor:UserFilesPath" value="/userfiles" />
</appSettings>

Note that the path must start with a forward slash “/” and not a “~/”.

Tuesday, November 08, 2005 8:34:41 PM UTC :: Filed Under ASP.NET

Free ASP.NET hosting for Christians… Does it get any better than this?

http://www.christianasp.net/Hosting.aspx

Tuesday, November 08, 2005 5:40:00 PM UTC :: Filed Under ASP.NET

Although this type of toolbar has been around for a long time for the FireFox browser, the IE Team at Microsoft has finally gotten around to creating a Developer Toolbar add-in for IE.

Wednesday, November 02, 2005 8:53:15 PM UTC :: Filed Under ASP.NET

Sample comparing two dates:

Dim t1 As String = DateTime.Parse("3:30 PM").ToString("t")
Dim t2 As String = DateTime.Now.ToString("t")
If DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) < 0 Then 
     Response.Write(t1.ToString() & " is < than " & t2.ToString())
Else 
     Response.Write(t1.ToString() & " is > than " & t2.ToString())
End If

Sample comparing two moments in time:

Dim adate As DateTime = DateTime.Parse("06/24/2003") 
Dim bdate As DateTime = DateTime.Parse("06/28/2003")
Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks)
Response.Write(ts.TotalDays & "<br>")
Response.Write(ts.TotalHours & ":" & ts.TotalMinutes & _
        ":" & ts.TotalSeconds & ":" & ts.TotalMilliseconds) 
Sunday, October 30, 2005 5:01:10 AM UTC :: Filed Under ASP.NET

When using a GridView in ASP.NET 2.0, note that you must set HtmlEncode = False in addition to setting the DataFormatString or else the formatting will not work:

image0011.png

Sunday, October 30, 2005 3:15:06 AM UTC :: Filed Under ASP.NET

Because of the cost and portability, I had a tendency to use Microsoft Access databases as the back-end for many of my web sites.  Microsoft recently released Visual Studio 2005 which includes SQL Express 2005.  SQL Express is designed to be used in-place of Access for low volume web sites.

With this in-mind, my first thought was, “How to I upsize my Access 2000 databases to SQL Express 2005?”  It’s surprisingly easy.

How to Upsize an Access 2000 Database to an SQL Express 2005 Database

1. Open the Access database you wish to up-size.
 
2. Select Tools > Database Utilities > Upsizing Wizard



3. Select Create new database and then Next >
 
4. This is probably the hardest part.  The instance of your SQL Express database won’t show-up in the database dropdown list.   For the name of your SQL Server, enter MACHINENAME\SQLExpress or .\SQLExpress.  The former worked for me:



5. Make sure you name the database, click Next >, and the rest is the same as it’s always been.

If you find that Access can’t connect to the SQL Express database, this FAQ might be helpful:

FAQ: How to connect to SQL Express from "downlevel clients"(Access 2003, VS 2003, VB 6, etc(basically anything that is not using .Net 2.0 or the new SQL Native Client))

You’ll also likely want to bookmark the Microsoft SQL Express Blog to stay informed.

Friday, October 28, 2005 7:49:44 PM UTC :: Filed Under ASP.NET

I recently spent a considerable amount of time converting a client site from not following any particular standard to using the XHTML 1.0 Transitional standard.  This was a difficult task since the site was created with VisualStudio.NET 2003 which doesn’t care much about standards!  As a result, I spent most of my time designing pages in Macromedia Dreamweaver MX and doing the code in VS.NET (Can you say, “pain-in-the-butt”?)

In converting this site to XHTML, I learned a lot about CSS and the benefits of separating HTML from styles… so much that I have no real desire to go back to the old sloppy way of coding.
With the release of VisualStudio.NET 2005, one of the great features of this new tool is that it creates XHTML 1.0 Transitional code by default!  This doesn’t necessarily mean that I can through Dreamweaver out the window, but at least I can open my HTML and ASPX pages up in VS.NET and know it isn’t going to re-write and mangle my code.

The following article from the Microsoft ASP.NET Developer Center is very helpful in explaining the new features of VS.NET 2005 in regards to web standards:

Building ASP.NET 2.0 Web Sites Using Web Standards

If XHTML Transitional isn't good enough and XHTML Strinct is preferred... no problem!  Add the following in your project's web.config file:

Note that in addition to changing the runtime behavior to be strict, you can also then change the validation drop-down in the VS toolbar to validate html/javascript against XHTML strict as well.
Friday, October 28, 2005 7:35:34 PM UTC :: Filed Under ASP.NET

The more articles I read about VisualStudio.NET 2005, the more excited I get!  This article from Scott Guthrie explains how to use the new Custom Item Template feature in VS.NET 2005 which will help eliminate the need to waste time “setting-up” a newly created page ASPX page:

Defining Custom Item Templates in Web Projects with VS 2005

A helpful MSDN article relating to the templates:

MSDN: Visual Studio Template Reference

Friday, October 28, 2005 6:56:15 PM UTC :: Filed Under ASP.NET
From Scott Guthrie's blog:Basically, if you place a file with this name in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.  ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the app offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

This provides a convenient way to take down your application while you are making big changes or copying in lots of new page functionality (and you want to avoid the annoying problem of people hitting and activating your site in the middle of a content update).  It can also be a useful way to immediately unlock and unload a SQL Express or Access database whose .mdf or .mdb data files are residing in the /app data directory.

Once you remove the app offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and life will continue along as normal.

Friday, October 28, 2005 6:03:34 PM UTC :: Filed Under ASP.NET

I’m not sure if it’s a sign of getting old or just my personality type, but I like things to be organized… and that includes the files in my web projects.  Lucky for me, ASP.NET Grand-Pubba Scott Guthrie has written a nice article demonstrating ways to clean-up and organize your web projects in VisualStudio.NET 2005:

Some Techniques for Better Managing Files in Visual Studio 2005 Web Projects

Thursday, August 11, 2005 2:29:30 PM UTC :: Filed Under ASP.NET

I see Microsoft isn’t always devoted to creating serious business apps… some times they like to play: http://www.escapeyesterworld.com/

This site is for marketing Visual Studio 2005 and SQL Server 2005 and features old movie clips and the like… pretty funny!

Wednesday, June 22, 2005 6:12:47 PM UTC :: Filed Under ASP.NET | VB.NET

I’ve been told time and time again that Microsoft’s Visual Source Safe 6.0 is not a very good application to use for managing project files, but it’s all I have and it has been working pretty well… until today.   One of my project folders apparently got corrupt; I couldn’t open the folder, delete it, rename it… nuttin’.

After trying a gazillion stupid things just short of creating a whole new VSS database and starting over, I finally discovered the ANALYZE command line tool.  Sure enough, that’s all I needed to fix the corrupted database.  The analyze tool is located in the C:\Program Files\Microsoft Visual Studio\VSS\win32 folder.

Running the following command was all I had to do to fix the problematic folder:

C:\Program Files\Microsoft Visual Studio\VSS\win32>ANALYZE –F \\server\vss\dbname\data

Here is a list of a few other VSS Utilities. Since I now know how to repair a corrupt VSS database, I’m going to continue to ignore everyone’s advice and keep using VSS in the hopes that the 2005 version will be a cure-all (yah right!) J

Wednesday, May 04, 2005 4:21:07 PM UTC :: Filed Under ASP.NET | Web Design

FireFox is nice and all, but I work for a ‘Microsoft Shop’, so it doesn’t do me much good to browse the ‘Net on a Mozilla-based browser.  Yet, we all know that Internet Explorer is nearly become a dinosaur.

Well, there’s a bit of hope (and it’s free!)  I recently downloaded the Avant Browser which is basically a wrapper for Internet Explorer.  Some of the nifty features include:

·         Flash Animation Filter (Yippee! Block those annoying Flash ads.)

·         Built-in Pop-up Blocker

·         Multi-Window Tabbed Browsing

·         Real Full Screen Mode and Alternative Full Desktop mode

·         Built-in Yahoo/Google Search Engine

·         Full IE Compatibility

·         Records Cleaner

·         Safe Recovery

·         Skins

There certainly are other browsers like the Avant Browser, but I found that this one works best for my needs.

Saturday, April 30, 2005 10:49:00 PM UTC :: Filed Under ASP.NET | VB.NET

In case you didn’t already know, you can run SQL scripts right within Visual Studio.NET which is much nicer than having to fire-up Query Analyzer all of the time.  This tutorial assumes you already know what a Database project is in Visual Studio.

Instructions:

The first thing you must do is create a Database Reference in your database project. In the Visual Studio Solution Explorer, open the database project and right click on the Database References folder.  Select New Database Reference… and the following window should pop-up:

If the database you’d like to connect to is not listed, click Add New Reference… and you will be prompted to setup a connection to the database of your choice.  Items are added to this list via the Server Explorer

You can add several database references to a project.  I would suggest making a reference to your local, development SQL database and one to the live web server’s SQL database.

Once the database you’d like to connect to is listed in the Add Database Reference list, select it and click OK.  You notice that this reference is now listed under the Database Reference section in the Solution Explorer:

If you have several databases listed, you can right-click on the one you want as the default (usually your local SQL database) and select Set as Project Default.

To run a SQL Script against a selected database, right-click one of the SQL scripts stored in the database project and select Run On…  You’ll be prompted with a window like this:

Select the database you’d like to run the script against, click OK, and the script runs!  Hopefully you’ll find this a useful and time-saving tip J

Saturday, April 30, 2005 10:22:56 PM UTC :: Filed Under ASP.NET

Don’t you hate it when you complain about a program not being able to do something, then you realize the program could do exactly what you wanted but you were too dumb to know how to use it correctly?   Well, for me, this is the case with Visual Studio.NET’s Copy Project utility.   I’ve tried it before in the past, but never got it to work right so I just manually copied projects from my development machine to the live web server.  Duh.

When configured correctly, the Copy Project utility copies whatever you want to the live web server, the most useful feature being the ability to copy over only the essential files required for running the app.

Instructions:

In the Visual Studio Solution Explorer, select the project that you would like to copy project, then browse to Project > Copy Project…

You should be prompted with a window that looks like this:

For the Destination project folder, it should be the full URL path to your site’s virtual directly.  That may be http://localhost/someproject or a fully qualified domain name like  http://my.domain.com/... It all depends if you’re copying to a virtual directory on your dev machine or a web site on a live web server.  Obviously you should insert the path to the file-share on your machine that connects to the live web server.  Apparently a mapped drive or UNC path will work.

Select Only files needed to run this application from the Copy section.   This prevents .vb, .resx, and other non-essential files from being copied to the web server.

You may be prompted with a warning stating that the Virtual directory could not be created… just click OK.  You will then be prompted with this:

Check Apply to all items and let VS.NET copy all the files to the live web server.

Make sure the web.config file is correctly configured for use on the web server.  The Copy Project utility will not copy a user.config file over (assuming you excluded it from your VS.NET project), so use the user.config on your local machine and leave the web.config configured for the live server settings. The Copy Project seems to remember the last settings you used, so if you’re constantly working on the same program, you won’t have to keep reconfiguring the Copy Project tool.

Tuesday, April 26, 2005 7:06:24 PM UTC :: Filed Under ASP.NET

The Problem:

You just built a user control (.ASCX) that is a header template for your web site.  The user control contains some ‘root sensitive’ information, like the path to an image, the path to a linked JavaScript file, the path to a linked CSS file, etc.   You’d like to use relative file paths, but you already know that you can’t prefix the file path with “/” because your developing the site in a Virtual Directory on your Windows XP machine.  Prefixing a relative URL with “/” will take you to the root of the web site, not the root of the Virtual Directory.

So, what do you do to make sure the file paths always work no matter where your user control is placed in the directory structure?

One option is to append <%= Request.ApplicationPath %> before all of your URLs to automatically insert the name of the Virtual Directory into the path.  (This is used in the Microsoft iBuySpy Portal solution.)  For example, if you wanted to link to your Style Sheet in the header, the HTML would look like this:

<link href="<%= Request.ApplicationPath %>/CSS/Screen.css"
type="text/css" rel="stylesheet">

However, once you move your site from your development machine to a live web server where your site will most likely be located in the root directory, the above code will fail.  Well, it will work, but the path to the Style Sheet will end-up being:

//CSS/Screen.css

Note the double forward slashes.  Request.Application path returns “/” when ever the site is at the root directory.  Some browsers will choke on a URL with two forward slashes in it.

Ok, so that was lame.   Are we just screwed?

The Solution: (Well, the best one I’ve found so far)

When inserting images into a User Control, it’s probably easiest to just use the ASP.NET Image Control.  If you prefix the ImageURL in an Image Control with “~/”, the Image Control will automatically find the root directory for you.

That’s all fine-and-dandy, but what if you’re not working with an image?  Well, after much research, I found-out the secret method being used by the image control is ResolveURL().  With ResolveURL(), you can insert the path to any file and get the root directory.  For example, let’s go back to our Style Sheet example from above.  If you replace the Request.ApplicationPath with ResolveURL, your problem is solved:

<link href="<%=ResolveURL("~/CSS/Screen.css") %>"
type="text/css" rel="stylesheet">

Note that you’ll still need to prefix the URL with “~/”.   Granted, this isn’t the prettiest solution, and image won’t show-up in design time (I hate that), but at least it works!

Tuesday, April 05, 2005 11:46:49 PM UTC :: Filed Under ASP.NET | VB.NET

It seems easier than it is… looping through an array of items (collection) and removing items you don’t want.  However, when you remove an item from a collection while looping through it, the size of the collection changes and the loop may fail… depending on how you are looping.

The correct way to loop through a collection is to essentially loop through it backwards, starting with the item with the maximum ID and working down to zero:

    1  For i As Integer = MyList.Count - 1 To 0 Step -1
    2      If MyList.Items(i).Value <> SomeValue Then
    3          MyList.Remove(MyList(i))
    4      End If
    5  Next
Thursday, March 24, 2005 4:38:14 AM UTC :: Filed Under ASP.NET

Have you ever noticed that some pages on Microsoft's web site have an extension of .ASHX (among other things)?

ASHX files are WebHandlers that derive from IHttpHandler. Their advantages are mainly that you can gain access to the HttpContext without all the overhead of loading the Page class if you don't need the UI.

These classes have only two required methods - ProcessRequest, which accepts an HttpContext parameter, and the boolean IsReusable. In short, ASHX files let you create an HTTP endpoint that can return any content type that you want. And, with ASHX, there is no requirement for registration in web.config or machine.config - you just drop them into your project and they are usable "out of the box".

One thing I've noticed is that the C# guys seem to have all sorts of articles on using ASHX files, but the VB.NET guys do not.   So, after a little bit of research, I figured-out how to write an ASHX page in VB.NET.  The code sample below only has the small function of logging a user out of a web site... Maybe it's not the best example, but its all I've got!

    1 <%@ WebHandler Language="VB" Class="MyNamespace.Web.Logout" %>

    2  

    3 Imports System.Web

    4 Imports System.Web.Security

    5  

    6 Namespace MyNamespace.Web

    7     Public Class Logout

    8         Implements IHttpHandler

    9         Public Sub ProcessRequest(ByVal context As HttpContext) _

   10    Implements IHttpHandler.ProcessRequest

   11             FormsAuthentication.SignOut()

   12             Context.Response.Redirect("default.aspx")

   13         End Sub

   14  

   15         Public ReadOnly Property IsReusable() As Boolean _

   16          Implements IHttpHandler.IsReusable

   17             Get

   18                 Return False

   19             End Get

   20         End Property

   21     End Class

   22 End Namespace

Using an ASHX page is just the tip-of-the-iceberg when it comes to using HTTP Handlers.  Scott Mitchell's article, “Serving Dynamic Content with HTTP Handlers“ shows how HTTP Handlers can be used to format code on web pages, prevent people from “hot-linking” to images on your web site, and re-writing URLs to more user-friendly names.  

Using ASHX and Code-Behind

The method described above shows how to use an ASHX as a single file. However, VisualStudio.NET doesn't recognized the file type, hence no Intellisense support :( I don't know about you, but I can't live without Intellisense, and there is hope! An ASHX file can have a code-behind class file just like an ASPX page. The actual ASHX page should only have a line like the following in it:

<%@ WebHandler Language="VB" Codebehind="Logout.ashx.vb" 
Class="GMR.eFelix.Web.Logout" %>

The ASHX code-behind page would be a normal class file.

Tuesday, February 15, 2005 2:48:04 PM UTC :: Filed Under ASP.NET | VB.NET

Admit it, you do it to.  You can’t remember the .NET way to do something, so you give-in and put Imports Microsoft.VisualBasic at the top of your .vb file.  It’s time to stop the madness! Where there is help, there is hope.

As of recently, a co-worker explained to me the virtues of not using the old-school VB namespace in favor of learning the newer VB.NET way of doing things.  One of the benefits is that VB.NET code is typically optimized to run faster… and we all love speed, don’t we?    There were two places in particular that I kept resorting to the old VB way: date manipulation and formatting.

For example, here is the old VB way to add 7 days to the current date:

DateAdd(DateInterval.Day, 7, Date.Now)

And here is the VB.NET way:

Date.Now.AddDays(7)

That’s not so bad, is it? Now let’s look at formatting.  Sure, there are quite a few ways to do the same thing, but here’s an example.   If you want to format a date type variable in VB:

Format(Date.Now.ToString, "MM/dd/yyyy")

… or …

FormatDateTime(Date.Now, DateFormat.ShortDate)

And in VB.NET:

Date.Now.ToString("MM/dd/yyyy")

Actually, the VB.NET way seems easier! I wish I would’ve explored the VB.NET method sooner.

Here's some more handy conversions:

To subtract to dates:

Dim dblDateDiff As Double = datEndDate.Subtract(datStartDate).Days

So far, I’ve only come across one VB function (but I’m sure there are more) that I haven’t been able to find a VB.NET replacement for: vbTab.  I found the replacement for vbCrLf is Environment.NewLine (one of the new VB.NET classes that is actually less convenient than its VB counterpart), but I have yet to find a way to put a simple tab space into a string.  Not a huge problem, but odd in my opinion since that means I can’t completely lay the Visual Basic namespace to rest!

To help yourself cure your addiction to Visual Basic (the old-school kind), set the filter in the Microsoft Visual Studio.NET 2003 Documentation library to ‘.NET Framework’ instead of ‘Visual Basic’.  I was under the impression that the ‘Visual Basic’ filter meant VB.NET, but it does not.

Wednesday, January 19, 2005 6:45:03 PM UTC :: Filed Under ASP.NET | VB.NET

Microsoft Certified Application DeveloperYippee!  After studying for the 70-310 exam (XML Web Services and Server Components using VB.NET) for months, I took it this morning for the first time and passed!  

This is the third Microsoft exam I've taken, so that bumps me up to the MCAD.NET status.   To me, the exam was really tough... the toughest so far.  I've taken the 70-229 exam (SQL Server) and 70-305 exam (VB.NET Web Apps) previously and although they were challenging, I had more experience to back my studying for those two tests.   As of yet, I've only used web services minimally and I've never had to create or use a service component.  Despite my lack of current experience with XML web services and server controls, I opted to take the 70-310 because I feel that applications such as Microsoft BizTalk Server will be more and more important in the future as the need to exchange data between desperate systems becomes crucial to being competitive in the business world.

To get my MSCD.NET certification, my next exam will be the 70-300 exam (Analyzing Requirements and Defining Solution Architectures), followed by the 70-306 (Windows-Based Apps w/ VB.NET).

Navigation
On this page....
Using Conditional Compilation for UI Testing
Working with XML in the .NET 2.0 Framework
101 Samples for Visual Studio 2005
Submitting a Form With the Enter Key in ASP.NET 2.0
Visual Studio .NET 2005 Style Builder Bug
Stand-Alone Internet Explorer for Backwards Compatibility
Customizing Visual Studio .NET 2003 VB Templates
Visual Studio 2005 Unit Testing Code Snippets in C#
Object-Oriented Programming Terminology
Displaying Browser Compatibility Mode
CopySourceAsHtml for VS.NET 2005
MSDN Action Figures
Typed Datasets End-to-End Examples
Content Negotiation for XHTML MIME Types in ASP.NET 2.0
Web Standards and ADA Compliance
The Unit Test Song
Update to Visual Studio .NET 2005 Web Project Conversion Wizard
Free FTP Deployment Tool for VisualStudio.NET 2003
Do Not Reference System.Data.SqlClient in VS.NET 2005
Online Book: Essential Skills for Agile Development
How to Save Your Programmer Hide
Testing Your Web UI with SW Explorer
The HTML Label Tag
NUnit to Visual Studio Team Systems Test Converter
Complex Data Binding Expressions
VS.NET 2005 CSS Properties Window Plugin
Web Site Templates for the Graphically Challenged
Blog 'Flair'
Simple Toggle Layer Script
Handling DbNulls in a Business Logic Layer with Generics
Top 10 Must-Have Add-Ins for Visual Studio.NET
Visual Studio 2005 Templates
The Daily WTF?
Dilbert Does Agile Development
Launch a Web Server from Anywhere!
Running a Web Site in the Web Root
New Method for Checking Null or Empty Strings
Missing Profiles Tab in ASP.NET 2.0 Web Admin Tool
Abstraction in SQL Queries
Visual Studio Team Systems Rap
FCKeditor Rich Textbox Editor for ASP.NET
Christian ASP.NET Web Hosting
Microsoft Internet Explorer Developer Toolbar
Comparing Dates and Time
DataFormatString in GridView Does Not Honor Formatting
Upsizing an Access 2000 Database to SQL Express 2005
Building ASP.NET 2.0 Web Sites Using Web Standards
Defining Custom Item Templates in Web Projects with VS 2005
Taking an ASP.NET 2.0 Web Site Offline With App_Offline.htm
Managing Files in Visual Studio 2005 Web Projects
Escape from Yesterworld
Fixing a Corrupt Visual Source Safe (VSS) Database
Internet Explorer... the way it should be!
Running a SQL Script in VS.NET
Copying a Web Project
Finding the Root Directory in a User Controls
Removing Items from a Collection
The Mystery Behind the ASHX File
Weaning Myself Off the Visual Basic Namespace
I'm Now a MCAD.NET Geek!
Search
Archives
<July 2009>
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678
Categories
Contact me
Send mail to the author(s) Contact Todd M. Taylor