Route by name, Not by id.


I'm using Ubuntu 12.04 64bit with RubyMine 4.5.4Ruby 1.9.3Rails 3.2.8.


It's more a feature than a problem :P
I wanted to access my model by name and no by id for example:

By id:         |     By name:  
/friend/1     |   friend/john



By default controllers use the following code to get the required instance from the database:

@friend = Friend.find(params[:id])
respond_to do |format|
    format.html # show.html.erb

so first thing to try is:
@friend = Friend.find_by_name(params[:name])


So next i found map.connect...

map.connect 'friend/:name', :controller => 'friends', :action => 'show'
I found out that map.connect only available in rails 3.2 and was deprecated in rails 3.x 



Have you ever heard of to_param ?
I just needed to add the following to my model (friend.rb):

def to_param
And in the controller (friend_controller.rb):

@friend = Friend.find_by_name(params[:id]) 

No need to change anything in routes.rb!

ActiveAdmin fix:

For those of us who uses ActiveAdmin gem like me, there is another fix to be able to edit friends by name.
Add the following to your friends.rb: (ActiveAdmin.register Friend do)

before_filter :only => [:show, :edit, :update, :destroy] do
  @friend = Friend.find_by_name(params[:id])


Ruby on Rails GemNotFound / FetchError / connection attempt failed!

I didn't post for a very long time!
I had alot of sketches though but didn't had the time to finish and publish them..

But i hope to come back now with more posts!
Also i'm gonna stick to a new format in my posts thati think is better to read. maybe i'll also update old posts to this format.

I just started learning Ruby on Rails few weeks ago and ran into a very weird problem.


I'm using Windows 7 64bit with RubyMine 4.5.1, Ruby 1.9.3, Rails 3.2.

I was able to install all this working environment on my Desktop but not on my Laptop..


I encounterd the following errors on cmd & RubyMine:
C:\Users\Danpe>gem install rails
WARNING:  Error fetching data: Errno::ECONNREFUSED: No connection could be made
because the target machine actively refused it. - connect(2) (http://rubygems.org/latest_specs.4.8.gz) 
`block in materialize': Could not find rake- in any of the sources (Bundler::GemNotFound)

Fetching source index for `http://rubygems.org/`  Could not reach rubygems repository `http://rubygems.org/`  Could not find gem 'rspec-rails (>= 2.0.0.beta.22, runtime)' in any of the gem sources.

 ERROR: http://rubygems.org/ does not appear to be a repository       ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
 Errno::ETIMEDOUT: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed
because connected host has failed to respond. - connect(2)           (http://rubygems.org/yaml)
 I got all these kind of weird errors!


 so i started looking around the web and around my PC network settings.

I double checked my Internet Options to see that there is no proxy enabled, and there was none!
I opened cmd and typed SET to see my Environment Variables:

 As you can see there is an Environment Variable for HTTP_PROXY...


Go to Start (WinKey) type Edit the system environment variables and you'll get this window:

Click on Environment Variables and then remove HTTP_PROXY from System Variables!

Make sure you reopen cmd and RubyMine :)


Android Recursively change fonts ?

I think it's time to start blogging about android :)

I just got my Samsung Galaxy S2 a week ago and it's been so fun playing with !

So today i'm gonna show how to use custom fonts, There is a nice artical about Styling TextViews in here: Customize Android Fonts

You can see there that they are accessing a TextView using it's ID and then changing the font of the spacific TextView.
TextView txt = (TextView) findViewById(R.id.custom_font);  
Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf");  
Now that can be a pain in the a** if you have alot of TextViews in your page...
So iv'e created a Recursive that changes all TextView's & Button's fonts on the same page :)
void UpdateFonts(ViewGroup parent, Typeface font) {
  for (int i = 0; i < parent.getChildCount(); i++) {
   View child = parent.getChildAt(i);
   if (child instanceof ViewGroup) {
    UpdateFonts((ViewGroup) child, font);
   } else if (child != null) {
    if (child.getClass() == TextView.class) {
     ((TextView) child).setTypeface(font);
    } else if (child.getClass() == Button.class) {
     ((Button) child).setTypeface(font);
This is an eay recursive that loops through all children of a parent element and changes all of his children's fonts.
You can call it like that if you want all page:
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/choco.ttf");
ViewGroup rootView = (ViewGroup) findViewById(android.R.id.content).getRootView();
UpdateFonts(rootView, font);
Hope you enjoyed my first Android article :)
See you next time ;)


Fliping lots of text lines... ?


I'm using Windows 7 64bit with Notepad++ 5.9.3, Visual Studio 2010 Ultimate, C# .NET 2.0.


So i face a really annoying problem today,
I had an array with 400 lines written in C#.
The problem is that, the list was reversed from the order i wanted.


The array i have:

The array i need:

Like i said it's a 400 lines array...


I really needed this reversed, i tried Notepad++ with several plugins like TextFX without any success, i actually found out that it's possible to do it by recording a Macro in the Notepad++, but it's like not my thing.

So i used my best friend! C# :)

I'll make a quick explanation of what i'm doing and then just paste the code.


So i made a Console App that gets a file path from the application arguments.
It reads all the lines and pushs them into a Stack then writes it to a new file using Pop :)

Heres the code: (Just compile and it works)

class Program
 static void Main(string[] args)
  if (args == null)
   Console.WriteLine("args is null"); // Check for null array
   if (args.Length == 0)
    Console.WriteLine("Please enter a file path to reverse in the console arguments.");
    string p = args[0];
    string o = Path.GetDirectoryName(p) + Path.PathSeparator + Path.GetFileNameWithoutExtension(p) + "Reversed" + Path.GetExtension(p);
     String line;
     Stack< string > lines = new Stack< string >();
     // Create an instance of StreamReader to read from a file.
     // The using statement also closes the StreamReader.
     using (StreamReader sr = new StreamReader(p))
      // Read and display lines from the file until the end of
      // the file is reached.
      while ((line = sr.ReadLine()) != null)
     // create a writer and open the file
     // The using statement also closes the StreamWriter.
     using (TextWriter tw = new StreamWriter(o))
      // write a line of text to the file
      while (lines.Count > 0)
    catch (Exception e)
     // Let the user know what went wrong.
     Console.WriteLine("The file could not be read/written:");


Simple cross drawing :)


Here is a simple cross drawing
using System.Drawing;
//Create graphics object to handle drawings
Graphics gfx = picBox.CreateGraphics(); 
//Get client retangle from out PictureBox that we want the cross in
Rectangle rc = picBox.ClientRectangle; 
//Create a new pen to draw the cross
Pen RedPen = new Pen(Color.Red);
int Size = 10
//Draw the actual cross 
gfx.DrawLine(RedPen, rc.Width / 2, rc.Height / 2 + Size, rc.Width / 2, rc.Height / 2 - Size);
gfx.DrawLine(RedPen, rc.Width / 2 + Size, rc.Height / 2, rc.Width / 2 - Size, rc.Height / 2);


Run application on Windows Startup


In this post i'm gonna show you how to run an application on Windows Startup by adding the application to the registry in the right place.

First of all add this using:
using Microsoft.Win32;

So we can accesss the Registry of the computer.
Define a RegistryKey:

// The path to the key where Windows looks for startup applications
RegistryKey rkApp=Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",true);

You can change the CurrentUser to LocalMachine if you want your application to run on startup for all users.

Create the registry key and close the registry key handler:

rkApp.SetValue("notepad", @"C:\WINDOWS\system32\notepad.exe"); // Make notepad run on startup                 
rkApp.Close(); //Close the RegistryKey handler
Now notepad will always run when you turn on your PC :P

Nice registry locations can be found here: Registry Autostart Locations

Have fun tweaking the registry :)


Danpe Presents: C# HTML Builder

Having trouble building HTML with C# ?

Have you ever used something like this to generate HTML tables for example:
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 32; i++)
    sb.AppendLine("<tr class=\"row\">");
    sb.AppendLine("<td>" + i + "</td>");
    sb.AppendLine("<td> </td>");
    sb.AppendLine("<td> </td>");
    sb.AppendLine("<td> </td>");
return sb.ToString();
(As you see even the SyntaxHighlighter couldn't handle all of those Escape Characters)

I'm pretty sure you did :)
And you probably you hate all of those Escape Characters! (/" " +)
And doing sb.AppendLine all the time and doing all this formating!
Imagine you have 50 lines?? OMG...

So anyway i made an Application to make you'r life easier :)

Simple as it looks :)
Download Here: C# HTML Builder