The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  70 Posts :: 0 Stories :: 47 Comments :: 2 Trackbacks

Ads

Archives

Post Categories

Open Source Projects

Other Blogs

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
               };
}

This is (another) look at implementing a dynamic proxy using Reflection Emit. Why would you need a dynamic proxy? Well, there are times when functionality needs to be injected into existing code that can not be modified. My dynamic proxy generator allow you to supply two Action parameters the will be executed as pre- and post-call methods. The tests that I have provided with my sample application show an example of injecting timing code into existing methods. It could also be used to insert log

Thursday, August 06, 2009 #

After doing some random surfing this morning (I think I started off with binging “operator precedence C#”, I landed on this page about one line variable swaps, which then got me thinking about how to do this in C#. My only solution I could come up with was using arithmetic to solve the problem:

 

int x = 11;
int y = 42;
 
y = (y + x) - (x = (y + x) - x);
 
Debug.Assert(x == 42);
Debug.Assert(y == 11);

 

Please don't use this code, unless you're on some type of job security mission :)

 UPDATE: 12 Aug 2009 – Ok, so I wasted more time on it. Savage also submitted a refactored version of my previous try

 

int x = 11;
int y = 42;
 
x = y ^ x ^ (y = x);
 
Debug.Assert(x == 42);
Debug.Assert(y == 11);

 


Friday, July 31, 2009 #

Rant()

{

Stop reading here if you’re looking for something technical :)

I’ve recently started interviewing candidates for what I would describe as a mid-level developer, skilled in ASP.Net/C#. This brought back memories of much the same exercise I went through last year when looking for a med-to-senior level developer.

So to summarise how I think that went, I’ll paraphrase some questions and answers that have stuck with me:

Q: Does C# support multiple inheritance?
A: I’ve never really needed to use inheritance, so I haven’t paid much attention to it.

Q: Can you explain the concept of generics and what they add to C#?
A: C# allows you to program almost anything and that makes it quite generic.

Q: Can you explain to me what an abstract class is?
A: An abstract class is like a class but it isn't really one. It can't do anything.

Dismal. I have a wild imagination, and when I start thinking back to this, my mind is filled with the imaginative sound of a downward-spiral-type-thing. It's a lot like in the Road Runner cartoon when Wile E Coyote falls of the cliff, except in a spiral, going back and forth from ear to ear.

Wile-E-Coyote

I digress.

Before I get flamed with comments like “Aren’t these loaded/catch questions?” or “I’m sure you can find the answers on Google very quickly”, I have to ask a question: Surely these concepts should be understood by someone applying for a mid-level/senior developer position? What intrigued me at the time was the oft occurring idea that many of these candidates classed themselves as senior because they were either the person who had been at their previous company the longest, or they had managed to secure their current position which had that title.

I feel that a senior developer should have excellent knowledge of the language he is working in; he should be able to work on almost any code or project unsupervised, and require very little input on “how to do things”. I found this article on StackOverflow and the first answer (at the time of writing started with “We have similar gradings:”) is very much in line with my thinking and what I expect. I also think that a working knowledge of concepts like patterns, common algorithms, lazy loading and continuations are a plus. So, if I get a CV that describes the candidate as “senior developer”, I expect this person to be pretty damn good and they can expect me to give them an equally good grilling during the interview.

My idea of mid-level developers is that they have reasonable knowledge about the language they’re working in, can handle small projects by themselves with some guidance from a senior, and should be able to write a string reverse function which does simple things like boundary checking, null reference checks, etc. The reason I include that last one is that it’s one of the questions I ask in the practical test for mid-level developers. As of today, the score is zero out of four.

Maybe I’m expecting too much.

}


Monday, May 25, 2009 #

If you’ve decided to download the Castle ActiveRecord 2 Alpha version and see how it affects your existing projects, you’ll most likely get an error like this: “The ProxyFactoryFactory was not configured.Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.”. This release of ActiveRecord makes use of NHibernate version 2.1.0.1003, which requires an additional entry in the configuration section to work correctly. The updated configuration section for your config file looks like this (line 13 in the example is what you’ll need to add):

    1   <activerecord 
    2     isWeb="false"
    3     isDebug="true"
    4     threadinfotype=""
    5     sessionfactoryholdertype=""
    6     namingstrategytype="">
    7     <config>
    8       <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
    9       <add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
   10       <add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
   11       <add key="connection.connection_string" value="Server=(local);initial catalog=AppTest; Integrated Security=SSPI"/>
   12       <add key="show_sql" value="true"/>
   13       <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
   14     </config>
   15   </activerecord>

Wednesday, May 06, 2009 #

If you’ve ever used the Microsoft File Transfer Manager to download items from the MSDN subscriber downloads section, you may have accidentally closed it and searched your drive high and low to find the application to restart it.

If you haven’t run the MSI installer and just let IE install it, the application is in %SYSTEMROOT%\Downloaded Program Files\TransferMgr.exe. I found this article on Microsoft which has method of starting it from the command prompt, as well as an MSI installer which actually will give you a shortcut for you to start the application.

If you’re happy with you IE installed version, here is a shortcut (.LNK) file that you can use to start/restart it.