Sergio and the sigil

Wrong .Net Version being loaded

Posted by Sergio on 2008-04-23

At work one application has this intermittend problem that started when the developer started to use telerik's r.a.d. web controls. Once in a while, for some (until today) unexplained reasons, the telerik controls would start throwing this error:

This control is complied for ASP.NET 1.x. 
Please use the ASP.NET 2.0 native version: RadTabStrip.Net2.dll 

For reasons that are not relevant for this post, the application runs under ASP.NET 1.1, not 2.0. What the error message reveals is that sometimes .Net v2.0 was being loaded first in that appDomain. Resetting the app and hitting /default.aspx would be enough to make that error go away. Until it happened again a few days after that.

The application developers and the webmaster spent quite a bit of time checking IIS settings, .Net settings, other apps in the same appPool. Everything seemed correct.

Today I joined the effort to get rid of that problem and as soon as I saw some .asp files mixed with the .aspx ones it struck me. "We don't happen to have VB6 code doing interop with .Net code, do you?". That's right, we did. There are valid reasons for this but again it doesn't matter here.

I immediately brought up Scott Hanselman's two posts where he describes a similar situation. Different symptom, but similar enough to help us.

Basically, if the very first page to be hit in the application is an .asp file that does interop with .Net, it will load the .Net runtime and the default behavior is to load the newest version possible, which is version 2.0 in our case. Once loaded, that version stays throughout the lifespan of the appDomain, leaving Telerik's code flipping.

There are a few possible solutions, which are discussed in Scott's posts and comments. In our case it boiled down to the following alternatives:

  1. Update the application to .Net 2.0 or 3.5, migrate the telerik assemblies, and get rid of the ASP/VB6 code: This is the ideal scenario. It is possible, but a little bit too time consuming in our case because of the amount of VB6 stuff there (old app, important app.) But if we could afford the time, that would be the best route to go.

  2. Update the application to .Net 2.0 or 3.5 and migrate the telerik assemblies: The next best thing considering the VB6 problem mentioned above.

  3. Just get rid of the ASP/VB6 code: This could work too. But it seems like too much work to keep supporting .Net 1.x.

  4. Try the ISAPI filter suggested by Scott here: Looks like a quick and effective solution. I would be willing to try it out. Unfortunately we have no C++ expertise in the house and the developer felt a little uncomfortable deploying this solution and creating one more dirty little secret in this already convoluted application.

  5. Bootstrap the classic ASP engine to start ASP.NET the right way: The idea here is to add a global.asa file to the application and use the Application_Start event to call a dummy ASP.NET url. The trick is to invoke some /dummy.aspx file via HTTP, like shown in this article.

They are leaning toward #5 (path of least resistance, I know) but the mid-term solution will be #2 followed by #1 (schedules and budget permitting.)

Anyway, I just wanted to share this in case someone is also tasked with maintaining their own version of the worst application in the world. Thanks Hanselman for making me look good once again.

Update: We chose to go with #5 until we can afford to do #1. The solution was to add the following to the global.asa file (remember those?). The file bootstrap.aspx can be an empty file. It's there only to, erm..., bootstrap ASP.NET.
<script language="vbscript" runat="server">
Sub Application_OnStart
	Dim url, inet, s, xmlhttp 
	'the url must be absolute (i.e. start with http://)
	url = "http://127.0.0.1/myapplication/bootstrap.aspx"

	Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP") 
	xmlhttp.open "GET", url, false 
	xmlhttp.send "" 
	Set xmlhttp = Nothing 

End Sub
</script>

Creating Windows Services

Posted by Sergio on 2008-03-31
How to Create Windows Services

It's not uncommon for an enterprise application to need some form of background processes to do continuous work. These could be tasks such as

  • Cleanup abandoned shopping carts
  • Delete temporary files left behind by some report or image generation feature
  • Send email notifications
  • Create daily reports and send them out
  • Check an email inbox
  • Pull messages from a queue
  • Perform daily or monthly archiving
  • etc

For many of these things there are dedicated tools that provide that feature, like a reporting service (SSRS or BO,) scripts that run in the email server, or even simple executables that are fired by the Windows Task Scheduler. When you have only one or two background tasks, using something like the task scheduler may be OK, but administration quickly becomes painful when the number of tasks grows. The dedicated services like SSRS or BO can be overkill depending on the size of your application or organization.

One approach I like to take is to create a Windows Service for the application, grouping all the different background tasks under a single project, a single .exe, and a single configuration file. Visual Studio has always had a Windows Service project type, but the process of creating a working service is not as simple as you would hope, especially when your service performs more than one independent task.

After creating a couple of services, I realized that I definitely needed to stash all that monkey work somewhere I could just reuse later. I decided to create a helper library to assist creating and maintaining Windows services.

The library doesn't help with all kinds of Windows services, but has helped me a lot with the type of tasks I explained above. The key to the library is the ITask interface.

public interface ITask: IDisposable
{
    bool Started { get; }
    string Name { get; }
    void Start();
    void Stop();
    void Execute();
}

This interface shown all that is needed to create a task that can be started, stopped, and invoked by the service process. But this interface has too many members and many tasks are common enough that these members will be implemented almost identically. For example, tasks that execute on a regular interval will be almost identical, the only different member will be the Execute method. That's why the library comes with some handy base classes as shown in this diagram.

Now when I need to implement a task that runs repeatedly I simply inherit a task from PeriodicalTask or ScheduledTask as seen below. These classes will be part of my service project, from which I remove all the other classes that were added by default.

class CleanupTask : PeriodicalTask
{
    readonly static log4net.ILog Log =
        log4net.LogManager.GetLogger(
           System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public override void Execute()
    {
        //time to run....
        //TODO: write the actual code here
        // ShoppingCart.DeleteAbandonedCarts();
        Log.InfoFormat("Executed: {0}", this.GetType().Name);
    }
}


class DailyReportTask : ScheduledTask
{
    readonly static log4net.ILog Log =
        log4net.LogManager.GetLogger(
              System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    protected override void Execute(DateTime scheduledDate)
    {
        //time to run....
        //TODO: write the actual code here
        // SalesReport.SendDailySummary();
        Log.InfoFormat("Executed: {0}", this.GetType().Name);
    }
}

Instead of hard coding the interval or the scheduled time of the above tasks, we use the service's .config file for that:

<WindowsService>
    <tasks>
        <task name="CleanupTask" interval="600"  />
        <task name="DailyReportTask" time="21:30"  />
    </tasks>
</WindowsService>

There are only a few more things we need to do to get this service ready. First we need to add a new WindowsService item. Here we are naming it MyAppService and making it inherit from from SPServiceBase.

partial class MyAppService : SPServiceBase
{
    public const string MyAppSvcName = "MyAppSVC";
    public MyAppService()
    {
        InitializeComponent();
        //Important.. use the constant here AFTER 
        //   the call to InitializeComponent()
        this.ServiceName = MyAppSvcName;
    }
}

We also need to add an Installer Class, which I'll name simply Installer and which will be invoked during the service installation phase to add the appropriate registry entries to make the service be listed in the Services applet. Here's how this class looks like. Note that it inherits from another base class from the library.

[RunInstaller(true)]
public class Installer : SergioPereira.WindowsService.ServiceInstaller
{
    //That's all we need. Hooray!
}

I mentioned that the installer will add the necessary registry information. Some of that are the name and description of the service. We provide that with an assembly attribute that you can put in the AssemblyInfo.cs or anywhere you like in a .cs file (outside any class or namespace.)

[assembly: ServiceRegistration(
    SampleService.MyAppService.MyAppSvcName, // <-- just a string constant
    "MyApp Support Service",
    "Supports the MyApp application performing several " + 
           "critical background tasks.")
]

A Windows service is compiled as an .exe, so it needs an en entry point, a static Main function. Let's add a Program.cs like this:

class Program
{
    static void Main(string[] args)
    {
        if (!SelfInstaller.ProcessIntallationRequest(args))
        {

            MyAppService svc = new MyAppService();

            svc.AddTask(new CleanupTask());
            svc.AddTask(new DailyReportTask());
            //add more tasks if you have them

            svc.Run();
        }
    }
}

The code above is pretty simple, we are creating the tasks and telling our service to take care of them. Then we start the service. The interesting thing is the call to ProcessIntallationRequest. This is where we added the self-installing capability of the service. If you wrote a service in the past, you know that they get installed by using InstallUtil.exe. One potential problem is that InstallUtil.exe may not be present on the server or not in the PATH, making an scripted installation a little more complicated. Instead, by using the that call from SelfInstaller, we enabled our service to be invoked like the following to install or uninstall it (remember to execute as an Administrator).

SampleService.exe -i[nstall]
SampleService.exe -u[ninstall]

After installing it, you should see the service in the Services applet.

Here's the final structure of our project.

If you want, download the library source code along with a sample service project. There's more in the library than I have time to explain here, including an auto-update task and extra configuration properties for each task.

Edit and Continue

Posted by Sergio on 2008-03-29

I may very well be the last one to figure this one out, but I always thought that the Edit and Continue option in Visual Studio 2005 and 2008 was a myth. I always made certain that the Enable Edit and Continue check-box was firmly checked, as shown below, but I had never gotten the feature to work.

With that option enabled any time I attempted to alter the code during debug, to add a quick comment or fix a small typo, the dreaded message would pop up, mocking me for not losing that habit.

Only recently I was told that the darn thing works the other way around. I don't know if I'm reading this wrong, but it seems counter-intuitive that un-checking that option enables you to edit the source file during a debug session. I un-checked it and to my shock it worked. I felt that anger of several years of being deprived of that feature boiling inside of me and I had to take a deep breath to avoid a nervous breakdown.

Exaggerations aside, this one goes into my list of why wasn't I told that before along with: