{ Code: Impossible } | this = HowI.Roll();

TAG | .NET

Aug/10

27

Spot the bug

What is wrong with the code below?

Safe Assumptions:

  1. _dictionary is a valid non-null Dictionary<object,object>
  2. _dictionary contains items that will match the passed expression
  3. This code compiles with no warnings or errors
  4. This code will throw an exception at runtime.

public IList<TModel> GetAllByCriteria<TModel> ( Expression<Func<TModel, bool>> criteria )
{
    Func<TModel, bool> action = criteria.Compile();
    return _dictionary.Where( pair =>
        action( (TModel)pair.Value ) ).Cast<TModel>().ToList();
}

If you don’t see it right away then you’re not alone. I spent a while debugging to catch this. If you do see it right away then pat yourself on the back.

· · ·

I mentioned previously that I am working on a dev environment setup script for a long-term project at work. The goal of this script is to get a developer’s machine ready to work on the project, installing dependencies, creating dev/test databases, etc.

Since our project will be using CouchDB my script should create/update a few databases when it is run (this part is coming soon!). But before that can happen the script needs to check for the presence of an active CouchDB instance.

Since CouchDB has a completely HTTP-based API we can test for its existence by opening up our favorite browser and visiting http://localhost:5984. This gives us:

{"couchdb":"Welcome","version":"1.0.0"}

So my script is going to need to do an HTTP GET on the url above and compare it to the JSON response that CouchDB should send back. Now normally, I might want this check to be less strict, maybe only checking that {"couchdb":"Welcome" was returned, but in this case I want the specific version number as well so this check will be fine going forward.

If I don’t get the response I expect I’ll want the script to fail out immediately; No sense in continuing with the environment setup if one of the key components is missing!


$futonurl = "http://localhost:5984"
$resp_couchdb = [string](new-object System.Net.WebClient).DownloadString($futonurl)

if( $resp_couchdb.Trim() -eq "{""couchdb"":""Welcome"",""version"":""1.0.0""}" ) {
    Write-Output "CouchDB 1.0 Found!"
    # here we can continue setting up our test/dev document stores
} else {
    throw("CouchDB v1.0 must be installed and running to continue...")
}

Althought this script is pretty simple, it shows that PowerShell is not just MS-Batch 2.0. PowerShell lets me leverage .Net to do heavy lifting from the command-line that I wouldn’t be able to do without creating a few console applications.

· ·

The Asp.net Mvc 2.0 RTM came out last month and a lot of people are converting their projects over. If you’re just starting to manually move your projects over then stop what you are doing, download and run the Mvc Converter. It will save you eons of time and frustration.

If you are like me, however, and started porting your project over manually and are now knee deep in WTFBBQ sauce then follow the steps below and your project should be up and running in no time.

1. Back up your project. Just in case.

2. Open your project file(s) inside your favorite text editor (one with a decent find/replace system). Open the Find & Replace dialog and find "603c0e0b-db56-11dc-be95-000d561079b0", replacing it with "F85E285D-A4E0-4152-9332-AB1D724D3325". My project turned up 1 result.

3. Open the Web.Config files in the root of the project and the root of the /Views folder. Open the Find & Replace dialog again, this time searching for "System.Web.Mvc, Version=1.0.0.0" and replacing it with "System.Web.Mvc, Version=2.0.0.0".

4. Add the following BindingRedirect to the bottom of the root Web.Config, just before the </Configuration> node.


<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
      <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
    </dependentAssembly>
  </assemblyBinding>
</runtime>

5. Open the solution in Visual Studio and replace the references to System.Web.Mvc 1.0 with the 2.0 assembly.
6. Finally, and only if you really need them, open a new MVC 2.0 project and copy all the files in the /Scripts folder to your project.

Enjoy your freshly migrated project!

· · ·

I’ve wrapped up work on v0.4 of the Jsoq Console, and the insanely strenuous release cycle for v0.1 of WhatDidIJustEat.com so I’m starting another side project tonight.

Ever been working with a programming language you’re not 100% familiar with and find yourself wondering:

Is this function a built-in function or in some included library?
What assembly is this class in again?
Can I name my class XXXX without conflicting with another class?

I’ve had these questions recently and found myself annoyed and frustrated to no end (PHP, I’m looking at you) so I’ve decided to build a system to keep track of this stuff for me :D.

The first thing on my list (because it was the easiest) was to do a data dump of all the public classes in the .Net Framework, including the ones in my GAC, and store some metadata for each one in a database table. I’ve just finished this step and thought that this data might be useful, so I’m posting it here.

Currently the fields included in the data dump are:


[namespace] = The namespace that the class exists in (ex: System.Collections.Generic)
[class_name] = The name of the class (ex: StringBuilder)
[assembly_fullname] = The display name of the assembly (ex: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
[assembly_file] = The full file path to the assembly (ex: C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll)
[framework_name] = The framework that uses this class, for this dump they will all be 'Microsoft .Net'
[framework_version] = The framework version that uses this class (ex: v.2.0.50727)

The .sql file takes about 18 seconds to run to completion on my AMD Athlon X2 2.53ghz machine with 4gb of RAM.

If you’re curious about how I generated the .sql file, below is the code I used to find all the classes. It’s not pretty but then again it was just meant to get the data into the database. Just paste the code into a new console app and run it in a command window like so:

[application_name].exe > c:\classes.sql

Or, you can download the .sql file I’ve generated (it will also create the table you need to store the data).


static void Main(string[] args)
{
	var dictionary = new Dictionary(){
		{ "v2.0.50727", @"C:\Windows\Microsoft.NET\Framework\v2.0.50727" },
		{ "v3.0", @"C:\Windows\Microsoft.NET\Framework\v3.0" },
		{ "v3.5", @"C:\Windows\Microsoft.NET\Framework\v3.5" },
		{ "v???", @"c:\windows\assembly\gac" }
	};

	var types = new List();

	foreach (var pair in dictionary)
	{
		var path = pair.Value;

		var assemblies = Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories);

		foreach (string file in assemblies)
		{
			try
			{
				Assembly asm = Assembly.LoadFile(file);

				foreach (Type t in asm.GetTypes())
				{
					if (t.IsPublic)
					{
						Console.WriteLine(String.Format(
							"INSERT INTO Classes (" +
								"[namespace], " +
								"class_name, " +
								"assembly_fullname, " +
								"assembly_file, " +
								"framework_name, " +
								"framework_version" +
							") " +
							"VALUES (" +
								"'{0}', " +
								"'{1}', " +
								"'{2}', " +
								"'{3}', " +
								"'Microsoft .Net', " +
								"'{4}'" +
							")",
							String.IsNullOrEmpty(t.Namespace) ?
								"GLOBAL" :
								t.Namespace,
							t.Name
								.Replace("`1", "")
								.Replace("`2", "")
								.Replace("`3", ""),
							t.Assembly.FullName,
							t.Assembly.Location,
							pair.Key == "v???" ?
								t.Assembly.GetName().Version.ToString() :
								pair.Key
						));
					}
				}
			}
			catch { }
		}
	}
}

If you found this useful, let me know in the comments!

· · ·

Oct/08

2

Jquery + MVC = Web Dev Heaven

So Jquery is going to become part of Asp.net MVC. First off, congrats to the Jquery team. They’ve put out a really awesome product. Second, congrats to Microsoft for catching every .Net developer completely by surprise, proving, again, that they are listening to the community.

I never really got into the microsoft javascript libraries that shipped with the ajax control toolkit because I found that I could do things much faster using external javascript libraries .

It will be interesting to see what Microsoft contributes back to the Jquery community in later updates to the ASP MVC product.

· · · ·

Older posts >>

Theme Design by devolux.nh2.me