Runtime Code Compilation

This is an interesting concept. .NET framework comes with all the necessary tools to allow you to compile C# code at run time. You might find this feature useful if you are developing an application where you need to evaluate C# or any other .NET language at runtime. Here is an example how you could accomplish this:

void Main()
{
    //Initializes a new instance of the CodeDomProvider class.
    CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");
    //Settings for the CodeDomProvider 
    CompilerParameters compParam = new CompilerParameters();
    compParam.ReferencedAssemblies.Add("System.dll");
    compParam.GenerateExecutable = false;
    compParam.GenerateInMemory = true;	
    //the source code will be evaluated at runtime.
    string[] file = new string[1];
    file[0] = @"c:\Temp\source.cs";
    CompilerResults result = codeDomProvider.CompileAssemblyFromFile(compParam, file);
    if (result.Errors.Count <= 0)
    {
        Assembly a = result.CompiledAssembly;
        object o = a.CreateInstance("RunTimeCompile.MyClass");
        Type type = o.GetType();
        MethodInfo mi = type.GetMethods()
            .Where<MethodInfo>((x) => x.Name == "DisplayMessage")
            .Single<MethodInfo>();
        mi.Invoke(o, null);
    }
    else
    {
        foreach(CompilerError err in result.Errors)
            Console.WriteLine(err.ErrorText);
    }
}

the source code that will be evaluated at runtime.

namespace RunTimeCompile
{
    public class MyClass
    {
        public void DisplayMessage()
        {
            System.Console.WriteLine("Hello World");
        }
    }
}

09/30/10

Set, Action => lambda

I recently to implemented a method that would allow one to execute any arbitrary piece of code and specify a time out period. Thanks to lambda expressions, this is now easier than walking in the park. Check out the sample code below:

static bool Execute(Action action, TimeSpan timeout)
{
    bool result = true;
    AutoResetEvent autoResetEvent = new AutoResetEvent(false);
    ThreadPool.QueueUserWorkItem((o) =>
        {
            action.Invoke();
            autoResetEvent.Set();
        }
    );
    if (!autoResetEvent.WaitOne(timeout))
        result = false;
    return result;
}

And this is how you would execute it

Execute(() => Console.WriteLine("test"), new TimeSpan(0, 5, 0));

09/23/10

Roll out your own twitter api!

Being frustrated with the twitter gem, and a few other gems I have tried, I couldn’t find the one that satisfied my needs. All I needed was get the most recent updates from my twitter account and display it on my personal site. Most gems provided way too much functionality that I did not care for.

Here is a small ruby app that I wrote just to fetch twitter updates in a few lines of code. This particular code uses no authorization such as oAuth

require 'rubygems'
require 'json'
require 'net/http'

class TwitterAPI
  @@URL = 'http://api.twitter.com/1/statuses/user_timeline.json?'
  def initialize(options)
    @tweets = []
    
    options.each do |k, v|
      @@URL << "#{k}=#{v}&"
    end
    
    #remove the last &
    @@URL.chop
    
    resp = Net::HTTP.get_response(URI.parse(@@URL))
    data = resp.body
    result = JSON.parse(data)
    
    #Since I am only interested in the tweet, I only collect the value of text element.
    result.each do |item| 
      item.find {|k, v| @tweets << v if k == "text" }
    end
  end
  
  def each
    @tweets.each {|t| yield t}
  end
end

And this how you would call it

search = TwitterAPI.new :screen_name => 'username', :count => 2, :include_rts => 1

search.each do |tweet|
  puts tweet
end

09/21/10

FunctMetaL, Rails 3.0, Rough Cuts

It’s been a while since I have posted any new updates here… Recently putting quite of bit of time into the redesign of functmetal.com. I should be able to publish it soon. Also investing a lot of my time getting up to speed with Rails 3.0.

A few of my favorite roughcuts that I am trying to keep up with:

08/31/10