Posts

Showing posts from 2008

Easy TraceLogging In C#

The .NET Framework includes some convenient ways for tracing and debugging. In this post, I'll discuss how to easily add tracing functionality to your apps to output data to a text file.

First, define a trace switch in your App.config file. This should be placed in the system.diagnostics node, and the point of the switch is to specify the level at which to output data with the switch. Here's an example:

<system.diagnostics>
  <!--
  TRACE SWITCH VALUES
  0 = Off
  1 = Error
  2 = Warning
  3 = Info
  4 = Verbose
  -->
  <switches>
    <add name="MainTraceSwitch" value="4"/>
  </switches>
</system.diagnostics>

There are five possible values:

0 = Off
1 = Error
2 = Warning
3 = Info
4 = Verbose

So, if you set the value of your switch to 1, you're telling it that you only want to trace on errors. If you set it to 4, you're telling it to trace everything. Basically, you'll check this value in your code before you write any output to yo…

How to Update an UpdatePanel Using JavaScript from an IFrame in ASP.NET

I recently had to make some additions to a website I was working on which involved the addition of an AJAX UpdatePanel which would contain a GridView. The GridView would contain rows with information related to submissions we received by the user. A timer would ensure that the GridView would be updated in a timely fashion and reflect any updates in our database, but we also wanted to instantaneously update the GridView as soon as a new submission was received. Updating an UpdatePanel from JavaScript wasn't a problem, but the source of new submissions to the site was located within an IFRAME hosted on the page, not on the page itself. How could I update the UpdatePanel on the main page when the page inside the IFRAME was submitted?

Turns out, it's no big deal. All you need to do is add code to the onload event of the IFRAME. This code will call the __doPostBack() JavaScript function that ASP.NET renders when you use the AJAX components. This function takes two parameters:…

Troubleshooting the "ORA-01036: illegal variable name/number" Error When Calling an Oracle Stored Procedure from .NET

Yesterday I had written some code in C# to call a stored procedure in an Oracle database, and when I began testing this code today, I was surprised to get the following error whenever the code would attempt to execute the OracleCommand:

ORA-01036: illegal variable name/number

I was scratching my head. Why wasn't this working? I've done this before!

From previous experience, I knew that the names of the procedure parameters must match exactly when you add them to the OracleCommand object. In other words, if your stored procedure is expecting two parameters, named email and phonenumber, your code should look something like this:

cmd.Parameters.Add("email", OracleType.VarChar);
cmd.Parameters.Add("phonenumber", OracleType.VarChar);
cmd.Parameters["email"].Value = psEmail;
cmd.Parameters["phonenumber"].Value = psPhone;

I checked the parameter names and I was already using the correct ones. What else was I missing? Then it dawned on me: when I i…

Why The MaxLength Property Isn't Working For Your ASP.NET TextBox

So, you've written a web page in ASP.NET, placed an asp:TextBox control on the page, and set it's MaxLength property -- but when you run the site and go to that page, you find that you can type in as much text as you want. What's going on here?

The answer: you set the TextMode property to "MultiLine".

Here's what's happening: when ASP.NET renders a page to the browser, it converts server-side controls to their HTML equivalents. In the case of an asp:TextBox control with the TextMode property set to "MultiLine", the control is rendered not as an &ltinput> control, but rather a <textarea> control. And the HTML specification for the &ltltextarea> control does not include a maxlength property.

So it all makes sense, though it would be nice if the compiler would catch this and generate an error -- otherwise, this could sneak by unnoticed and cause problems with your site later.

When AJAX and Forms Authentication Don't Play Nice

I've been doing some work with AJAX in ASP.NET lately, and one of the things I've run into is the "'Sys' is undefined" error. Originally, I was getting this error in my server-side code. You can view my solution in this post.

However, once that was resolved, I started getting the same error (or, sometimes, the slightly different "Sys is not defined" -- I think I got this one in FireFox) in my client-side code. The error was occuring on the login page of the site, and the site uses Forms Authentication. It was also intermittent -- everything would be working fine, but then after accessing the page a few times I'd get the error. A quick fix I discovered was to change the authorization info in the web.config file to allow all users, run the app in development mode, then close the browser and change the web.config file back to only allow authenticated users. This would stave off the error for a little while, but it would always return.

I finally…

Using Nullable Value Types in .NET 2.0 and Higher

In .NET, there are two types of variables: value types and reference types. Values types are generally allocated on a thread's stack, whereas reference types are allocated from the managed heap, and have values which are the addresses of the memory location where the object resides.

The default value of a reference type variable is null, but a value type can't be null -- it's default value will be a value that correspond's to the variable's type (for example, the default value of an int is zero). But what if you don't want a default value for a value type? In .NET 1.x, you're out of luck, but in .NET 2.0 and higher, you can use a nullable value type, made possible through the magic of generics.

To create a nullable value-type variable, use the System.NUllable<T> generic type definition, where T is the type of variable you want to instantiate. For example, the following line creates a nullable integer type and assigns it a null value:

System.Nullable&…

ASP.NET ClientID Weirdness

I recently ran across something "funny" in ASP.NET. Not "ha ha" funny, but "hmm" funny.

I had a page wherein I wanted to hide some of my server-side controls, but add an HTML button and a JavaScript function to make them visible when the button was clicked. Sounds simple enough, right? Of course, to access those server-side controls from JavaScript, I'd need their ClientIDs, which I embedded into my client-side script using server-side scripting tags (<% and %>). This worked like a charm -- when viewing the page source from my browser, the server-side tags had indeed been replaced with the appropriate ClientIDs. However, any attempt to access these controls using JavaScript's getElementById() function proved fruitless -- the function returned null for these controls.

I turned on page tracing (using the Trace="true" option in the Page declaration) and verified these controls existed -- however, here's the funny part, and the …

How to Call Web Service Methods Asynchronously From an ASP.NET Page Using the Event-Driven Method in ASP.NET 2.0 and Higher

If you wanted to call a web service method asynchronously from an ASP.NET page in ASP.NET 1.x, you had two options: you could either use thread-blocking, or a callback method. With thread-blocking, you had to be mindful of the affect on other threads, and if you were using a callback method, you had to take steps to make sure that the page load didn't complete before the callback method was executed. In ASP.NET 2.0 and above, however, you have another option, which uses an event to signal that the asynchronous call has completed. It's easy, and even better, the page load won't complete until the event occurs. Here's how to use this convenient functionality.

First, add the Async attribute to the Page directive that will be making the web service call, and set it's value to true, as shown below. This will allow the page to process asynchronously.

<%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="Default.asp…

Troubleshooting the "'Sys' is Undefined" Error When Using AJAX Extensions for ASP.NET

If you've put together some ASP.NET code that uses some of the AJAX extensions, but the code doesn't work and you get a client script error that states "'Sys' is undefined", you're not alone. I've experienced this error myself, and none of the stuff I found on the web concerning the error helped me out any. But I was able to resolve the problem, and here's how: I added the following lines to the httpHandlers section of my web.config file.

<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKey…

How to Use LINQ to Query a Collection of Objects in .NET 3.5

One of the cool new features in .NET 3.5 is LINQ, which stands for Language Integrated Query. It allows you to use a syntax similar to SQL to query datasources, XML, and objects. In this posting, we will use a subset of LINQ called LINQ to Objects to query a collection of objects.

Let's start with the class of object we'll be querying. For this example, we'll use a very simple class called Spaceship. Spaceship has two properties: Name, which is the name of the ship, and CrewCount, which is the number of crew members it has. It also overrides the ToString() method to return a string which gives the ship's name and crew count. Here's what the class looks like:

(Shameless plug: the code samples in this post were formatted for HTML with my HTML Encoder program, which you can download here)

/// <summary>
/// A class representing a spaceship
/// </summary>
class Spaceship
{
    private int miCrewCount;
    private string msName;

    /// <summary>
    /// The…

How to Get ASP.NET Apps To Run Under IIS7 in Windows Vista

Image
If you're trying to run an ASP.NET app under IIS7 in Windows Vista, you may receive a page informing you that "HTTP Error 404.3 - Not Found" has occurred. If so, here's what you have to do to correct the situation.

1. Click on what used to be the START button (the round button in the lower left hand corner of the screen with the Windows flag in it) and go to Control Panel.

2. If you are using the deafult view (the "Control Panel Home" text in the left pane will be highlighted), click on the Programs link. If you're using the classic view, double-click on Programs and Features.

3. Click on the Turn Windows Features On or Off link.

4. A security prompt will appear. Click Continue.

5. The Windows Features dialog will appear. Go to Internet Information Services->World Wide Web Services->Application Development Features and select ASP.NET. When you do, three other options will automatically be selected as well: .NET Extensibility, ISAPI Extensions an…

Extension Methods in C# 3.0

Image
The latest incarnations of the .NET languages include a slew of new features, and extension methods in C# is just one of them. Extension methods allow you to extend a class without subclassing it. You might be asking yourself "Why would I want to do that? Why not just subclass?" Well, what if the class you want to subclass is sealed, preventing you from subclassing it? Extension methods allow you to extend even sealed classes.

Let's say you have a class called Dog. Dog has all of the properties and methods of a real dog, including a Bark() method. Because of the strained relationship in the neighborhood between cats and dogs, you want your dogs to be able to meow to help further the cause of cat/dog co-existence. There's just one problem: the Dog class is sealed and can't be subclassed. The answer lies with extension methods.

First, create a static class. Extension methods must be part of a static class. Second, create a static member of the static cla…