The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  75 Posts :: 0 Stories :: 49 Comments :: 2 Trackbacks

Ads

Archives

Post Categories

Open Source Projects

Other Blogs

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.


Wednesday, July 07, 2010 #

There are a few solutions out on the web for this – here’s my implementation for you to use (and for me to safe-keep). I use this primarily for testing my ActiveRecord objects, as I haven’t really found any use for this mechanism in any production environment

Firstly, the configuration. Notice that I specify my own connection provider (make sure you correctly swap out the relevant portions with your own namespaces). Also, there’s a slight twist in the connection string that you may want to take note of. The rest is straight forward.

  <activerecord isDebug="true" isWeb="false">
    <config>
      <add key="connection.provider" 
           value="Darkside.ARLibrary.SqLiteConnectionProvider, Darkside.ARLibrary"/>
      <add key="dialect" value="NHibernate.Dialect.SQLiteDialect"/>
      <add key="connection.driver_class" value="NHibernate.Driver.SQLite20Driver"/>
      <add key="connection.connection_string" value="Data Source=:memory:;Version=3;New=True;"/>
      <add key="proxyfactory.factory_class" 
           value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
      <add key="show_sql" value="true"/>
    </config>
  </activerecord>

Next, you’ll need to implement your own connection provider. The reason this needs to be done is because when you close a connection on a SQLite database which you’ve configured to be in-memory, the entire contents (tables and data) is lost.

You simply inherit from NHibernate.Connection.DriverConnectionProvider and override the GetConnection() and CloseConnection() methods. In your implementation of GetConnection(), you cache an instance of the connection and always return the same one. In CloseConnection(), you do nothing – you don’t need or want to close the connection.

    public class SqLiteConnectionProvider : NHibernate.Connection.DriverConnectionProvider
    {
        private static System.Data.IDbConnection m_Connection;
        public override System.Data.IDbConnection GetConnection()
        {
            if (m_Connection == null) 
                m_Connection = base.GetConnection();
            return m_Connection;
        }
 
        public override void CloseConnection(System.Data.IDbConnection conn)
        {
            //Do nothing
        }
    }

Tuesday, May 11, 2010 #

A colleague asked me this morning if I already had a code snippet that compressed and decompressed byte arrays that he could make use of. He needed it to compress a variable before passing it as an argument to a WCF call, and decompress in the service itself. I’ve never made use of the System.IO.Compression namespace (I’d always used SharpZipLib), so I thought this would be a quick and useful experiment.

After referencing the local MSDN and then the customary 30 second google, I decided I’d make my own, better, wheel :) I’m still convinced it’s less verbose than the first ten results I looked at, by the way.

The compress part was easy enough (and follows the same logic as just about every example I found). What I couldn’t understand was why everyone implemented long-winded decompress routines. The answer to that question (found in MSDN) is that the Length property of the DeflateStream is not implemented and always throws an exception, meaning that you can’t determine the length of the byte array you’ll need.

Here’s my quick-and-easy solution to the problem: 

 Expand Code
    public static class CompressionUtils
    {
        const int BUFFERSIZE = 1024;
 
        public static byte[] Compress(byte[] data)
        {
            var memoryStream = new MemoryStream();
            var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress);
            deflateStream.Write(data, 0, data.Length);
            deflateStream.Flush();
            deflateStream.Close();
            return memoryStream.ToArray();
        }
 
        public static byte[] Decompress(byte[] data)
        {
            var buffer = new byte[BUFFERSIZE];
            var returnVal = new List<byte>();
 
            var deflateStream = new DeflateStream(new MemoryStream(data), CompressionMode.Decompress);
            int count;
            while ((count = deflateStream.Read(buffer, 0, BUFFERSIZE)) > 0)
            {
                if (count != BUFFERSIZE)
                {
                    var tmpBuffer = new byte[count];
                    Array.Copy(buffer, tmpBuffer, count);
                    returnVal.AddRange(tmpBuffer);
                }
                else
                    returnVal.AddRange(buffer);
            }
 
            return returnVal.ToArray();
        }
    }

Tuesday, April 13, 2010 #

It’s been ages since I posted anything. The following code has had me tied up for the past few months :) :

this.Children.Add(new Child("Sebastian", new Date(2010, 1, 8));

Just to get going again, here’s a simple tip. I’ve just completed installing Visual Studio 2010, and the first thing that struck me was that there was still no way to change the theme. (And this mild OCD thing that I may or may not have means that everything must look the same and be neat).

I found this extension for VS2010 in the Microsoft Visual Studio Gallery, and it works like a charm. When you initially install it, it adds a “Theme” menu to your IDE – after I set up the theme I needed, I simply customized the menu again to remove it.

image

Now my VS2010 IDE matches my Aero look and feel on my Windows 7 machine.


Thursday, November 19, 2009 #

Speculative execution is a term applied to the execution of code that you may not need the results of. With the abundance of spare processing power on servers these days (and workstations for that matter), you can easily make an application be far more responsive to the user or make processing tasks on a server application quicker.

Monday, November 16, 2009 #

If you find you’re getting compile errors something along the lines of

error C2664: 'CreateFileW' : cannot convert parameter 1 from 'char [261]' to 'LPCWSTR'

or

error C2664: 'CreateProcessW' : cannot convert parameter 2 from 'char *' to 'LPWSTR'

I got plenty of these when compiling code which I C&P’d, which was working perfectly in one project, to a new project I had just created; All the errors were related to converting char/char arrays to LPWSTR. There are plenty of programmatic ways of converting this data, and keep in mind you may still want to check these out, rather than my “simple” fix, which is change the “Character Set” property in the project configuration settings to “Multi-Byte”

 

image


Thursday, November 12, 2009 #

I was asked by a colleague about how I might go about shuffling a deck of cards in C#. I found a few takes on this general problem on Google, and make no mistake: this has been covered by numerous persons over the last 80 years according to some of the research I found. So, yes, this is mostly likely a Wheel Version 2.0 piece of code, but here it is and hopefully it’ll be useful to someone.

Firstly, you need to decide on a Random Number Generator. If you’re just interested in solving this card-shuffling problem as part of a hobby-type application, using the System.Random class provided, or in my case the System.Security.Cryptography.RandomNumberGenerator, will suffice. To make this really strong, you may want to look at a pseudo-random algorithm along the lines of the Mersenne twister or one of it’s improved variants, or the simpler to implement Multiply-with-carry. Random number generators are really a topic all on their own and way out of the scope of this post.

Now, onto the relatively simple part: Shuffling a 52 card deck. I’ve designed a simple Deck class to make it easier for displaying results, but the algorithms can easily be transferred to whatever structure you’re using to store your cards/deck. I’ve also added my RNG as a static local variable to the class to increase its effectiveness. (Also, part of the RNG-related topic)

 Expand Code

public class Deck : IEnumerable<Deck.SuitCard>

{

    public enum Suit { Spade, Diamond, Club, Heart }

    public enum Card { A, N2, N3, N4, N5, N6, N7, N8, N9, N10, J, Q, K }

 

    public class SuitCard

    {

        public long Index { get; set; }

        public Card Card { get; set; }

        public Suit Suit { get; set; }

 

        public override string ToString()

        {

            return Card.ToString().Replace("N", "") + " " + Suit;

        }

    }

 

    private readonly List<SuitCard> m_List = new List<SuitCard>();

    private static readonly RandomNumberGenerator m_Random = RandomNumberGenerator.Create();

 

    public Deck ()

    {

        int i = 0;

        foreach (Suit suit in Enum.GetValues(typeof(Suit)))

        {

            foreach (Card card in Enum.GetValues(typeof(Card)))

            {

 

                m_List.Add(new SuitCard() { Card = card, Suit = suit, Index=i++ });

            }

        }

    }

}

The first shuffle I’ve implemented is based on the Knuth-Fisher-Yates shuffle and as you can see by the code, is amazingly simple to implement.

 Expand Code

    1 public void Shuffle()

    2 {

    3     //Knuth-Fisher-Yates shuffle algorithm

    4     for (int i = m_List.Count - 1; i > 0; i--)

    5     {

    6         var data = new byte[1];

    7         m_Random.GetBytes(data);

    8         Swap(i, data[0] % (i + 1));

    9     }

   10 }

   11 

   12 private void Swap(int x, int y)

   13 {

   14     Debug.Assert(x >= y); //Just to make sure...

   15     SuitCard tmp = m_List[x];

   16     m_List[x] = m_List[y];

   17     m_List[y] = tmp;

   18 }

Quoted from Wikipedia: The basic process of Fisher–Yates shuffling is similar to randomly picking numbered tickets out of a hat, or cards from a deck, one after another until there are no more left. What the specific algorithm provides is a way of doing this numerically in an efficient and rigorous manner that, properly done, guarantees an unbiased result.

That being said, this computation as I’ve implemented in the source code is is prone to an effect known as modulo bias – you can seen the mod that is done on line 8.

Another amazingly clever, yet simple, method of shuffling the cards is randomising a number, assigning it to the first card in the deck, and repeating the process for each card. Once you’ve completed, you order the cards by the random number, and your deck is shuffled.

 Expand Code

   61 public void Shuffle()

   62 {

   63     for (int i = 0; i < m_List.Count; i++)

   64     {

   65         var data = new byte[4];

   66         m_Random.GetBytes(data);

   67         m_List[i].Index = data[0] + (data[1] * 256) + (data[2] * 65536) + (data[3] * 16777216);

   68 

   69     }

   70     m_List.Sort(new Comparison<SuitCard>(delegate(SuitCard x, SuitCard y)

   71     {

   72         if (x.Index < y.Index) return (-1);

   73         if (x.Index > y.Index) return (1);

   74         return 0;

   75     }));

   76 }

I use the same RNG, and then convert the four bytes to a long (line 67) – this is the field that I “sort” the deck by, to give you a shuffled deck.

And that’s my two ways of shuffling a deck of cards in C#.


Thursday, October 08, 2009 #

If you get an error message along the lines of “Saving changes is not permitted. The changes you have made…”, it’s actually an option that can be toggled. Go to Tools->Options->Designers->Table and Database Designers and toggle the “Prevent saving changes..” option.

image


Friday, August 14, 2009 #

Seeing as I have to search for this code snippet on most occasions that I use it, I’ve decided to put it here as a post. I often find that I have to repeat the same code over and over when converting between two similar types (e.g. Person domain object and PersonDto object). If you see something like this crop up too often:

var personDto =  new PersonDto
{
    Id = person.Id,
    FirstName = person.FirstName,
    LastName = person.LastName,
    Age = person.Age
};

You have two options: 1) Refactor your code into an extension method so you have something like this:

var personDto = person.ConvertToPersonDto();

or, refactor you code into an implicit operator overload, so that your code looks like this:

var personDto = (PersonDto) person;

I prefer the latter, primarily because my refactored code can be part of the same class, and not have to be placed in separate static classes, as with all extension methods. The overloading of the operator looks like this:

public static implicit operator PersonDto (Person person)
{
    return new PersonDto
               {
                   Id = person.Id,
                   FirstName = person.FirstName,
                   LastName = person.LastName,
                   Age = person.Age
               };
}