IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

We’re Living in an Unstandardized World

This post has started from my suffering from developing web sites differently to make them work in IE and in Firefox the same. That was everything I asked for…Currently, even with IE8 I still can’t develop on Firefox and remain calm and confident that the site works the same on IE.

The truth is that it is not entirely Microsoft’s fault. When they begun developing IE somewhere in 1995, standards were not that important – it was more about “please just work” kind of work. In addition, even if there were standards, we can assume that the guys at  Microsoft assumed that they would change the standards as they had done before in other fields. What Microsoft didn’t realize was that the Internet was stronger and that they were not going to win the standards battle this time.

Anyway, out of my suffering I came to a conclusion – even though we like to think of Microsoft as this big evil doer that doesn’t follow standards, it is just another brick in the wall of global un-standardization that started long long ago and still effects our everyday life.

Language – yes, language. Starting from the beginning of days, the very basic resource of our communication is a one big un-standard thing. Just visit the country near you (and sometimes even the district near you) and most likely you will run into a different language than yours. Think of how big it is – almost everything you create in one country, should be fixed in some way to fit a second country. TV shows, manuals, books, user interfaces, etc.

If you do not agree with me because language is related to culture and different cultures is a part of our nature (some would say that it’s a kind of un-standardization, too), the next bullet will be harder for you to disprove.

Signs – especially driving signs. This is something which is entirely unrelated to the local culture. We all should stop at the traffic light, slow when entering school perimeter and beware of rolling stones. As a result, driving rules across the globe are very similar indeed. However, every country uses a slightly different sign set. For example, look at the different Stop signs from across the globe:

Stop in the USAOld UK Stop SignIsraeli Stop SignStop sign in Zimbabwe

If we had to develop a globalized application that involves driving signs, we had to create local versions for each country – very similar to writing code for IE and for Firefox…

Driving direction – that always amazes me. The world is split to about 34% live in right hand traffic countries and 66% live in left hand traffic countries (according to Wikipedia). This is such a big historical standard failure! it forces car companies to produce different versions of cars to meet both standards!

Left hand car Right hand car
In London it’s funny to see drivers from other EU countries driving their right-sided cars and trying to understand how to enter the roundabout. Actually it’s not that funny if they enter the roundabout in the wrong direction – life can be lost! and it’s all because of un-standardization…

The IE vs. FF issue seems less important now, doesn’t it?

Electricitythe differences in electricity methods around the world is astonishing – 110W, 220W, plug with 2 holes, with 3 holes, with wide holes, with thin holes…… huh? why?

 Australia/New ZealandUKIndiaUSAItalyIsrael

It’s like every country developed electricity by itself and didn’t tell the others until they developed it as well. do I hear someone say “Microsoft  and Netscape!”?

In conclusion, our world is full of un-standardization – from the language we talk to Internet development. There are much more examples than the ones I’ve brought here – shoe and shirt sizes, Km and Miles, Kg and Pounds, Meters and Feet, money and more. Although it might be upsetting to meet all standards it also has one big advantage – it creates so many jobs! consequently it helps the world’s economy!

So Microsoft actually helps the world. Yes.

All the best,
Shay.



Executing IronPython Code from IronRuby

One of the advantages of the Dynamic Language Runtime (DLR) is the fact that it makes sharing code between the languages that are written on top of it (and on top of the CLR as well). Therefore, it is possible to share code between IronPython and IronRuby (and any other DLR language as well like IronScheme).

This means that IronPython libraries can be used from IronRuby code and vice versa. Ruby on Rails in Python? Django in Ruby? feels like the end of days, isn’t it? perhaps we should really start preparing to year 2012

In this post I’ll show you how to run simple IronPython code from IronRuby so you can take it and do whatever your imagination guides you to.

Assuming we have a demo.py IronPython file with the next content:

class MyPythonClass:
  def add(self, x, y):
    return x + y

welcome_message = "Hello from Python!"

 

To those of you who don’t know Python, the code  above declares a class named MyPythonClass with a single method named add that combines two numbers and return the result. It also contains a variable named welcome_message.

Note

Because executing Python code from IronRuby involves DLR services, methods that you call from IronRuby must have self as their first argument just like IronRuby-targeted C# methods have (if the method accepts no parameters, then it should have only the self argument). This argument contains the caller class instance.
This means that python code that should be executed by IronRuby should be modified to match the requirements.

After we have the python file in place we can use it from IronRuby. The key for doing so is loading the python file using the IronRuby.require method. This method is similar to the Kernel#require method but with a small difference – it returns the DLR scope object of the loaded script.  This enables you to call the script members via the scope, just like when you load a script manually via the DLR LoadFile method.

The next IronRuby is pretty straight-forward:

# Load the python file
python = IronRuby.require('demo.py')

# Get an instance of MyPythonClass
python_class = python.MyPythonClass()
# Execute the add method (pay attention that there's no 
# need to pass the self parameter, this is done automatically)
puts python_class.add(1, 5)

# Get the python variable and print its value
puts python.welcome_message
# Set the python variable
python.welcome_message = "Hello from Ruby!"
# Print its new value
puts python.welcome_message

 

The output is:
6
Hello from Python!
Hello from Ruby!

Note that for this sample to run, you need IronRuby and IronPython installed on your machine, both compiled with the same Microsoft.Scripting project. I just compiled IronRuby’s and IronPython’s sources to make  it work.

In conclusion, the DLR opens a bunch of new and exciting possibilities specifically in the field of code sharing between dynamic languages and dynamic and static languages. Go ahead and try it, it’s magical!

All the best,
Shay.

kick it on DotNetKicks.com Shout it



IronRuby Sample #3: Creating a DSL

[ This is part 3 of my IronRuby samples series. You can read the first post (Hello World) and the second post (C# Recorder using IronRuby) as well. ]

The Ruby language is very powerful in general, and in its metaprogramming abilities in particular. This time I’m going to demonstrate how you can take advantage of these abilities along with Ruby’s syntax capabilities in order to create a custom DSL (Domain Specific Language) in a matter of minutes. Pay attention that these features are not specific to IronRuby, they are a part of every implementation of the Ruby language.

Let’s start from the end this time. This is the code you will be able to write with my little DSL:

list = ShoppingList.new
list.buy 3.kilograms.of(Peanuts)
list.buy 100.grams.of(Cheese)
list.buy 2.kilograms.of(Snacks)
list.print

Running this will result in the next output to the console:

Please buy:
- 3000 grams of peanuts
- 100 grams of cheese
- 2000 grams of snacks

It’s a nice little DSL to manage your shopping lists with. But as much nice as it is, the more important fact is that you can write your custom DSLs in Ruby (and IronRuby of course) with ease and make your coding experience much more fluent.

How is it Written?

The code for this DSL contains 49 lines of code, including lots of comments… Again, writing DSLs in Ruby (and IronRuby) is very easy. All I needed for this DSL were two “special” techniques of Ruby – const_missing and monkey patching. These two together makes about all the magic of this DSL.

I’m not going to go through the code line by line. I added comments inside the code so I think it will pretty straight forward to read. Do not hesitate to comment or contact me directly if something is not clear enough.

the DSL code:

# ShoppingList class
class ShoppingList
  # Ruby's class constructor - initializes the shopping list array.
  def initialize
    @list = []
  end
  
  # The main method - gets an item and adds it to the array.
  def buy(item)
    @list << item
  end
  
  # Prints all items in the list in a user-friendly way.
  def print
    puts "Please buy:"
    @list.each do |item|
      puts "- #{item[:grams]} grams of #{item[:product].downcase}"
    end
  end
end

# Every call to an undefined constant will reach here.
# This allows to use Peanuts inside the DSL code without defining it
# so we can write 5.grams.of(Peanuts) instead of 5.grams.of("Peanuts")
def Object.const_missing(name)
  # Return the constant as a string
  name.to_s
end

# For the DSL, we need to add grams and kilograms methods to all integers in the application.
# In order to do that, I open the Fixnum class (which is Ruby's equivalent to C# Int32) and add
# the needed methods
class Fixnum
  # grams method will just return itself
  def grams
    self
  end
  
  # Because we save everything in grams, when the kilograms method is used, I'll return 
  # the current value * 1000.
  def kilograms
    self*1000
  end
  
  # The of method retrieves an object and returns a hash of the object and its gram amount.
  def of(product)
    {:product=>product, :grams=>self}
  end
end


All the best,
Shay.



Just Released: IronRuby 0.9.2

We’re getting closer to V1.0!

Version 0.9.2 fixes 44 bugs (some of the irritating ones like the Rails' bug with :default_url_options and the bug that prevented the RSS standard library from running).
The biggest announcement in the 0.9.2 version, in my opinion, is that IronRuby now has an MSI-based installer for Windows! no need to extract a zip file and do everything yourself anymore.

Download it from: http://ironruby.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=33693#DownloadId=90621
0.9.2 release notes: http://rubyforge.org/frs/shownotes.php?release_id=41087

Good times,
Shay.



My Presentation at the Web Developers Community – Riding IronRuby on Rails

Yesterday I had the honor to present IronRuby and Ruby on Rails to the Israeli web developers community.

Thanks all for coming! I had a great time!

The demo and presentation can be downloaded from here:

I also add here the list of resources to get you started with IronRuby and Ruby on Rails:

Lastly, if you have any question, request, recommendation or whatever, don’t hesitate to contact me through the contact form or twitter.

Thanks,
Shay.



Is String.IsNullOrEmpty Good or Bad?

I started to wonder about that when I was looking for an equivalent method in Ruby. Apparently, Ruby doesn’t come with such a method built-in, but you can add it very easily by using Ruyb’s monkey patching abilities.

This is odd, because Ruby is the greatest language and has everything you possibly need (and IronRuby is even better! :) ). So why isn’t there an IsNullOrEmpty-like method? Well, they might just didn’t think it was important enough. And there might be a different answer, maybe the decision has other reasons below the surface.

Several developers have discussed the String.IsNullOrEmpty issue over the years. Some say it’s good, some say it’s bad and some even say it’s hazardous to your code (because of a bug it has).

For me, I go with Ruby’s approach (unless they didn’t add it because of time constraints). Most of the time there will be a big difference between a null string object and an empty string object. Therefore, I think that String.IsNullOrEmpty() should be avoided as much as possible and the application should have a convention of how uninitialized strings should look like – nulls or String.Empty

For example, say you need to validate some input and String.Empty is sent to you. How do you know if the string is an uninitialized string or a real input? saying that null is the convention would have solved this confusion.

I know there are cases where you have to use IsNullOrEmpty. For example, when using 3rd party components that you are not aware of their uninitialized string convention (if such exists…). This is why I don’t rule out IsNullOrEmpty entirely. I do say that wherever you can, do not use it and prefer str == null to spot uninitialized strings.

By the way, deciding that only null is the convention for uninitialized strings can also improve your application performance since str == null is faster than String.IsNullOrEmpty(str) in about 35%. However, you’ll notice an improvement only if you’re doing billions of String.IsNullOrEmpty calls, so don’t panic right away.

In conclusion, String.IsNullOrEmpty is there for convenience reasons.  Sometimes with convenience comes tranquility, so make use of it wisely!

Just a final addition, Ruby on Rails adds a blank? method to Ruby which provides the equivalent to String.IsNullOrEmpty method in C#. So, if Ruby does not contain everything you need, Ruby on Rails surely does! :)

So what do you think, IsNullOrEmpty is good or bad for your application?

All the best,
Shay.

kick it on DotNetKicks.com Shout it



 

C# Recorder using IronRuby

[This post is the second in my series of IronRuby samples. Read the first one here]

The release of Visual Studio 2010 Beta 2 and IronRuby .Net 4.0 Beta 2 CTP has brought some AMAZING abilities to the .Net world like the dynamic keyword. This keyword is a revolutionary little thing. It takes everything you know about C# and throws it away – explicit types, locating syntax errors in compilation time, compiled code…

Sounds bad? well, it is just AWESOME!!! The dynamic keyword brings so much goodness to our beloved C# language, that if it was possible I would have hugged it and asked it to join my family.

Well, enough with the nonsense, let’s get down to business. IronRuby is Microsoft’s implementation of the Ruby language. It runs on top of the DLR and provides a seamless integration with .Net code. In short, it ROCKZZZZZ. This post is about IronRuby’s seamless integration with .Net and the ability to use the great power of Ruby inside C#.

The Ruby language has some very powerful metaprogramming abilities. One of those is the method_missing method. When you declare it in your class, every call to a method that doesn’t exist will be routed to it. You can then do whatever you want with the call – execute a different method, raise an exception, interpret the call somehow or just do whatever you want (jump in the air? do your little Irish dance thing?).

Another nice metaprogramming feature is the ability to send requests to objects by using the send method. The concept is very similar to C#’s reflection method – Invoke.

Now if we combine method_missing and send, we can create a class that saves calls and playbacks them upon request. I will call it… tam tam tam… Recorder:

 

class Recorder
  # Initialize an array that will save the calls
  def initialize
    @calls = []
  end
   
  # Save the calls to method_missing	
  def method_missing(name, *args, &block)
    @calls << [name, args, block]
  end

  # Playback the calls on a given object	
  def playback(obj)
    @calls.each do |name, args, block|
      obj.send name, *args, &block
    end
  end
end

 

I think this code is pretty straight forward, no special things here. With this class defined, we can record Ruby calls and playback them on Ruby objects:

 

# Record calls
rec = Recorder.new
rec.reverse!
rec.insert 2, "ABAB"
rec.delete! "A"

# Playback them on a real object
str = "Hello World"
rec.playback(str)
puts str # Prints "dlBBroW olleH" 

 

 

It is AWESOME, but the great thing about it is that with .Net 4.0 and the dynamic keyword, it is available in C# too!

To try the next code by yourself, first open Visual Studio 2010 Beta 2, create a new C# console application and add references to IronRuby.dll, IronRuby.Libraries.dll, Microsoft.Scripting.dll and Microsoft.Dynamic.dll (remember to use the CTP assemblies and not the regular IronRuby assemblies).

The following code loads the Ruby recorder class file (recorder.rb) to the C# environment, creates an instance of the Recorder class, records a few operations and playbacks them on .Net objects:

 

static void Main(string[] args) 
{      
  // Load the recorder IronRuby file
  var engine = IronRuby.Ruby.CreateEngine();
  engine.ExecuteFile("../../recorder.rb");
  dynamic ruby = engine.Runtime.Globals;

  // Initialize IronRuby's recorder class
  dynamic recorder = ruby.Recorder.@new();

  // Record
  recorder.Add(1);
  recorder.Add(2);

  // Playback on CLR's List object
  List<int> list = new List<int>();
  recorder.playback(list);

  // Print the results!
  foreach (var item in list)
  {
    Console.WriteLine(item);
  }

  // Record console printing
  recorder = ruby.Recorder.@new();
  recorder.Write("IronRuby");
  recorder.WriteLine(" and .Net 4.0");
  recorder.WriteLine("Rock!!!!!!!!!!");

  // Playback on console
  recorder.playback(Console.Out);
}


The output to the console will be:
1
2
IronRuby and .Net 4.0
Rock!!!!!!!!!!

Try it out and see the magic happens right in front of your very own eyes!

In my opinion, this joint venture is incredibly helpful and useful. I predict that as time goes by we will see more and more dynamic language code make its way to the conservative .Net world, enhancing it and adding it powerful abilities that it never has had before.

All the best,
Shay.

Share it: kick it on DotNetKicks.com Shout it



IronRuby Sample #1 – Hello World

A bunch of readers have asked me to post IronRuby samples. I took your advice and I am starting a series of posts where I’ll write some IronRuby samples so you can see what’s IronRuby code is all about.

I’ll begin with the simplest sample and as the series goes on, I’ll try to bring you more complex samples. If you’d like to see a specific sample, please contact me and let me know about it.

So the first sample is a Hello World sample. The regular Ruby Hello World app, which of course runs on IronRuby as well, is as follows:

puts "Hello World"

 

Now, the great thing about IronRuby is the ability to use .Net classes. The next code also writes Hello World to the console, but this time it uses .Net’s System.Console class. The sample also sets the color of the text to green:

orig_color = System::Console.foreground_color

System::Console.foreground_color = System::ConsoleColor.green
System::Console.write_line "Hello World"

System::Console.foreground_color = orig_color

 

To run that, just save this text into a file and execute it by ir.exe <file name>. This is how its execution will look like:

IronShay - IronRuby Sample #1

.Net developers pay attention - CLR objects get Ruby’s naming conventions when they are converted to IronRuby objects. This operation is called “name mangling”.  This is why System.Console.ForegroundColor appears as System::Console.foreground_color in IronRuby. You can read more about name mangling in the .Net Interoperability Fundamentals chapter in my book. These chapters are available for free through the Rough Cuts program.

If you’d like to see a certain sample next time, let me know.

All the best, 
Shay

Upcoming Session: Riding IronRuby on Rails at WDC, Israel

I’m glad to announce that another IronRuby session is getting closer, this time at the Israeli Web Developers Community!

When?

Sunday, 1st of  November, 2009. 17:00-20:00.

Where?

Microsoft Offices, 2 HaPnina St., Rannana.

What?

The session is all about IronRuby, with a focus on Ruby’s most famous member – Ruby on Rails. The session will  start with an overview of the Ruby language and its powerful abilities, continue with IronRuby and  the stuff it brings to your everyday work and end with a Ruby On Rails overview, including live demo of building a Web 2.0 application from scratch.

Why?

Because IronRuby can enhance your everyday work, speed up your development process and make it enjoyable and fun! In addition, you will see another web development framework, Ruby on Rails, which will show you another way of web development and will also give you an idea about where today’s web MVC frameworks got all their ideas and probably their future ones as well  :)
And most importantly, there will be free food and drinks!

How?

Register to the event at: http://msevents.microsoft.com/cui/EventDetail.aspx?EventID=1032426828&culture=he-IL 

By the way, If you’d like me to come and present at your event (conference, user group, internal gatherings, courses…), please contact me.

Hope to see you there,
Shay.

Visual Studio Tip: Compilation Symbols

There are times when we need to use different code statements for different build configurations – this means that some code will not exist in assemblies that are built in certain build configurations.

Compilation symbols come to help in this case. You can set a symbol that will exist in  a specific build configuration and then use it inside your code files to write or exclude code when this project is built using this build configuration.

The most familiar case of this scenario is debug and release build configurations. Actually, the debug build configurations comes with a compilation symbol by default named DEBUG. By using it you can write code that will run only when you compile your project in debug mode (show extra message boxes, write more logs, etc.).

Creating Compilation Symbols

  1. In Visual Studio, go to Project-> <project name> Properties…
  2. The project properties view will open. Click on “Build” on the left.
  3. The Build settings will open on the right. The first field there, with the label “Conditional compilation symbols” is the one you need.
  4. Add there the name or names (semi-colon separated) of the compilation symbols you want to define. Pay attention that the naming convention for these symbols is all uppercase.
  5. Save

You’re done. You can start using the compilation symbols you have just  defined. The next screenshot contains a sample project with two symbols defined – SHAY and FRIEDMAN:

IronShay | Compilation Symbols

Using Compilation Symbols

In order to use the compilation symbols you have defined, you need to use the special compilation conditions. If these conditions are not met, the code within the condition will not be compiled at all.

The condition starts with #if <condition> and ends with #endif. For example, the next code will be compiled only when SHAY is defined (which is in debug build configuration):

#if SHAY

Console.WriteLine("SHAY is defined! woot!");

#endif

You can also write more complicated conditions like !SHAY for all build configuration without SHAY defined. You can add conditions too – SHAY && FRIEDMAN.

Well, that’s about it!
Hope it helps,
Shay.

kick it on DotNetKicks.com