The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  83 Posts :: 0 Stories :: 56 Comments :: 2 Trackbacks

Ads

 

Donate via PayPal...

...if you feel the site helped.

Archives

Post Categories

Open Source Projects

Other Blogs

Friday, January 20, 2012 #

Wow – it seems like last year just flew by. I opened LiveWriter this morning and realised that I last posted an article in June 2011, and that I have 14 incomplete articles that I’ve never got round to completing.

To kick off the year, I’m going to start off with (what I think) is an underused class in Castle ActiveRecord (actually, it resides from NHibernate) – Disjunction.

The Disjunction type can be used to construct large 'OR' statements for use in ActiveRecord data retrievals. If you have used this class before, you may have noticed that any ‘OR’ operations that have more than two boolean operation that you’ve wanted to perform end up looking like this:

    var criteria = Restrictions.Or
        (
        Restrictions.Or(Restrictions.Like("Firstname", "Foo"), Restrictions.Like("Lastname", "Foo")),
        Restrictions.Or(Restrictions.Like("Firstname", "Bar"), Restrictions.Like("Lastname", "Bar"))
        );
 
    var person = Person.FindAll(criteria);

The example above ends up producing some unnecessary code clutter to essentially come up with the SQL statement:

WHERE 
   Firstname LIKE '%Foo%' OR
   Firstname LIKE '%Bar%' OR
   Lastname  LIKE '%Foo%' OR
   Lastname  LIKE '%Bar%'

Using the Disjunction class, you can modify the original example to look like this:

            var criteria = new Disjunction();
            criteria.Add(Restrictions.Like("Firstname", "Foo"));
            criteria.Add(Restrictions.Like("Firstname", "Bar"));
            criteria.Add(Restrictions.Like("Lastname", "Foo"));
            criteria.Add(Restrictions.Like("Lastname", "Bar"));
 
            var person = Person.FindAll(criteria);

In my opinion: better looking code and, although it’s not quite made evident in the examples above, it makes for much easier programming. Image that you were searching 5 fields for three keywords – the “tree” that you’ve effectively built in the first example would start looking horrendous and would be a nightmare to maintain.


Tuesday, June 07, 2011 #

A while ago I blogged about a template project that I often use as my starting point for Windows services. I’ve recently been introduced to a component called TopShelf that makes writing a service even simpler as well as taking just about all the plumbing code needed for installing/uninstalling and running in debug mode.

Here’s an example of the code that goes into the Main method. It sets up the service, name, description, and you tell it what to call on the Start and Stop service control events.

 Expand Code
        static void Main(string[] args)
        {
            const string name = "My Service Host";
            const string description = "My Service Host Description";
            var host = HostFactory.New(configuration =>
            {
                configuration.Service<ServiceHostControl>(
                    callback =>
                    {
                        callback.SetServiceName(name);
                        callback.ConstructUsing(s => new ServiceHostControl());
                        callback.WhenStarted(service => service.Start());
                        callback.WhenStopped(service => service.Stop());
                    });
                configuration.SetDisplayName(name);
                configuration.SetServiceName(name);
                configuration.SetDescription(description);
                configuration.DependsOnMsSql(); //Just here as an example of some of the features
                configuration.RunAsLocalService();
            });
            host.Run();
        }

I make reference in the code above to a class called ServiceHostControl. This class is the only other code I have in my template project as of now – it provides the stub methods for starting and stopping the service.

 Expand Code
    internal class ServiceHostControl
    {
        public void Start()
        {
            Console.WriteLine("starting...");
            //Do everything here to start up the service...
            Console.WriteLine("started.");
        }
 
        public void Stop()
        {
            Console.WriteLine("stopping...");
            //Do everything here to shut the service down...
            Console.WriteLine("stopped.");
        }
    }

There is no longer a need to have a service installer class anymore either in the project – all this functionality is brought to the party by the Topshelf component. To install your service, you simply drop to a command prompt and type in:

{serviceassembly.exe} install

and (as you can most likely guess) to uninstall, you type in:

{serviceassembly.exe} uninstall

It’s as simple as that.


Thursday, May 12, 2011 #

This is just a quick tip that you can use to restart ReSharper in Visual Studio (without restarting the IDE) if it becomes unresponsive. In my case, it just disappears from view and the majority of my shortcuts stop working.

Open the immediate window, either through the menu “Debug->Windows->Immediate” or using the keyboard shortcut “Ctl-Alt-I”.

Type in:

>ReSharper_Suspend press enter, and then

>ReSharper_Resume

You must type the “>” first to be able to enter commands in the immediate window.

 

Some other notes:

  • You can use the command window as well (just leave out the angle bracket), however, I find that the shortcut “Ctl-Alt-A” often breaks when ReSharper is broken. Moving my hand to my mouse is an effort :)
  • You could also use the command “ReSharper_ToggleSuspended” twice in a row; You just have to keep swapping to a code window to test it out.

Monday, April 04, 2011 #

I’ve been contemplating the fact that Reflector is no longer a free tool, and paying the $35 (USD) for the tool. I’ll be honest: paying for software has never been an issue for me. I even use SQL Prompt from RedGate. I write software, and need to get paid for it, for a living.

But…

The fact that RedGate said that they would continue offering Reflector for free and did an about turn on it has riled me a tad. They haven’t even offered existing users a “this-is-the-final-free-version-and-will-never-get-updated” option. Sad.

I went through the suggestions from this Stack Overflow article, and personally feel that ILSpy is the best alternative.

Here’s the list (copied from the summary from the article above):

  1. Common Compiler Infrastructure (CCI)
  2. Mono Cecil
  3. ILSpy
  4. Kaliro
  5. Dotnet IL Editor (DILE)
  6. Monoflector (no longer active as of April 2011)

Try them out – see what you think…


Wednesday, March 30, 2011 #

Configuration

Version 3 now supports the short-hand configuration options supplied by NHibernate. You choose the DB type, supply a connection string name, and the rest of the defaults are chosen for you.

  <configSections>

    <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>

  </configSections>

  <connectionStrings>

    <add name="ARTest" connectionString="Server=(local); Database=ComplexDBTest; Integrated Security=SSPI"/>

  </connectionStrings>

  <activerecord>

    <config db="MsSqlServer2005" csn="ARTest"/>

  </activerecord>

SessionScope-less Lazy Loading

This is a great change that’s been implemented. The code example below (very contrived, I know, but demonstrates the point) used to throw an exception, but doesn’t anymore.

    [ActiveRecord("Person", Lazy = true)]

    public partial class Person : ActiveRecordBase<Person>

    {

        [PrimaryKey(Generator = PrimaryKeyType.GuidComb, Column = "PersonId")]

        public virtual Guid Id { get; set; }

 

        [HasMany(typeof(ContactNumber), Table = "ContactNumbers", ColumnKey = "PersonId", Lazy = true)]

        public virtual IList<ContactNumber> PersonIdContactNumbersList { get; set; }

    }

 

    [ActiveRecord("ContactNumber")]

    public partial class ContactNumber : ActiveRecordBase<ContactNumber>

    {

        [PrimaryKey(Generator = PrimaryKeyType.GuidComb, Column = "ContactNumberId")]

        public virtual Guid Id { get; set; }

 

        [BelongsTo(Type = typeof(Person), Column = "PersonId")]

        public virtual Person Person { get; set; }

    }

 

    public class Program

    {

        static void Main(string[] args)

        {

            ActiveRecordStarter.Initialize(Assembly.GetExecutingAssembly(), ActiveRecordSectionHandler.Instance);

 

 

            ContactNumber contactNumber;

            using (new SessionScope())

            {

                contactNumber = ContactNumber.FindFirst(Order.Asc("Id"));

            }

            Debug.WriteLine(contactNumber.Person.Id); //Used to throw an exception

        }

    }

Make sure that in your configuration, (if you’re still specifying the entire config) you’re using the Castle.ActiveRecord.ByteCode.ProxyFactoryFactory proxy factory.

 

Lazy Loading of Blob Properties

You can now use the “Lazy” keyword on blob properties which tells NHibernate not to include this column in the select statement, but only call it when it’s explicitly used. Some notes on this, though:

  • If you have more than one column marked as lazy, they are ALL fetched when you access the first one.
  • The property should be an auto-prop
  • This results in and extra select being fired off when you used this column – it may end up being a problem in large sets of data.

The syntax is straight forward:

        [Property (Column ="Data", ColumnType = "BinaryBlob" , Lazy = true)]

        public virtual byte[] Data { get; set; }

 

LINQ

LINQ support is now rolled into the Castle ActiveRecord assembly, and doesn’t require a reference to another file.

 

SessionScopeWebModule (Breaking Change)

This has been removed from the main Castle ActiveRecord assembly and is now in the assembly Castle.ActiveRecord.Web.dll. You’ll need to update your configuration for the HttpModule as follows:

    <httpModules>

      <add name="ARScope" type="Castle.ActiveRecord.Framework.SessionScopeWebModule, Castle.ActiveRecord.Web"/>

    </httpModules>


Friday, February 11, 2011 #

It’s been a while since I used the SqlDependency class and the features it provides, and was then quite disappointed that I hadn’t a copy of the plumbing code anywhere on my web clipboard (a.k.a darkside.co.za). I’ve put together a static helper class that you can attach an event to, and then call the Start(…) method.

Here is the code for the class (UPDATE: or you can download it here):

 Expand Code
    1 using System.Data;
    2 using System.Data.SqlClient;
    3 
    4 namespace Darkside
    5 {
    6     public class SqlNotificationHelper
    7     {
    8         private static SqlConnection m_SqlConnection;
    9         private static SqlCommand m_SqlCommand;
   10         private static DataSet m_DataSet;
   11         private static string m_ConnectionString;
   12 
   13         public delegate void DataChanged(DataSet dataSet);
   14         public static event DataChanged DataChangedEvent;
   15 
   16         public static void Start(string connectionString, string sql, CommandType commandType)
   17         {
   18             m_ConnectionString = connectionString;
   19             SqlDependency.Stop(m_ConnectionString);
   20             SqlDependency.Start(m_ConnectionString);
   21             if (m_SqlConnection == null)
   22                 m_SqlConnection = new SqlConnection(m_ConnectionString);
   23             if (m_SqlCommand == null)
   24                 m_SqlCommand = new SqlCommand(sql, m_SqlConnection) { CommandType = commandType };
   25             if (m_DataSet == null)
   26                 m_DataSet = new DataSet();
   27 
   28             SetupNotification();
   29         }
   30 
   31         public static void Stop()
   32         {
   33             SqlDependency.Stop(m_ConnectionString);
   34             if (m_SqlConnection != null)
   35                 m_SqlConnection.Close();
   36         }
   37 
   38         private static void SqlDependencyOnChange(object sender, SqlNotificationEventArgs e)
   39         {
   40             var sqlDependency = sender as SqlDependency;
   41             if (sqlDependency != null)
   42                 sqlDependency.OnChange -= SqlDependencyOnChange;
   43             SetupNotification();
   44             if (DataChangedEvent != null)
   45                 DataChangedEvent(m_DataSet);
   46         }
   47 
   48         private static void SetupNotification()
   49         {
   50             m_DataSet.Clear();
   51 
   52             m_SqlCommand.Notification = null;
   53             var sqlDependency = new SqlDependency(m_SqlCommand);
   54             sqlDependency.OnChange += SqlDependencyOnChange;
   55             using (var adapter = new SqlDataAdapter(m_SqlCommand))
   56             {
   57                 adapter.Fill(m_DataSet, "DataSet");
   58             }
   59         }
   60     }
   61 }
   62 

And you can use it as follows:

protected static void Main()
{
    SqlNotificationHelper.DataChangedEvent += new SqlNotificationHelper.DataChanged(SqlNotificationHelper_DataChangedEvent);
    SqlNotificationHelper.Start("Server=(local); Database=Test; Integrated Security=SSPI", "SELECT Id, FirstName, Surname FROM dbo.People", CommandType.Text);
    Console.ReadLine();
}
 
private static void SqlNotificationHelper_DataChangedEvent(System.Data.DataSet dataSet)
{
    Console.WriteLine("Event – Data Updated." + dataSet.Tables[0].Rows.Count);
}

I should point out that you need to be quite specific in the type of query that you use. The list contained here on MSDN is quite comprehensive. The most common pitfalls I can imagine will befall people is using a * in the SELECT statement, and not specifying the table name in two-part format. The change event still fires even if the query isn’t correct, however, it fires repeatedly and can be quite a pain to debug.


Friday, September 03, 2010 #

I’ve been searching for a good regular expression to validate a string representation of a GUID, and even though there are 17 results on RegExLib.com and 73000+ on Google, I’ve not found one that matches the start and end braces correctly. Every single one I’ve found (without exaggerating, I read over 60 posts while looking)either matches a GUID without the braces, or those that match on a string including the braces allow for either only the first or last to be present.

^(?<-BRACE>\{)?[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}(?<-BRACE>\})?(?(BRACE)^.)$

On a side note: The project I’m doing maintenance on is VS2008/.Net 3.5. If you’re using .Net Framework 4, you can use the Guid.Parse and Guid.TryParse methods to validate a Guid.

UPDATE: I’ve submitted it to RegExLib.com.


Wednesday, August 18, 2010 #

I was busy with a(nother) comparison of Castle ActiveRecord and the Microsoft offerings that have shipped with VS2010 just to make sure that I wasn’t missing out on anything. I ended up fiddling with EDMX files, and then custom generation, which then led me to downloading the ADO.Net POCO T4 generation templates and checking out what was in the files.

I have to admit: when I saw what was in it, I got quite giddy with excitement, followed shortly by feeling like a tool. I can’t believe I’ve missed out on this excellent piece of functionality that has been around for ages.

I decided to tackle making a template that generated output that matched what is generated by Generator Studio, which is an open source project I started with FryHard a few years back, primarily to generate my ActiveRecord classes from my database model. I based my template on the ADO.Net POCO template from Microsoft and used it as my guideline.

Explaining the code in the TT file is a little out of the scope of this article, but it is available here for download

You can paste the zip file in

%userprofile%\Documents\Visual Studio 2010\Templates\ItemTemplates\Visual C#\

and then open the Visual Studio Command Prompt (as Administrator) and run:

devenv /installvstemplates

The command above installs the new templates for Visual Studio.

The quickest way to use it in much the same way as a generator is as follows:

  1. Create a new class library or windows app project.
  2. Add a reference to Castle.ActiveRecord.
  3. Add an ADO.NET Entity Data Model to your project.
  4. Choose the “Generate from Database” option in the wizard
  5. Run through the rest of the wizard adding the tables you’d like to generate ActiveRecord classes from.
  6. Open the entity model in the IDE, and change the “Code Generation Strategy” property in the properties tab to “None”. This remove all code from the designer class attached to the EDMX file.
  7. Add a new “Castle ActiveRecord Basic Template” item to your project. This is the template contained in the download above.
  8. Once the template has been added, you can look at the files generated by it, and there should be 1 each for each table in your database, as well as an additional file that has the same name as the template (except with a .CS extension), that has no functionality in it. This is created by the template (as it was in the original from MS), and I’ve left it there because I’ll most likely use for custom features/base classes as I build on the template.

You should now be able to use the ActiveRecord classes generated as you normally would.

If you make changes to your model in the EDMX designer, you can simply right-click on the template file in the solution and select the “Run Custom Tool” to regenerate your classes.


Friday, July 16, 2010 #

I stumbled upon an interesting problem this morning where Castle ActiveRecord was being initialised correctly in the development environment, but as soon as everything was rolled out to the lab environment, the application would throw errors about AR not being initialised. The error message was along the lines of:

An ActiveRecord class (Darkside.Domain.Person) was used but the framework seems not properly initialized. Did you forget about ActiveRecordStarter.Initialize() ?

A bit of background info: As is custom in our web projects, we use an HttpModule to do the AR initialisation. In this case, the web project is actually a WAS host for our WCF services. After doing a bit of research, I found out that HttpModules are not executed when running WCF services. The reason we had the illusion it was working in dev is because of a default page that was started when the project was run. This caused the HttpModule to run, which in turn initialised AR for that session.

Our solution to this problem was to make use of a custom service host factory. I’ve touched on the custom service host factory subject here before, and this solution is just another use of it.

public class CustomServiceHostFactory : ServiceHostFactory
{
    private static readonly object m_InitActiveRecordLock = new object();
 
    public override System.ServiceModel.ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
    {
 
        //Initialise ActiveRecord...
        if (!ActiveRecordStarter.IsInitialized)
        {
            lock (m_InitActiveRecordLock)
            {
                if (!ActiveRecordStarter.IsInitialized)
                {
                    ActiveRecordStarter.Initialize(Assembly.Load("Darkside.Domain"), ActiveRecordSectionHandler.Instance);
                }
            }
        }
 
        //Hand off the real host creation to the base class..
        return (base.CreateServiceHost(constructorString, baseAddresses));
    }
}

You then need to add the Factory attribute into your .SVC file

<%@ ServiceHost Language="C#" Debug="false" Service="Darkside.Services.CRUDService, Darkside.Services" Factory="Darkside.WAS.CustomServiceHostFactory" %>

Now, if a new service host is created in your app, AR will be initialised first, if needed.


Thursday, July 15, 2010 #

Here’s a winner snippet of code I found:

public enum BooleanComparer
{
    True,
    False
}

I laughed. I cried. I came to the conclusion that maybe booleans are just not for everyone.