#!/usr/bin/env ruby

$VERBOSE = true

$: << ".." << "../lib"

# This sample demonstrates a lot of rubydotnet features
# including: instantiating objects from .net classes, accessing
# the features on the objects, implementing .net interfaces in ruby,
# .net delegates that call ruby. It also shows how to include C#
# directly in the ruby script


require 'dotnet'




# Lesson 1: Instantiating and using objects

arrayList = System::Collections::ArrayList.new

# The .net namespaces map to ruby modules
# so the usual trick for avoiding the long fully
# qualified names work fine

include System::Collections

arrayList2 = ArrayList.new

1000.times { |i| arrayList2.add(i*i) }

puts "arrayList2[10] = #{arrayList2[10]}"




# Lesson 2: Using C# (or VB.net or JScript) directly
# within a ruby script.

# cs_compile has vb_compile and js_compile cousins for
# Visual Basic .net and JScript.net

cs_compile <<-EOF
	using System;

	public delegate void MyDelegate(string arg);

	public class MyClass {

		public static string aProperty { get { return "propValue"; } }

		public static event MyDelegate myEvent;

		public static void fireMyEvent(string arg) {
			if (myEvent != null)
				myEvent(arg);
		}
	}
EOF

puts "MyClass.aProperty = #{MyClass.aProperty}"



# Lesson 3: Using events and call backs

MyClass.add_myEvent(proc { |s| puts "proc1 called with s=#{s}" })
MyClass.add_myEvent(proc { |s| puts "proc2 called with s=#{s}" })

MyClass.fireMyEvent("hello world")



# Lesson 4: Implementing .net interfaces with a ruby object
# and using cs_eval to evaluate a small C# fragment. Notice
# the same can be achieved with vb_eval or js_eval for
# VisualBasic.net and JScript.net

class MyDisposableRubyClass
	implements System::IDisposable

	def Dispose	
		puts "Dispose called"
	end
end

myDisposableInstance = MyDisposableRubyClass.new

# cs_eval(script, *args) - script must return a value (e.g. null). 
# args are available as a System::Object[] array
cs_eval("((IDisposable)args[0]).Dispose(); return null;", myDisposableInstance)



# Copyright (C) 2003 Thomas Sondergaard
# rubydotnet is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.