Fully qualified type names for generic types

Syntax for generic types names:

MyAssembly.MyClass`[[MyAssembly.MyOtherClass, MyAssembly]], MyAssembly

Should be able to use this format anywhere a type name is required, including the Inherits attribute on ASPX Page declarations.

</p>

Using AppDomains to run a process outside of the ASP.NET Context

There a few reasons why you might want to run a process in an AppDomain.

For example, if you need to be able to unload and update the loaded

assemblies. Or in my case, use an assembly which actively blocks

execution in your currentAppDomain which may be under the ASP.NET context.

In

this simple example the same security evidence and configuration of the

current domain is used. Further the current assembly happens to be the

one we want to execute, this doesn’t need to be the case however. TheAppDomain.CreateDomain method creates a new AppDomain

and returns a reference to it. This will be used to call create the

processing class and unload the domain when it’s no longer needed.

Next an interface is needed (suggested) for the object that is going to be executed. Here it’s IMyProcess

which defines a Process method. The implementation needs to inherit

from MarshalByRefObject. This allows the framework to handle garbage

collection and life cycle management of the object across the two

domains. Also any object passed across the domain should inherit from

MarshalByRefObject. If the process is really long running, some of the

life cycle properties of MarshalByRefObject will need to be changed.

A

context object is used here to pass data to the processing class, this

isn’t explicitly needed but makes for a little cleaner code. It is also

a MarshalByRefObject. TheCreateInstanceAndUnwrap method creates a proxy

to the specified type and Unwraps it making it usable as if the object

was created in the current domain. The full assembly name, the type

name,BindingFlags, args (for the constructor in this case), CultureInfo, and security evidence need to be passed to the CreateInstanceAndUnwrap

method. The returned object needs to be cast to the Interface type,

done with the as keyword here. Now the Process method of theIMyProcess can be called.

Lastly, the created domain should be unloaded using the AppDomain.Unload method, passing the domain reference from the CreateDomain method. This should be in a finally block to make sure the domain is unloaded. Creating AppDomains

is an expensive process and should be done with this consideration in

mind. Below is most likely not the best way to minimize that expense.



using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security.Policy;

namespace AppDomainSample
{
static class Program
{
[STAThread]
static void Main()
{
Execute(1, "connection...");
Console.ReadKey();
}

public static void Execute(int id, string connectionString)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string assemblyName = assembly.FullName;
string basePath = new Uri(Path.GetDirectoryName(assembly.CodeBase)).LocalPath;

AppDomain currentDomain = AppDomain.CurrentDomain;
Evidence evidence = currentDomain.Evidence;

AppDomainSetup ads = new AppDomainSetup();
ads.ConfigurationFile = currentDomain.SetupInformation.ConfigurationFile;
ads.ApplicationBase = basePath;
ads.PrivateBinPath = basePath;
ads.ShadowCopyFiles = "true";

AppDomain d = AppDomain.CreateDomain("AppDomainSampleName", evidence, ads);
try { MyContext context = new MyContext(id, connectionString);

d.Load(assemblyName);
object[] args = new object[] { context };
IMyProcess r =
d.CreateInstanceAndUnwrap(assemblyName, "AppDomainSample.MyProcessImpl", false,
BindingFlags.CreateInstance, null, args, CultureInfo.CurrentCulture, null, evidence) as IMyProcess; r.Process(); } finally { AppDomain.Unload(d); } } } internal class MyProcessImpl : MarshalByRefObject, IMyProcess
{
private readonly MyContext _context;

public MyProcessImpl(MyContext context)
{
_context = context;
}

public void Process()
{
Console.WriteLine("ConnectionString: {0} from {1} domain.", _context.ConnectionString,
AppDomain.CurrentDomain.FriendlyName);
}
}

internal interface IMyProcess
{
void Process();
}

internal class MyContext : MarshalByRefObject
{
private readonly int _id;
private readonly string _connectionString;

public MyContext(int id, string connectionString)
{
_id = id;
_connectionString = connectionString;
}

public int Id
{
get { return _id; }
}

public string ConnectionString
{
get { return _connectionString; }
}
}
}

Initializing excel for use from a service account

Sometimes you need to use excel automation and you’d like to have your service or web application running under an service account identity. In some cases excel wants to run some setup on first use by an account. One way is to log into the machine using that account and open excel. A quicker way is to use the following command.

C:\Program Files\Microsoft Office\OFFICE11>runas /user:MyServiceAcct excel.exe

Embedded Databases

I needed an embeddable database to handle some processing before

inserting the data into the final database. I worked with three

different embeddable databases, each had some pros and cons.

SQL Server Everywhere/Mobile edition

SQL Server Everywhere

is a free embeddable database from Microsoft, formally SQL CE. It’s

small, fast and offers almost full support for T-SQL. One thing that it

doesn’t support is square brackets for escaping names. Also, no support

for stored procedures, which wasn’t a concern for this project. The

main problem was that it will throw an exception if it’s running under

IIS. It’s obvious from the documentation that running under IIS is not a supported

environment, but there are some cases where it could provide a good

solution. I worked around this using app domains, which I’ll post about

later. It can be used with SQL Server replication which could be a hugely useful feature.

Being a MS product it has a fully supported .net provider and is supported on Mobile devices.

Embeddable Firebird

Firebird was

easy to setup and get going, but it does have one very annoying quirk.

It uppercases names by default and it doesn’t accept square brackets

for escaping names, but does accept single quotes. Also, it is case

sensitive so if you use them then you always have to use them unless

your names are uppercase. For example select * from ‘mytable’ is not the

same as select * from ‘MyTable’. And if you create a table with create

table mytable it will create a table named MYTABLE and selects will

need to select from MYTABLE not mytable. I don’t know if I explained

this clearly, but it is a weird quirk. This may be changed in version 2

which I don’t think has an embedded version yet, but could be a very good DB if this quirk was addressed.

The download section has the embeddable version and a .net provider.

Sqlite

Sqlite was also

very easy to get working and worked well for smaller data sets. Using

an index column or having a lot of data rows (10,000+) and things started

to really slow down. It could have been that I didn’t have something

setup correctly, but regardless it was performing really slowly. Setting up a auto

incrementing primary key was a bit tricky, the syntax is below. I don’t

see any advantage to this over SQL Server Everywhere, except that it’s

open source, it may also support stored procedures, but I’m not sure.

create table mytable (id integer primary key)…

The System.Data.Sqlite

project offers the Sqlite DB and a .net provider in one merged managed DLL, which makes

for a very clean distribution. Also, provides Mobile development

support.

All in all, I liked SQL Server Everywhere the best, it has really good

performance a small footprint and a familiar syntax if you’re used to

SQL Server.</p>


Castle monorail logging with windsor

Using Castle monorail with windsor, I setup the logging facility and followed the IoC of concept parameters for optional components. I noticed the base Controller had Logger property and assumed that windsor would handle it from there. However, my controller always had the NullLogger as the ILogger property. The base Controller class doesn’t have a setter for the Logger property. Still not sure why that is, also the property is not virtual. I should submit a patch for this. Anyway, one solution is to create a new property Logger in your own Controller with a getter and setter thus allowing windsor to set the Logger when the Controller is created.

public abstract class BaseSiteController : ARSmartDispatcherController
{
private ILogger _logger = new NullLogger();

public new virtual ILogger Logger {
get { return _logger; }
set { _logger = value; }
}
}
</p>

SharpDevelop project templates

I wanted to create castle project template for SharpDevelop, I ran into a few issues, some I found a way to fix, some I didn’t.

One thing that I needed to do was add a project reference to a dll that was not in the GAC, to do this the HintPath attribute can be used on the Reference element.

    <Reference Include=“Castle.Core” HintPath=“c:\castlebin\Castle.Core.dll”/>

Secondly, I wanted to set the debug options to allow cassini debugging. I found a way to set these options but I didn’t find a way to dynamically insert the project name/dll into the command line options. In the PropertyGroup element you can add the following to set these options. Note the ${ProjectName} string is not replaced with the project name.

    <DebugOptions>
        <StartAction>Program</StartAction>
        <StartProgram>c:\program files\cassini\CassiniWebServer2.exe</StartProgram>
        <StartArguments>C:\Documents and Settings\Dusty\My Documents\SharpDevelop Projects\${ProjectName} 8080 “/${ProjectName}”</StartArguments>
    </DebugOptions>

So I guess there are still two main problems with this setup. First you have to know the path of any dll’s that are not installed in the GAC. And if you want to reference the project name in the debug options, it doesn’t look like there is a way to do that. But for setting up personal project templates these things may be useful.


Setting build numbers with Nant

    <h3> Setting build numbers with Nant </h3> I wanted something that would update the version number of my builds from within Nant. I found that using some of the built in functions of Nant I could get what I wanted without too much work. Nothing really exciting here, but a couple of notes. First the version numbers stored in the meta data limit the size to uint16.maxvalue - 1 so the value must be less then 65534. As such I could not use the format yyyyMMdd as I wanted to, so I ended up using days since 1/1/2000. Secondly, when loading the file with loadfile I needed to mark the encoding as UTF-8 so that the file would be writen back out in a usable form. Anyway, here's the nant code I ended up using.<br /><pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">property</span><span class="attr"> name</span><span class="kwrd">="build.major"</span><span class="attr"> value</span><span class="kwrd">="0"</span><span class="kwrd">/&gt;</span><span class="kwrd"><br />&lt;</span><span class="html">property</span><span class="attr"> name</span><span class="kwrd">="build.minor"</span><span class="attr"> value</span><span class="kwrd">="9"</span><span class="kwrd">/&gt;</span><span class="kwrd"><br />&lt;</span><span class="html">property</span><span class="attr"> name</span><span class="kwrd">="build.build"</span><span class="attr"> value</span><span class="kwrd">="${timespan::get-days(datetime::now() - datetime::parse('01/01/2000'))}"</span><span class="kwrd">/&gt;</span><br /><span class="kwrd">&lt;</span><span class="html">property</span><span class="attr"> name</span><span class="kwrd">="build.revision"</span><span class="attr"> value</span><span class="kwrd">="0"</span><span class="kwrd">/&gt;</span><br /><span class="kwrd">&lt;</span><span class="html">property</span><span class="attr"> name</span><span class="kwrd">="build.version"</span><span class="attr"> value</span><span class="kwrd">="${build.major}.${build.minor}.${build.build}.${build.revision}"</span><span class="kwrd">/&gt;</span><br /><span class="kwrd">&lt;</span><span class="html">foreach</span><span class="attr"> item</span><span class="kwrd">="File"</span><span class="attr"> property</span><span class="kwrd">="assemblyinfofile"</span><span class="kwrd">&gt;</span><br />  <span class="kwrd">&lt;</span><span class="html">in</span><span class="kwrd">&gt;<br /></span>    <span class="kwrd">&lt;</span><span class="html">items</span><span class="attr"> basedir</span><span class="kwrd">="${project.root}"</span><span class="kwrd">&gt;<br /></span>      <span class="kwrd">&lt;</span><span class="html">include</span><span class="attr"> name</span><span class="kwrd">="**\AssemblyInfo.cs"</span><span class="kwrd">/&gt;<br /></span>    <span class="kwrd">&lt;/</span><span class="html">items</span><span class="kwrd">&gt;</span><br />  <span class="kwrd">&lt;/</span><span class="html">in</span><span class="kwrd">&gt;</span><br />  <span class="kwrd">&lt;</span><span class="html">do</span><span class="kwrd">&gt;<br /></span>    <span class="kwrd">&lt;</span><span class="html">echo</span><span class="attr"> message</span><span class="kwrd">="${path::get-file-name(assemblyinfofile)}"</span><span class="kwrd">/&gt;<br /></span>    <span class="kwrd">&lt;</span><span class="html">loadfile </span><span class="attr">file</span><span class="kwrd">="${assemblyinfofile}"</span><span class="attr">property</span><span class="kwrd">="assemblyinfofile.content"</span><span class="attr">encoding</span><span class="kwrd">="utf-8"</span><span class="kwrd">/&gt;</span><br />    <span class="kwrd">&lt;</span><span class="html">regex</span><span class="attr"> pattern</span><span class="kwrd">="&amp;quot;(?'version'\d+\.\d+\.\d+\.\d+|\d+\.\d+\.\*)&amp;quot;" </span><span class="attr">input</span><span class="kwrd">="${assemblyinfofile.content}"</span><span class="kwrd">/&gt;</span><br />    <span class="kwrd">&lt;</span><span class="html">echo</span><span class="attr"> file</span><span class="kwrd">="${assemblyinfofile}"</span><span class="kwrd">&gt;</span>${string::replace(assemblyinfofile.content, version, build.version)}<span class="kwrd">&lt;/</span><span class="html">echo</span><span class="kwrd">&gt;</span><br />    <span class="kwrd">&lt;</span><span class="html">echo</span><span class="attr"> message</span>="<span class="attr">-</span><span class="kwrd">&gt;</span> Updated version from ${version} to ${build.version}"<span class="kwrd">/&gt;<br /></span>  <span class="kwrd">&lt;/</span><span class="html">do</span><span class="kwrd">&gt;</span><br /><span class="kwrd">&lt;/</span><span class="html">foreach</span><span class="kwrd">&gt;</span></pre><div style="clear: both; padding-bottom: 0.25em;"></div>

Brutalist Framework