IronRuby 1.1 with LINQ support

by DotNetNerd 20. July 2010 08:37

Finally LINQ is supported in IronRuby now from v. 1.1 and I think it has been solved quite elegantly without any real syntactical gooeyness. Trying it out has been made very straight forward by looking at the 101 LINQ samples rewrite for IronRuby.

From day one LINQ has seemed a natural fit with IronRuby already having a similar approach with functions such as .each {|item| ...} which is accessible on anything that can be enumerated - very much like a big part of LINQ is extentions methods to the IEnumerable interface. No doubt there has been some challanges around how to map generics, extention methods etc between the languages, but syntactically it seems a natural fit.

products.where(lambda { |p| p.units_in_stock > 0 and p.unit_price > 3.00 }).each { |x| puts x.product_name }

Combining functional methods from LINQ with the existing Ruby methods just makes the "Integrated Query" syntax even better. So now we get a .each method with LINQ even though Microsoft originally didn't want to include it :)

 

Tags: ,

IronRuby and hashes in metaprogramming

by DotNetNerd 29. June 2010 19:39

This will probably be one of the shortest blogposts I'll ever write, and probably the one with the least amount of code - besides an occational rant. The reason is that like pictures sometimes say more than a 1000 words, so does elegant code.

module MyModule
class MyClass
def write_stuff text
puts text
end
end
end

m = MyModule::MyClass.new
actions = {:write_stuff => "Hello action packed world!"}
actions.each {|key, value| m.method(key).call(value) }

It might just be me who is weird - but I think this way of doing eg. a strategy pattern is pretty cool.

Tags:

Ajax-enabled WCF services and loadbalancing

by DotNetNerd 10. June 2010 20:35

This week I ran into a problem when we were deploying a webapplication that uses ajax-enabled webservices to an environment that uses loadbalancing. The services were running fine in the stage environment and when each of the servers were called directly, but as soon as we went through the loadbalancer they failed.

I started by checking if the svc files could be reached, and surely enough they could be accessed from the servers, but through the loadbalanced domain I got a 404.

Reading blogposts on the subject provided little help – well actually it just hightened my degree of confusion. So after some time I started thinking about IIS bindings. I remembered that I had written a custom WebScriptServiceHostFactory because we had several bindings which IIS doesn’t handle too well.

using System;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace MySite.ScriptingService
{
    public class MyCustomHostFactory : WebScriptServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            //This makes it possible to control which binding is used by sorting them in IIS.
            return new ServiceHost(serviceType, baseAddresses[int.Parse(ConfigurationManager.AppSettings["BindingIndex"] ?? "0")]);
        }
    }
}

I started playing around with which binding we used, and as I suspected if the binding was not the one for the loadbalanced domain it returned the 404. This was one of those “doh!” moments. I still had a problem though, because the site could be accessed both with and without the www subdomain. A colleague pointed to the fact that we could use the URL rewrite plugin for IIS, and have it ensure all traffic was directed through one of the domains. As it turnes out it actually has a CanonicalHostNameRule that does just this because its a SEO good practice. Only issue I had left was that umbraco on the other hand has a practice that it must be accessed directly on one server, so changes are made on the master and replicated to the slave(s). This just required extending the conditions so it does not redirect if the umbraco folder is part of the path.

IIS routing

So now by posting this I hope Ill save someone else from getting a few extra gray hairs, and if not maybe I’ll save my self some other time when I can’t remember how I did…

Tags: , ,

Hello rake-world

by DotNetNerd 27. May 2010 16:31

Rake is a quite popular build framework, that has its strengths in the fact that it is code (no more xml), and it is very simple to get started with. Actually setting it up is a 3 step process.

  1. Make sure the path environment variable is set to point at your ironruby/bin folder.
  2. Run “igem install rake” from the commandline
  3. Write a Rakefile.rb like the following and place it at the root of your site

require 'rake'

task :default => [:say_hi]

desc "Does quite a bit of greeting"
task :say_hi_to_me do
    puts "Hello me. Now that was easy."
end

task :say_hi_to_world do
    puts "Hi world!"
end

task :say_hi => [:say_hi_to_me,:say_hi_to_world] do
    puts "I’m, all hellowed out"
end

This really all it takes, so now you are ready to run your tasks from the commandline by writing: “rake” or “rake say_hi_to_me”.

Now for this to get really interesting you will need albacore which makes it easy to do all kinds of basic tasks.

This is installed with the command “igem install albacore”, and makes it possible to do builds and run unittests like this:

require 'rake'
require 'albacore'

task :default => [:full]

task :full => [:clean,:build_release,:run_tests]

task :clean do
    FileUtils.rm_rf 'build_output'
end

msbuild :build_release do |msbuild|
  msbuild.properties :configuration => :AutomatedRelease
  msbuild.targets :Build
  msbuild.solution = "TestApp/TestApp.sln"
end

nunit :run_tests do |nunit|
    nunit.path_to_command = "tools/nunit/nunit-console.exe"
    nunit.assemblies "build_output/TestAppTests.dll"
end

rakemonkey

Tags: ,

Silverlight and IronRuby – a match made in heaven

by DotNetNerd 25. April 2010 10:31

A couple of months ago I was starting to read about IronRuby, and while thinking about what my first little pet project should be I saw a tweet from a guy who was enjoying the combination with Silverlight. I gave the idea some thought and liked the idea of using a dynamic language to make a rich internet application. So after reading IronRuby UnleashedI started out doing a version 2 of my dotnetnerd.dk site – which is just a little toy selfpromotion site.

Getting started was pretty straight forward because with IronRuby there is a small webserver called Chiron, which can make a project template. All you have to do is open a cmd, and go to the library where IronRuby is installed and type script\sl.bat ruby <projectpath>

Armed with my starter template I began playing around and got my layout in place. I also tried using some 3rd party components by referencing some dll’s and all that basic stuff. Most of it went smoothly, but I did run into an assembly (Flickr.net) that threw an exception when used with Silverlight/IronRuby. Using it from a console project in IronRuby worked fine, so I quickly decided to just go directly against the flickr api using the .NET WebClient class. Running the site from chiron was as easy as calling script\chr.bat /d:<projectpath> /b:index.html

When I had the first couple of pages ready and had written a picturegallery showing the last 5 pictures I have uploaded to flickr I wanted to get the site deployed, so I would no longer depend on chiron. From my book and by looking at blogs it seemed to be smooth sailing, because chiron has a function that makes a .xap file which is all you need. To my surprise when I referenced the .xap file from the html file in my my project it looked like it loaded, but then just stopped at 100% without showing my actual site. I felt pretty stuck, because I had no exception or anything to go on, and my site ran fine when I was using chiron.

I then wrote an email to “Iron” Shay Friendman, who wrote the book that I was using as my inspiration. I thought it was worth a shot, and that I could not be the only one with that problem. Later that day he wrote back, and (as the nice guy he is) told me that he did not know the solution off the top of his head but he would look at it as soon as he had a couple of available hours. A few days later he had found a solution, and it turnes out a few things need to be done differently when running it outside of chiron. So this is basically what I want to share with this post :)

What you need to do is:

1) If your .rb files contain references like “app.xaml” it should be changed to app\app.xaml – in other words the references should be from the root of the solution and not from the app folder where the file is located.

2) Make the .xap file using the command script\chr /d:<projectpath> /z:<projectpath>\app.xap

3) In the index.html file where the .xap file is referenced find the like starting with <param name="initParams".
Change its value attribute to "start=app\app.rb,reportErrors=errorLocation".

And easy as 1-2-3, your site should work when running the index.html file.

Shortly put it really has been a fun project, and I really like the IronRuby and Silverlight combination, so it is definately not my last project where I will combine the two.

ironrubylogo

MongoDB – getting better for .NET

by DotNetNerd 6. March 2010 16:24

Since my last post Rob Connery has joined the team working on MongoDB, and he recently blogged about the latest additions he has made on github. I couldn’t resist taking a look at the latest changes, and even though there is still some way to go it is nice to see the improvements to the drivers for .NET.

My last sample is already depricated, so Ill shamelessly steal his sample, and modify it slightly just to see the new bits running with entities that I worked with last. So Ill recommend looking at the sample from the blogpost, since I’ll be using his session class.

First thing to notice from Robs sample is that I don’t have to think much about mapping classes to documents any longer. One thing that is already depricated even from Robs own sample is that it is now a requitement that the class has an identifier. So going with the simplest thing possible I added an ID integer.

using (var session=new Session()){
   session.Add(new Actor { ID = 1, Name = "Hans", Age = 40, Gender = Gender.Male });
   session.Add(new Actor { ID = 2, Name = "Eva", Age = 22, Gender = Gender.Female });
}

So comparing to Db4o, we are now closer to a similar experience. One of the things I’ll wait to look at, but I see as fairly importait is how either will handle Lazy<T> properties and other kinds of more advanced scenarios.

With the above objects saved the data can be accessed using a Linq query like so:

using (var session=new Session())
{
   var actors = session.Actors;
   foreach (var actor in actors.Where(a => a.Gender == Gender.Male))
   {
       Console.Write(actor.Name);
   }
}

The LINQ provider is still not too far along so I’ll leave it alone for now, but it is also one of the places where it will be interesting to compare e.g. db4o and MongoDB in the future.

Tags: ,

Ayende - the relational dragonslayer

by DotNetNerd 23. February 2010 18:31

Ayende, who most know to be one of the Guru's when talking about ORM's and by extention working with relationel databases came to a very interesting conclusion a couple of days ago when he received a phonecall. To parafrase his point in "Slaying relational dragons" in a few words, a very real and complex problem had one very simple and elegant solution - do not use a relational database. This acknowledgement is as a see it a strong incentive to take a look at what NOSQL solutions like document and object based databases has to offer. And his blogpost is something I would definitely recomment reading...

 

Tags: ,

Db4o – first look

by DotNetNerd 21. February 2010 13:12

As the next step in my recent adventures into NoSQL country I decided to take a look at db4o. Shortly put I hope it will give me more than the document based databases, like Mongo that I have also been taking out for a spin.

My interest in NoSQL has been kindled further than it already was because of blog posts from Rob Connery, who looked into practical approaches and posts on CodeBetter provokingly entitled Using an ORM is like kissing your sister. Basically what they are all saying is that it is very limiting that we always start out with a relational database without even considering this very very important architectural decision.

Object vs Document

Similar to the document based database, the big win is that there is no schema, and no need to map between objects and a relational model. Actually with document based databases you do map to key/value pairs, so it’s not the whole truth, but still simpler than mapping to a relational model.

Mapping can be expensive in two ways – because it takes time to write the code, and it does warrant a certain overhead. On top of that db4o as an object oriented database has a concept of relations between objects. This means that rich querying capabilities are build in and that it performs really well.

When comparing to MongoDB the big thing missing is that it basically works on a flat file out of the box. So you need something to handle concurrency and stuff like that. Rob Connery posted a nice sample of how this could be done, and its really quite straight forward, because db4o does provide all you need to do it.

The basic stuff

In the interest of simplicity I’ll just sample how to work with db4o directly. Also this will illustrate just how straight forward it really is. The first thing that brought a smile to my face was how little I had to do to save and query a bunch of objects.

using (IObjectContainer context = Db4oEmbedded.OpenFile(Server.MapPath("myDatabase.yap")))
{
    var empolyeeToSave = new Employee() { Name = "John", Card = new TaxCard() { Number = "12345678" } };
    context.Store(empolyeeToSave);

    IList<Employee> retrievedEmployees =
        context.Query<Employee>(employee => employee.Card.Number == "12345678");
}

 

As you can see it’s very straightforward stuff. Besides this type fo querying which takes a predicate, there is also a QueryByExample, which works as one would expect. Another nice thing is that all calls to the Store method make up a transaction, so there is a Rollback method available. When the context is disposed the convention is that Commit is called for you, so when you don’t need rollbacks you don’t have to think about it.

Indexing is also possible with db4o, and it is also very simple to do, so if for instance I would like to apply an index for the name property on my Employee I could do this.

Db4oFactory.Configure().ObjectClass(typeof(Employee)).ObjectField("Name").Indexed(true);

Moving along

Some of the first things that I have heard people think about when I say object/document based database is how to handle versioning and querying. With querying in this case I mean how to enable a scenario similar to opening SQL Manager and writing some queries to take a look at the actual data.

The versioning part may take a little work, but there are methods to help with e.g. renaming directly baked in - and besides, it takes work no matter what kind of database your using. On top of that my thought is that both of these issues can be addressed with a dynamic language. My plan is to take a look at this at some point, and that it will fit nicely because my copy of IronRuby Unleashed should be on it’s way :)

b_DBA

Tags: ,

My Ajaxy JavaScript stack

by DotNetNerd 24. January 2010 12:12

I have been working primarily with ASP.NET MVC for a little over a year now, and this has prompted me to do quite a bit more Ajaxy functionality. So while doing this I have been looking at quite a few Ajax/Javascript libraries.

As most other developers I have been swept away by JQuery, which by far is the most important component when I am doing Ajax and manipulating the html DOM - see cheatsheet. Besides making a lot of these things easier, it also provides a wide variety of plugins that enable all sorts of shiny fancy features without much work. One of the very usefull ones that I find myself using on all kinds of projects is tablesorter- that makes clientside table sorting almost free.

Working in the Microsoft domain I have of course also been working with Microsofts ASP.NET Ajax Librarywhich also brings quite a few cool things to the table. Most basically it enriches the javascript experience by providing namespaces, intellisence and a bunch of extentions to the basic javascript type system. On top of that there are a lot of extenders to work with accordions, watermarks, listsearch etc. were most projects will find something that is useful to provide a better UI experience. The latest addition, that I am already very fond of even though it is still just in the beta version is templates. This gives us a easy way to do databinding on the client - one-way/two-way livebindings, and ways to do this both declaratively and imperatively. In other words it provides a rich templating experience and no more clumbsy string manipulation!

Next thing that is important when working with Ajax is having some solid libraries to do JSon serialization. Here I will strongly recommend JSON2for the client because eval is evil. Also a small but important thing to know is that data must be serialized and provided as a string when using JQuery to call a WCF service. On the serverside, I recommend Json.NET or maybe Json for the compact framework if you need something that is easier and more extendable than the .NET build in DataContractSerializer.

Finally something that might also be worth looking at to get better performance is using a content delivery network to reference the different scripting librarys. Here I will recommend looking at either Microsoft Ajax Content Delivery Networkor Google AJAX Libraries. Both seem very reliable and will give what you need, so its mostly a matter of personal preference.

18okt04_ajax_logo_150_rgb

ajax_logo2

Tags: , ,

MongoDB – how to get started

by DotNetNerd 3. January 2010 11:17

Even though I have been pretty disconnected during the holydays I couldn’t help read that Rob Conery wrote quite a bit on his blog about his thoughts on Ayendes “EF vs NHibernate” discussion. Rob Conery argues that he is tired of these discussions and that we need to look at the NOSQL movement and instead focus on alternatives to relational databases.

I found this pretty interesting and decided that it was finally time for me to take a look at one of the document based databases out there. As Rob mentioned MongoDB I thought this was a good a place to start as any. Based on my experiences I then decided to do this post on what I learned about getting MongoDB up and running. So first of all, the steps to get a MongoDB server running are:

  1. Download and unpack from: http://www.mongodb.org/display/DOCS/Downloads
  2. Create folder C:\data\db and make sure the server has read and write access
  3. Run the server from cmd. Go to dir where you unpacked (eg: "c:\MongoDB\bin") and run "mongod"

You can now work with the database from the commandline, but to start writing some code you need to get a driver that suits you. In my case I went with a driver so I can write my code in C#. This driver along with a early edition of a LINQ library can be downloaded from http://github.com/samus/mongodb-csharp/downloads 

This is all you need to get going, so just create a new project and start coding!

A good sample can be found here http://blog.dynamicprogrammer.com/2009/11/10/UsingMongoDBFromC.aspx and if your into F# this might be interesting http://gist.github.com/218388

The first sample focuses on two ways to handle converting objects into documents.

  1. Serialize object(hierarchy) into JSon using JSonConverter - which was the sample I focused on.
  2. Make entities implement the IMongoEntity interface – which basically just makes your entity expose a Document property which then contains the state for the entity.

Of course I wont cheat you from seeing the bit of code I started out with, which is heavily inspired by the before mentioned blog posts.

//Connect to the database
var mongo = new Mongo();
mongo.Connect();
var db = mongo.getDB("movieReviews");

//Access the collection that you wish to work with
var movies = db.GetCollection("movies");

//Add a document
var movie = new Document();
movie["title"] = "Star Wars";
movie["leadActor"] = JsonConvert.SerializeObject(
 new Actor() {Name = "Mark Hamill", Age = 26, Gender = Gender.Male});
movie["releaseDate"] = new DateTime(1977, 5, 25);
movies.Insert(movie);

//Do a query
var result = from mov in movies.AsQueryable()
             where (string)mov["title"] == "Star Wars"
             select mov;

//Write out info from document
foreach (var document in result)
 foreach (string key in document.Keys) Console.WriteLine(document[key]);

//Deserialize and write name
Console.WriteLine(JsonConvert.DeserializeObject<Actor>((string)result.First()["leadActor"]).Name);

//Disconnect from database
mongo.Disconnect();

 

You'll also need this simple class for the sample:

public class Actor
{
 public string Name { get; set; }
 public int Age { get; set; }
 public Gender Gender { get; set; }
}

public enum Gender
{
 None = 0,
 Male = 1,
 Female = 2
}

Tags: ,

Who am I?

My name is Christian Holm Diget, and I work as an independent consultant, in Denmark, where I write code, give advice on architecture and help with training. On the side I get to do a bit of speaking and help with miscellaneous community events.

Some of my primary focus areas are code quality, programming languages and using new technologies to provide value.

Microsoft Certified Professional Developer

Microsoft Most Valuable Professional

Month List