Ruby on Rails and Heroku is a great match! Heroku is a great platform for any startup that wants to develop fast and without spending a lot money
Heroku is a platform that allows you to think about servers as a service.
I am using Heroku with Rails (and Node.js) for a long time. But in my current startup the only servers that we have (so far) are on Heroku. It is much more easy that you don't need to think about your servers. I got much more time to handle the important stuff. It is so easy and simple that each developer can create his own server, qa servers, staging server and the production server
Heroku currently supports: Ruby, Node.js, Clojure, Java, Python and Scala. If you are looking for .NET solution you should look at AppHarbor - it is the same solution for .NET applications, I personally didn't use it - so use it on you own risk :)
Some few great thing about heroku is:
1. It is free! (if you don't expect a lot of traffic)
2. it is easy. All you need to do in order to deploy to a server is:
- $ heroku create
- $ git push heroku master
3. It is fun! every time that you create a server you get a funny name for example:
- afternoon-waterfall
- deep-mist
- empty-mist
- empty-sunrise
- furious-fog
- gentle-leaf
- morning-planet
and much more names funny names, yes you can change it by running "heroku rename"
Even if you don't need heroku now you should play a bit with it
Keep Writing, Compiling, and Debugging
Alon Nativ
Well this is an end of an era for me...
I left Conduit and starting my own startup. There are few major changes in this event
1. I am starting my own company :)
2. I decided to buy a mac.
Yes yes I know that you can't develop with .Net on a mac. After a long journey with .NET (since .NET 1.1) I have decided to leave it and write with Ruby on Rails. In the past few month I was using both .NET & Ruby and even though I am (or was) a big .NET fan I must say that my hart goes with Ruby. When I started writing in Ruby i felt that someone opened my eyes and told me the king in naked… I started to understand that in .NET I am wasting to much time on writing infrastructure for my project instead of writing the real business logic. My code becomes much shorter, easier to read, with less bugs and was written faster.
Good bye .NET it was fun…
Hello Ruby!
BTW: here is my new mac (another good reason to abandoned .NET)

Keep Writing, Compiling, and Debugging
Alon Nativ
Today we had our 1st developers meet-up @conduit.
I made a session on node.js Socket.IO and the Real-time web. You can find the slides here: http://www.slideshare.net/alonnativ/nodejs-socketio

It was fun!
Keep Writing, Compiling, and Debugging
Alon Nativ
As you know you can’t make an Ajax cross domain request. The browser block this kind of requests. To enable Cross-Origin Requests (CORS) you need to add some headers to the server response: “Access-Control-Allow-Origin” and “Access-Control-Allow-Methods”.
So I made a MVC filter that will allow cross domain calls:
public class AllowCrossDomain : ActionFilterAttribute
{
public const string AllDomains = "*";
private readonly string[] _allowMethods;
private string _allowOrigin;
public AllowCrossDomain()
: this(null, null)
{
}
public AllowCrossDomain(string allowOrigin, params string[] allowMethods)
{
_allowMethods = allowMethods;
_allowOrigin = allowOrigin;
if (string.IsNullOrWhiteSpace(_allowOrigin))
{
_allowOrigin = AllDomains;
}
if (_allowMethods == null || _allowMethods.Length == 0)
{
_allowMethods = new[] { "GET" };
}
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", _allowOrigin);
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", string.Join(", ", _allowMethods));
filterContext.HttpContext.Response.Headers.Add("Access-Control-Max-Age", "86400");
}
To use it just put it on a method on controller:
[AllowCrossDomain]
public ActionResult Index()
{
return Json(new {sample="a sample data",crossDomain="you can read it from cross domain"})
}
Simple…
A few things before you try this:
1. “Cassini” doesn’t support this kind of headers you will need to run it on IIS \ IIS Express
2. CROS are supported only by modern browsers FF 3.6+ all chrome browsers, modern smart phones…
3. In order to enable it on IE you need to change the security settings:

you can read more about CROS here: http://www.w3.org/TR/cors/
Keep Writing, Compiling, and Debugging
Alon Nativ
Recently I was asked question how to get the image or the comment when using Facebook FQL API to get notification. http://developers.facebook.com/docs/reference/fql/notification/
It is very easy to make an application that will show the basic notification like that looks like:
“David has comment on your link”
“James liked your photo”
You can see more samples at this link: http://www.facebook.com/notifications.php
Well there is no documentation of how to do it (and there is not even a clean way to do it) there is no column that points the the original link\image\comment.
So… do we give up? of course not!
If we will look at the format of the “herf” we will see that there is a param called “story_fbid” (sometimes it is called “fbid” depends on the type of the notification)
http://www.facebook.com/permalink.php?story_fbid=178287412229452&id=100001445838266\
Now all you need to do is take the id and call the graph API https://graph.facebook.com/{ID}?access_token=XZY for more information about the graph API visit (http://developers.facebook.com/docs/reference/api/)
That’s it.
Now you can improve your Facebook notification
Keep Writing, Compiling, and Debugging
Alon Nativ
Just wanted to create a web logger in MVC. The idea is the same as Google analytics that a client will send data from the "client side" to the server. The server will save the data and return “Image Pixel” just like any other normal web logger. In order to do that I have created an ImagePixel ActionResult.
The server logger method will look something like that:
public ActionResult Logger(string trackingData)
{
Log(trackingData);
return new ImagePixelResult();
}
The ImagePixelResult is defined like this:
public class ImagePixelResult : ActionResult
{
private static readonly byte[] Imgbytes = Convert.FromBase64String("R0lGODlhAQABAIAAANvf7wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase httpResponse = context.HttpContext.Response;
httpResponse.ContentType = "image/gif";
httpResponse.AppendHeader("Content-Length", Imgbytes.Length.ToString());
httpResponse.Cache.SetLastModified(DateTime.Now);
httpResponse.Cache.SetCacheability(HttpCacheability.NoCache);
httpResponse.Expires = -1500;
httpResponse.Cache.SetNoStore();
httpResponse.ExpiresAbsolute = DateTime.Now.AddYears(-1);
httpResponse.BinaryWrite(Imgbytes);
}
}
Clean and simple :)
Keep Writing, Compiling, and Debugging.
Alon Nativ
Just added Google +1 to my blog.
The +1 is the Google "like" button. It should help Google to find what kind of pages people are interested in and improve the search experience.
In order the add the +1 button go to the documentation add to your page:
<!-- Place this tag in your head or just before your close body tag -->
<script type="text/javascript" src="http://apis.google.com/js/plusone.js"></script>
<!-- Place this tag where you want the +1 button to render -->
<g:plusone></g:plusone>
In some pages (this blog platform for example) you can’t add this code so you must use HTML5 style (I think it is better)
<div class="g-plusone" data-size="standard" data-count="true"></div>
You can read more on how to do it in here
So +1 my blog
Keep Writing, Compiling, and Debugging
Alon Nativ
Just made a small autocomplete textbox that search a user friends from Facebook.
it is a pretty simple implementation that allow the user to search for his friends. In order to use it you will need to get a valid access_token from Facebook (but you can read more in how to use the Facebook graph API at http://developers.facebook.com/docs/reference/api/ – or get a sample one).
There are a few tricks in the implantation
So here is the code
1: <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
2: <script src="../../Scripts/jquery-ui.min.js" type="text/javascript"></script>
3: <script type="text/javascript" src="../../Scripts/jquery.autocomplete.min.js"></script>
4: <script>
5:
6: //Get the user image from the user id
7: function getImage(id) {
8: return "http://graph.facebook.com/" + id + "/picture?type=square";
9: }
10:
11: var accessToken = "PUT A VALID ACCESS TOKEN HERE INORDER TO MAKE IT WORK";
12: $(document).ready(function () {
13: $("#example").autocomplete("https://graph.facebook.com/me/friends?access_token=" + accessToken + "&callback=?", {
14:
15: width: 250,
16: height: 400,
17: max: 8,
18: dataType: 'jsonp',
19: cacheLength: 10,
20: minChars: 1,
21: parse: function (data) {
22: var rows = new Array();
23: data = data.data;
24: for (var i = 0; i < data.length; i++) {
25: rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
26: }
27: return rows;
28: },
29: formatItem: function (data, i, n, value, text, a, b, c, d) {
30: var x = getImage(data.id);
31: return "<div class='test2'><img class='test' width='32px' height='32px' src='" + x + "'></img><span>" + data.name + "</span></div>";
32: },
33:
34: }
35: ).result(function (evnet, item) {
36: alert(item.id);
37: });
38: });
39: </script>
40: Write a friend name
41: <input id="example" />
The final result will look something like that:

All you need to do now is change the style so it will fit in your site
You can read more about jquery autocomplete plugin here: http://docs.jquery.com/Plugins/Autocomplete/autocomplete
Keep Writing, Compiling, and Debugging
Alon Nativ
A few weeks ago redgate announced that the lovely .NET reflector is going to cost money, that was a very sad news for every .NET developer out there.
But the good news are that a few days after JetBrains announced that they are releasing there own reflector called dotPeek. I personally hate the name but It is a great tool!
Much faster great UI and the best thing it has all of the ReSharper shortcuts!
So even if you decided to pay for the .NET reflector I think that you should throw it away and start using dotPeek
The king (.NET reflector) is dead. Long live the King (dotPeek)!
Keep Writing, Compiling, and Debugging.
Alon Nativ
Hi,
I wanted to create an application that will allow users to pick there own urls just like twitter (http://twitter.com/anativ). It seems that there is a very simple way for doing it using MVC.
I saw many solution to this problem that catch the 404 and handle it. I personally didn’t like that solution it was too complicated and had many small issues that you need to solve.
Here is the sample controller that handle the custom urls:
public class UsersController : Controller
{
private static HashSet<string> _pages = new HashSet<string>();
public ActionResult Add(string id)
{
_pages.Add(id);
string msg = "Page added " + id;
if (string.IsNullOrWhiteSpace(id))
{
msg = "The site name can't be empty...";
}
ViewBag.Message = msg;
return View();
}
public ActionResult Get(string id)
{
if (_pages.Contains(id))
{
ViewBag.Message = "Welcome " + id;
return View();
}
return RedirectToRoute("Error","NotFound");
}
}
The idea is to support customize urls without losing the default routing mechanism (controller/action/id).
First try:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"UserPage", // Route name
"{id}", // URL with parameters
new { controller = "Users", action = "Get" } // Parameter defaults
);
So how do you do that? lets see the problem… if we create a “UserPage” route like the example above we will never catch it because the “Default” MVC route will catch all the patterns before it. If we will change the order that the “UserPage” route will be before the default route the “UserPage” route will catch everything before the “Default” route.
Lets see how we can solve the problem… In order to do that we need to understand what is the job of the “Default” route. The MVC “Default” route catches 3 types of request:
- Empty request: the empty request –> handled by /Home/Index
- Controller + method –> handled by {controller}/{index}
- Controller with empty request –> handled by {controller}/Index
So lets split the controller into rules that will answer all types of the requests above:
for rule number 1 we will create a rule:
routes.MapRoute(
"Home", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
for rule number 2 we will create a rule:
routes.MapRoute(
"Controller_Action", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { id = UrlParameter.Optional } // Parameter defaults
);
This rule is almost the same as the “Default” MVC route the only deference is the “Parameter defaults” section this rule must get a controller name and an action name.
Now to solve number 3 we need to do a small trick. I created a custom rule for each controller in my project – you can do it manually or you can do it with reflection. I added the method below to my global.asax file it runs on every controller that I have in my project and creates a rule for it (controller/Index).
private static IEnumerable<Route> GetDefaultRoutes()
{
//My controllers assembly (can be get also by name)
Assembly assembly = typeof (HomeController).Assembly;
// get all the controllers that are public and not abstract
var types = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof (Controller)) && t.IsPublic && !t.IsAbstract);
// run for each controller type
foreach (var type in types)
{
//Get the controller name - each controller should end with the word Controller
string controller = type.Name.Substring(0, type.Name.IndexOf("Controller"));
// create the default
RouteValueDictionary routeDictionary = new RouteValueDictionary
{
{"controller", controller}, // the controller name
{"action", "index"} // the default method
};
yield return new Route(controller,routeDictionary, new MvcRouteHandler());
}
}
Now we will need to do is add the call for this method in the RegisterRoutes method just above the last rule
foreach (var route in GetDefaultRoutes())
{
routes.Add(route);
}
That’s it. Now the global.asax looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Home", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Controller_Action", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { id = UrlParameter.Optional } // Parameter defaults
);
foreach (var route in GetDefaultRoutes())
{
routes.Add(route);
}
routes.MapRoute(
"UserPage", // Route name
"{id}", // URL with parameters
new { controller = "Users", action = "Get" } // Parameter defaults
);
}
Now I can create an url per user and save the default routing logic.
If you don’t want to apply the default rule on all of your controllers you can add an attribute that will “ignore” the controller or change the default action method from “Index” to something else.
Keep Writing, Compiling, and Debugging
Alon Nativ
Hi,
I am creating windows services using Topshelf for a while and I forget how “hard” (not that hard but harder) it was to create a windows service without Topshelf.
Topshelf is a lightweight framework for building Windows services using the .NET framework. The idea is to create a console application and “publishing” it as a service with command line. No more dedicated window service project and an installer.
So, how does it work? here is a simple example:
1. Create new “console application”
2. Create your service class
public class MyService : IService
{
public void Start()
{
Console.WriteLine("Running...");
}
public void Stop()
{
Console.WriteLine("Done!");
}
}
3. write something like the code below: (here we are using topshelf)
static void Main(string[] args)
{
RunConfiguration cfg = RunnerConfigurator.New(x =>
{
x.ConfigureService<MyService>(s =>
{
s.Named("MySampleService");
s.HowToBuildService(service => new MyService());
s.WhenStarted(service => service.Start());
s.WhenStopped(service => service.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("The service");
x.SetServiceName("MySampleService");
});
Runner.Host(cfg, args);
}
That’s it!
now you have a console application that will run the Start() method when you start it and run the Stop() method when you stop it. Very comfortable when you are in the development process and you want to run or debug your service.
Now to install it or uninstall run the command line:
myservice.exe install
myservice.exe uninstall
Enjoy your new service, I personally wrapped Topshelf that I wont need to copy the code above every time:
I created an interface called IService
public interface IService
{
void Start();
void Stop();
}
And a simple method called ServiceCreator
public static void ServiceCreator<T>(string name, string displayName, string description, string[] args) where T : IService, new()
{
RunConfiguration cfg = RunnerConfigurator.New(x =>
{
x.ConfigureService<MyService>(s =>
{
s.Named(name);
s.HowToBuildService(service => new T());
s.WhenStarted(service => service.Start());
s.WhenStopped(service => service.Stop());
});
x.RunAsLocalSystem();
x.SetDescription(description);
x.SetDisplayName(displayName);
x.SetServiceName(name);
});
Runner.Host(cfg, args);
}
Now my main looks like this:
static void Main(string[] args)
{
ServiceCreator<MyService>("Name", "Display Name", "desciption", args);
}
Hope it will help you to create and debug windows services
Update: MAY-2012
The API has changed a bit, now in order to install the server you need to run "{your_exe} install" and to uninstall "{your_exe} uninstall"
Keep Writing, Compiling, and Debugging
Alon Nativ
Hi,
A few days ago I wanted to use attributes to make my code easier. The problem was that It cost me in performance and I couldn’t afford it at this point of the code, so I decided to use expression to optimize my code.
Lets say we want to make a [DefaultValue] attribute that will set a default value for a property
1: public class Person
2: {
3: [DefaultValue("Alon")]
4: public string Name { get; set; }
5: [DefaultValue("Nativ")]
6: public string LastName { get; set; }
7: [DefaultValue("http://blogs.microsoft.co.il/blogs/alon_nativ/")]
8: public string Blog { get; set; }
9:
10: public override string ToString()
11: {
12: return string.Format("Name: {0}, LastName: {1}, Blog: {2}", Name, LastName, Blog);
13: }
14: }
The Attribute definition:
1: [AttributeUsage(AttributeTargets.Property,AllowMultiple = false,Inherited = true)]
2: class DefaultValue : Attribute
3: {
4: public DefaultValue(string key)
5: {
6: Value = key;
7: }
8:
9: public string Value { get; set; }
10: }
Now we will use it like that:
Option 1: The simple way to use the attributes is by using reflection:
1: var person = new Person();
2: IEnumerable<PropertyInfo> props = typeof(Person).GetProperties().Where(p => p.GetCustomAttributes(true).Where(a => a is DefaultValue).Any());
3: foreach (var propertyInfo in props)
4: {
5: DefaultValue defaultValue = propertyInfo.GetCustomAttributes(typeof(DefaultValue), true)[0] as DefaultValue;
6: propertyInfo.SetValue(person, defaultValue.Value, null);
7:
8: }
9: Console.WriteLine(person);
The code above will work but it is not optimized, of course we can cache the PropertyInfo for each object type to improve performance but it is not good enough.
So I decided to use expression trees to optimize the above code.
Option 2: The idea is to create a static object per type. We can do it by using generic static class this will make sure that each type will compile only once.
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Linq.Expressions;
5: using System.Reflection;
6:
7: namespace Alon.Samples
8: {
9: /// <summary>
10: /// Init object with default values
11: /// </summary>
12: /// <typeparam name="T">The object that will be init</typeparam>
13: public static class Initializer<T> where T : new()
14: {
15: private static Action<T> _initFunction;
16:
17: static Initializer()
18: {
19: //The method that extract the value accurding to the attribute key
20: MethodInfo method = typeof(Initializer<T>).GetMethod("GetValue", BindingFlags.Static | BindingFlags.NonPublic);
21: var param = Expression.Parameter(typeof(T), "TObject");
22: //The expressions that we want to run
23: List<Expression> exps = new List<Expression>();
24: //Get all the properties that has DefaultValue attribute
25: var props = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(true).Where(a => a is DefaultValue).Any());
26: foreach (PropertyInfo propertyInfo in props)
27: {
28: MemberExpression prop = Expression.Property(param, propertyInfo);
29: DefaultValue defaultAttribute = propertyInfo.GetCustomAttributes(typeof(DefaultValue), true)[0] as DefaultValue;
30: ConstantExpression ce = Expression.Constant(defaultAttribute.Value);
31: MethodCallExpression call = Expression.Call(method, ce);
32: BinaryExpression assign = Expression.Assign(prop, call);
33: exps.Add(assign);
34: }
35: //If we dont have any attributes we will create an empty block (otherwise we will get an exception)
36: BlockExpression blockExpression = exps.Count > 0 ? Expression.Block(exps) : Expression.Block(Expression.Empty());
37: Expression<Action<T>> lamExp = Expression.Lambda<Action<T>>(blockExpression, param);
38: //Compile the method :)
39: _initFunction = lamExp.Compile();
40: }
41:
42: private static string GetValue(string key)
43: {
44: return key;
45: }
46:
47: public static void Init(T obj)
48: {
49: _initFunction(obj);
50: }
51: }
52: }
Now to use it all we need to do is something is:
1: var p = new Person();
2: Initializer<Person>.Init(p);
3: Console.WriteLine(p);
After I did that I wanted to make sure that I improved the performance so I tested the reflection why vs the expression way.
I run each solution 10000 times (after caching the PropertyInfo) and the results are (on my laptop)
Reflection: 2900 Milliseconds, Expression trees 30 Milliseconds – about 100 times faster
Here is the test code:
1: static void Main(string[] args)
2: {
3: List<PropertyInfo> props = typeof(Person).GetProperties().Where(p => p.GetCustomAttributes(true).Where(a => a is DefaultValue).Any()).ToList();
4:
5: var obj = new Person();
6: SetValues(obj, props);
7: Stopwatch sw1 = Stopwatch.StartNew();
8: for (int i = 0; i < 100000; i++)
9: {
10: obj = new Person();
11: SetValues(obj, props);
12: }
13: sw1.Stop();
14: Console.WriteLine(sw1.ElapsedMilliseconds);
15:
16: sw1 = Stopwatch.StartNew();
17: for (int i = 0; i < 100000; i++)
18: {
19: obj = new Person();
20: Initializer<Person>.Init(obj);
21: }
22: sw1.Stop();
23: Console.WriteLine(sw1.ElapsedMilliseconds);
24:
25: }
26:
27: public static void SetValues(Person myObj, IEnumerable<PropertyInfo> props)
28: {
29: foreach (var propertyInfo in props)
30: {
31: DefaultValue tran = propertyInfo.GetCustomAttributes(typeof(DefaultValue), true)[0] as DefaultValue;
32: propertyInfo.SetValue(myObj, tran.Value, null);
33: }
34: }
I think that there are many cases that we want to use attributes to make our code easier to read and write and by optimizing it with expression trees we can enjoy a clean code and not paying for it in performance.
BTW: After I did that I created a custom serializer on the same idea (just need to change the Initializer that will return values instead of set the object properties
Keep Writing, Compiling, and Debugging
Alon Nativ
Hi all,
My name is Alon and this is my first post at my new home blogs.microsoft.co.il. So far it looks like a nice place to place my blog.
I am going to write mainly about: .Net, C#, ASP.NET, Sql. and development in general.
See you at Tech-ed 2010
Keep Writing, Compiling, and Debugging
Alon Nativ