Printing Web Pages – the Cool Way!

When developing web applications we often run into a request to print one or more pages within the applications. In most cases, these pages will contain some type of report.
There are tons of ways to do that. Most of them I don’t like, especially the trivial one that pops to mind - “open a new window with a printer-friendly version of the page and set onload=’window.print()‘”. I find it quite irritating for the user.

There is another solution, which is less popular than its fellow window.open solution, but IMHO is much more user friendly and also might save you a few lines of code. It’s the CSS @media print solution!

What’s it all about?

  1. You get to have a single page that prints in slightly a different way than it’s presented on the browser.
  2. The magic lies within a special CSS block where you define CSS classes that will be used when the page is printed.
  3. This way you can hide parts of the page that don’t need to be printed, change the background image, increase/decrease font size, etc.

 

How to use it

The idea is to declare a different set of CSS styles for the page’s print mode. The great thing about that is that you can also, via CSS, hide elements that are unnecessary for printing.

For example, assuming you have the next HTML document:

<html>
<head>
    <title></title>
</head>
<body>
  <h1>REPORT</h1>
  <form><input type="button" id="printButton" value="Print" onclick="window.print()"/></form>
  <table border="1">
    <thead>
      <tr>
        <td>Column A</td><td>Column B</td><td>Column C</td>
      </tr>
    </thead>
    <tbody>
      <tr><td>1</td><td>2</td><td>3</td></tr>
      <tr><td>4</td><td>5</td><td>6</td></tr>
      <tr><td>7</td><td>8</td><td>9</td></tr>
    </tbody>
  </table> 
</body>
</html>

This page will be presented as follows:

image

Great UI indeed. However, printing this page will be a bit ugly (surprise surprise!), but really, in terms of printing the page, the header shouldn’t be that big and the print button shouldn’t be visible at all.

To do so, all we have to do is to define the styles for printing mode:

<style type="text/css">
  @media print
  {
    /* Here goes all styles to be used when printing */

    #printButton { display: none; } /* hide the print button */
    h1 { font-size: 12px; } /* make the header 12 pixels */
    body, td { 10px; } /* make regular text 10 pixels */
  }
</style>  

That’s it. Now if we print-preview the page, the header will be smaller and the Print button will be hidden:

Print Preview with @media print

Voila! No window.open is needed!

[Side note: I know this approach might be problematic sometimes because the user wouldn’t know what to expect when the page is printed. However, I still think this is a much more elegant way than the window.open approach. Use it wisely though].

ASP.NET developers: be careful when using CSS’s ‘#’ symbol with element IDs. Remember that ASP.NET changes the final HTML element ID of your controls that have the runat=”server” attribute.

All the best,
Shay.

Full source:

<html>
<head>
  <title></title>
  <style type="text/css">
    @media print
    {
      /* Here goes all styles to be used when printing */

      #printButton { display: none; } /* hide the print button */
      h1 { font-size: 12px; } /* make the header 12 pixels */
      body, td { 10px; } /* make regular text 10 pixels */
    }
  </style>  
</head>
<body>
  <h1>REPORT</h1>
  <form><input type="button" id="printButton" value="Print" onclick="window.print()"/></form>
  <table border="1">
    <thead>
      <tr>
        <td>Column A</td><td>Column B</td><td>Column C</td>
      </tr>
    </thead>
    <tbody>
      <tr><td>1</td><td>2</td><td>3</td></tr>
      <tr><td>4</td><td>5</td><td>6</td></tr>
      <tr><td>7</td><td>8</td><td>9</td></tr>
    </tbody>
  </table> 
</body>
</html>
Posted by shayf | 2 comment(s)
תגים:, ,

Announcement: IronRuby Unleashed has been Released!

Good times!

Right after IronRuby RC2 was released and a bit before IronRuby 1.0 RTM is out, my book, IronRuby Unleashed, is available!

The print book is available from today on the InformIT web site (Sams Publishing’s book store) and will be available shortly on Amazon as well (and other book stores too).

IronRuby Unleashed by Shay Friedman

In short, IronRuby Unleashed contains all you need to start developing IronRuby applications. From Ruby language introduction, through the fundamentals of IronRuby programming (like implementing CLR interfaces, using generic methods, overriding CLR events and more) to using IronRuby with several different development frameworks like WPF, ASP.NET MVC, Silverlight, Ruby on Rails and more. The book also includes some advanced IronRuby topics like a chapter that explains how to develop IronRuby extensions.

 

I’d be glad to hear comments about the book, so don’t hesitate to contact me!

Shay.

Use .NET Built-in Methods to Save Time and Headaches

During our everyday programming tasks we run into several repetitive code blocks that after the 20th time you implement them become really annoying. The worst case is to re-implement these code blocks every time, and the better case is to create a central class library with helper classes and methods. However, a large amount of these tasks can be achieved easily with built-in .NET methods.

In this post I will go through several repetitive code blocks and show you how to implement them using built-in .NET method. If you want to add your suggestions, comment! I’ll add your suggestions to the post periodically.

Disclaimer: I’m sure some of the code blocks I use in the NOT Recommended sections can be written much better. These code blocks are here just for demonstration purposes.

Code Block #1 – Check string for nullity or emptiness

NOT Recommended

str = "something"
if (str == null || str == String.Empty)
{
	// Oh no! the string isn't valid!
}

Recommended

str = "something"
if (String.IsNullOrEmpty(str))
{
	// Oh no! the string isn't valid!
}

Code Block #2 – Check string for nullity or emptiness (spaces only string is invalid too)

NOT Recommended

str = "something"
if (str == null || str.Trim() == String.Empty)
{
	// Oh no! the string isn't valid!
}

Recommended (C# 4.0 Only)

str = "something"
if (String.IsNullOrWhiteSpace(str))
{
	// Oh no! the string isn't valid!
}

Code Block #3 – Copy an Array

NOT Recommended

string[] source = new string[] { "a", "b", "c" };
string[] dest = new string[3];
for (int i=0; i < source.Length; i++)
{
	dest[i] = source[i];
}

Recommended

string[] source = new string[] { "a", "b", "c" };
string[] dest = new string[3];
Array.Copy(surce, dest, source.Length);

Code Block #4 – Check if a char is a digit

NOT Recommended

char c = '1';
if (c == '1' || c == '2' || c == '3' ||
	c == '4' || c == '5' || c == '6' ||
	c == '7' || c == '8' || c == '9' ||
	c == '0')
{
	// It's a digit!
}

Recommended

char c = '1';
if (Char.IsDigit(c))
{
	// It's a digit!
}

Code Block #5 – Combine Paths

NOT Recommended

string folder = @"C:\MyDir";
string file = "MyFile.docx";
// Combine to make a path
string path = folder + @"\" + file;

Recommended

string folder = @"C:\MyDir";
string file = "MyFile.docx";
// Combine
string path = System.IO.Path.Combine(folder, file);

Code Block #6 – Get file extension out of a file path

NOT Recommended

string path = @"C:\MyDir\MyFile.docx";
string extension = path.Substring(path.LastIndexOf("."));

Recommended

string path = @"C:\MyDir\MyFile.docx";
string extension = System.IO.Path.GetExtension(path);

Code Block #7 – Get MyDocuments Path

NOT Recommended

// Probably some nasty stuff here

Recommended

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

Code Block #8 – Check if object is of a specific type

NOT Recommended

object obj = "str";
if (obj.GetType() == typeof(String))
{
	// It's a string!
}

Recommended

object obj = "str";
if (obj is String)
{
	// It's a string!
}

Code Block #9 – Set default enum value

NOT Recommended

public class MyClass
{
	private enum Sample 
	{
		A,
		B,
		C
	}
	static Sample s = Sample.B; // Set default value explicitly
	public static void Run()
	{	
		Console.WriteLine(s); // Prints B
	}
}

Recommended

public class MyClass
{
	private enum Sample 
	{
		A,
		B = 0, // Make B the default value
		C
	}
	static Sample s; // Default value will be used
	public static void Run()
	{	
		Console.WriteLine(s); // Prints B
	}
}

Code Block #10 – Check if a string starts with another string

NOT Recommended

string str = "Hello World";
if (str.Substring(0, 5) == "Hello")
{
	// String starts with Hello!			
}

Recommended

string str = "Hello World";
if (str.StartsWith("Hello"))
{
	// String starts with Hello!		
}

Code Block #11 – Convert list of items of one type to a list of items of a different type

NOT Recommended

List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
List<string> convertedList = new List<string>();
foreach (int item in list)
{
	convertedList.Add(item.ToString());
}

Recommended

List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
List<string> convertedList = list.ConvertAll<string>(Convert.ToString);

Code Block #12 – Check if a string contains a number and get the number

NOT Recommended

string str = "4";

int num = 0;
bool success = false;
try 
{
	num = Convert.ToInt32(str);
	success = true;
}
catch
{
	success = false;
}

if (success)
{
	// Do something with the number
}

Recommended

string str = "4";

int num = 0;
if (Int32.TryParse(str, out num))
{
	// Do something with the number
}

Code Block #13 – Writing a string to a file (courtesy of Yaron Naveh)

NOT Recommended

  1. const string str = "put me in a file";  
  2. const string file = @"c:\logs\file.txt";  
  3.  
  4. var fs = new FileStream(file, FileMode.Create);            
  5. var sw = new StreamWriter(fs);  
  6. sw.Write(str);  
  7.  
  8. sw.Close();  
  9. fs.Close(); 

Recommended

  1. const string str = "put me in a file";  
  2. const string file = @"c:\logs\file.txt";  
  3.  
  4. File.WriteAllText(file, str); 

Code Block #14 – Pick value if not null and a different on if it is (courtesy of Abhishek)

NOT Recommended

  1. string input = "sdfds";  
  2. string result = null;  
  3. if (input == null)  
  4. {  
  5.     result = "Input is null!";  
  6. }  
  7. else 
  8. {  
  9.     result = input;  

Recommended

  1. string input = "sdfds";  
  2. string result = input ?? "Input is null!"

This is it for now. If you have more, comment and I’ll add your suggestions to the list (with credits).

All the best,
Shay.

kick it on DotNetKicks.com Shout it
Posted by shayf | 3 comment(s)
תגים:, ,

Vote to See IronRuby in MIX10

Do you want to hear about IronRuby in the upcoming MIX10 conference? If so, make sure to vote for my IronRuby session - IronRuby - the Development Booster Machine.

In the session I plan to talk a bit about the Ruby language and its strengths and then move on and show how .NET developers can take advantage of these stengths in several different scenarios like testing, debugging and Silverlight.

YOU have the power to make it happen! Go ahead and vote!
http://visitmix.com/opencallvote/Entry?entryId=IRONRU127

See you all there,
Shay.

Posted by shayf | with no comments

A New Year, A New Beginning

2010!

It’s a new year and the wind of change is in the air. This year is a big year for me – IronRuby Unleashed will be published (est. FEB 15th), another big project is coming (more details in a few weeks) and I changed jobs!

In the last 4 years I worked at a startup named ActionBase. I learned a lot at this place and managed to work with various platforms – Office addins, WinForms, Silverlight and ASP.NET. After 4 years it was a time for a change and I decided to move on. Starting from 1/1/2010 I’m a .NET technologies consultant and instructor at Sela. My main field is dynamic languages but I’ll be doing other stuff too. I’m really thrilled and excited to get started, help customers and spread my knowledge.

If you want me to come to your company to run a course or consult, don’t hesitate to contact me. This is my job now, not a hobby anymore, so go ahead and use me! :)

I wish you all a wonderful and happy new year. May this year will be the one you were waiting and hoping for!

Peace and love,
Shay.

Posted by shayf | 1 comment(s)
תגים:

Good to Know: Built-in ASP.NET Http Handlers

Http handlers is a really elegant infrastructure allowing you to provide special behavior to specific paths in your application. You can use them to create RSS  feeds, dynamically generate images, handle requests differently and  more.

Apart from writing new http handlers, there are some built-in handlers that you can take advantage of. The built in handlers are separated into three categories (in my opinion at least): request handlers, error generators and misc. handlers.

Request Handlers

These handlers process requests in a specific way. Although these already have paths configured  for them, you can manually configure them in the web.config (or via  IIS Manager) to run on different  paths. For example, treat ABC files the same as ASPX files. There is one catch here – because ASPX, ASHX and ASMX files are dynamically compiles, you will also need to provide build configurations for the new extensions.

The handlers in this category include:

  • The regular ASP.NET page (ASPX) hander - System.Web.UI.PageHandlerFactory.
  • The generic handler (ASHX) handler - System.Web.UI.SimpleHandlerFactory.
  • The resource handler (WebResource.axd) - System.Web.Handlers.AssemblyResourceLoader.
  • The web service handler (ASMX) - System.Web.Services.Protocols.WebServiceHandlerFactory.
  • The trace handler (trace.axd) – System.Web.Handlers.TraceHandler.

The following web.config  sample enables accessing trace info via MyTrace.aaa (this is web.config configuration for IIS 7 running in Integrated  mode, in other versions or modes the configuration will be a bit different):

    <system.webServer>
      <handlers>
        <add verb="*" path="MyTrace.aaa" name="Trace-handler" type="System.Web.Handlers.TraceHandler"/>
      </handlers>
    </system.webServer>

After this is configured (and tracing is enabled as well), try navigate to MyTrace.aaa page.

    Error Generators

    These handlers generate specific http errors. You can use them to prevent access to specific files, specific extensions or folders. These error generator handlers include:

  • Forbidden – generates a 403 Forbidden http error - System.Web.HttpForbiddenHandler.
  • Not Found – generates a 404 Not Found  http error - System.Web.HttpNotFoundHandler.
  • Method Not Allowed – generates a 405 Method Not Allowed http error - System.Web.HttpMethodNotAllowedHandler.
  • Not Implemented – generates a 501 Not Implemented http error - System.Web.HttpNotImplementedHandler.

The following web.config sample prevents users from accessing all files with secret extensions. Once a user tries to access such file he or she will get a 403 Forbidden page:

<system.webServer>
  <handers>
    <add verb="*" path="*.secret" name="SecretAccess" type="System.Web.HttpForbiddenHandler"/>
  </handlers>
</system.webServer>

Try navigating to top.secret and witness the result.

    Miscellaneous

    The misc. category contains one handler, the static file handler, which can help in various  scenarios. It will present the file content without any processing. With this handler you can, for example, enable users to retrieve lkr file (no special meaning to this extension that I know of) content.

  • Static file – shows the content of a file without any processing - System.Web.StaticFileHandler.

The following  sample configures lkr files to be processed by the static file handler. To test this, create a txt file in your web application root folder, rename its extension to lkr and navigate to it.

<system.webServer>
  <handlers>
    <add verb="*" path="*.lkr" name="lkr-handler" 
              type="System.Web.StaticFileHandler" resourceType="File"/>
  </handlers>
</system.webServer>

 

All  the best,
Shay.

Share it:
Shout it kick it on DotNetKicks.com

Posted by shayf | with no comments
תגים:,

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

Posted by shayf | with no comments

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.

Posted by shayf | with no comments
תגים:,

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.

Posted by shayf | with no comments
תגים:,

My Presentation at 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

Posted by shayf | with no comments

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

Posted by shayf | with no comments

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

Posted by shayf | 2 comment(s)
תגים:,

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.

Mirror post: http://ironshay.com/post/Upcoming-Session-Riding-IronRuby-on-Rails-at-WDC-Israel.aspx

Posted by shayf | with no comments

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

Mirror: http://ironshay.com/post/Visual-Studio-Tip-Compilation-Symbols.aspx

Posted by shayf | with no comments
תגים:, , , , ,
More Posts Next page »