Overcoming Rails Beginners Paradox: Part 1

What is Rails Beginners Paradox?

Well, if you are one of those guys who wanted to create a startup or build your own web application and went with Ruby on Rails instead of purchasing all those expensive Microsoft and Java tools, libraries and services out there (although being a Microsoft / Java expert), but after a point in time you are realizing that you are googling more often than you actually code, and considering whether or not to go ahead with Rails? (Phew.. that was long!) You my friend, are under the Rails Beginners Paradox!

It’s actually not as bad as it sounds. Hey, I was stuck in one too!

Anyways, after I got over the honeymoon stage with Rails and found that it wasn’t so fine and dandy, I found this blog post by Rob Yurkowski explaining why Rails is not for beginners. (Go ahead – read it)

If you feel like he is talking directly to you, well.. actually he is. You’ve got to change your plan of attack.

Here are my suggestions (I’ll be covering this in parts, so here.. this is part 1) -

Procurement

We always need the right culinary tools to make the perfect dish (says the guy who can barely make coffee!). Like Rob points out, the main issue with us all is, we want to run 100 meters race before we can barely crawl. We want to learn Rails and build our web application, make money and get rich so badly, that we forget the main piece – learning Ruby AND Rails effectively!

In my previous post, I talked about the online courses, screencasts etc that are available out there. In this section, I’ll tell you what books you need, in order to master Ruby. (The books listed below are the ones I bought. It’s up to you whether you want to buy / download them or not)

  • The Ruby Programming language by David Flanagan and Yukihiro Matsumoto – For those of you who didn’t already know this – Yukihiro Matsumoto (commonly known as Matz) is the one who originally designed and developed the Ruby programming language, and David Flanagan is a great author – I’ve read his Javascript books. This book starts from the extreme basics and talks about Ruby in detail
  • Eloquent Ruby by Russ Olson – I don’t know a lot about Russ Olsen (you can google it yourself), but this book is absolutely awesome! It really makes you write Ruby code eloquently. Having finished this book, you can consider yourself to be a Ruby Ninja!
  • Practical OO Design in Ruby by Sandi Metz – From design patterns to interfaces to tips and tricks to improving performance by reducing cost, this book will make you a Ruby Sensei! Yes – you will be a master and you’ll be able to go teach others.
Y U NO TALK ABOUT RAILS?

Y U NO TALK ABOUT RAILS.. RIGHT?

Rails – Yes. Here -

  • Ruby on Rails by Michael Hartl – I actually have RoR 3, but you can actually go with later versions (as a lot of things seem to have changed with Rails 4 and Ruby 2). This book is perfect for beginners who want to start Rails. From basic MVC structure to a fully functioning app (like twitter), it talks about every aspect (including Test Driven Development – TDD)
  • Advanced Rails by Brad Ediger – This book starts with Rails plugins and walks you through the “real” advanced Rails. From DB load balancing to securing your application from SQL injection attacks to localization, it tells you how everything is done in bigger projects.
  • Enterprise Rails by  Dan Chak – Obviously after finishing the Advanced Rails book, you’ll be thirsty to kick the world’s ass with your Rails application (Please go right ahead!).  But before we do anything “enterprise”, the enterprise will look at you like you need to have some street cred. You can gain that by looking over the Enterprise Rails book. From big data to scalability to APIs, this book covers em all and tells you how to do it well.
  • Rails Cookbook by Rob Orsini – Because cooking isn’t complete without a cookbook. I gazed over this book and bought it because it covered some pretty cool tips and tricks to overcome some complex problems. Flip over a few pages and see if it interests you, if it does – consider getting it.

Yay, I’m done with my book suggestions!! (Now you’re in a different paradox, right? :P) Like I said, the books I’ve mentioned are completely suggestions and it’s upto you whether or not to get them.

I found them really valuable and they made me absolutely confident about choosing Ruby on Rails as the platform to build my web application on, even though I come from the .NET world . I know I’ve invested a couple hundred bucks. But hey, it’s better than buying some cheap 3rd party library right? I can now take over the planet with my RoR knowledge and experience! (Oh, and the precious hours too!)

Anyways, if you are having this paradox and wondering if you’ve made a bad decision by switching to Rails as a beginner, please consider what I said and take a little effort. It’ll be absolutely worth it.

Happy RoR programming and good luck!

 

From a .NET Expert to a Rails Noob

Dear .NET – You’ve been an excellent development platform. Thanks to corporate America, I got to ride business class – not only flights but with your Visual Studio 2012 Ultimate (funny, it actually costs as much as a business class ticket to the other side of the planet!), Sharepoint, TFS and other sweet tools you’ve got to offer. But when it comes to start ups and cool things out there, you’re like getting married to a rich old woman who loves to go shopping every weekend (that’s a terrible comparison, I know!) and it’s hard to turn away from other good tools in the other side of the developer world.

I was introduced to Ruby on Rails recently. Although it was a bit odd initially, coming from a world with ; (semi-colons). It was pretty hard to wrap my head around some of the loosely typed syntax. Nevertheless, I’ve started to realize the full potential (Or atleast 80%) of what Rails can do and would like to explore it to the fullest.

Although there are lots of good resources out there for Rails. I’d like to blog about the teensy-weeny information I was able to gather as part of my ongoing Rails expedition.

To begin with, I started with these resources -

  • Rails for Zombies (http://railsforzombies.org/)
    • Some of us would have seen this guy from the MVC videos from way back when. Gregg Pollack – He is absolutely phenomenal. After a couple of screencasts – I was like “Whaaat?? Did you just cover MVC, CRUD and Queries (LINQ as we call in the .NET world)?? Is it that simple??”
  • CodeSchool (http://www.codeschool.com/)
    • Having gotten through 50% of Rails for Zombies, I automatically got a Pro subscription with CodeSchool (which teaches Rails from the basics with it’s sweet web editor) and has more Gregg Pollack tutorials
  • RailsCasts (http://railscasts.com/)
    • Just when you think you’ve seen it all. You were told about this guy who does these awesome screencasts about the latest on Rails, Javascript libraries and what not. Another Pro subscription!
  • CodeSchool TV (https://www.youtube.com/user/CodeSchoolTV)
    • CodeSchool’s youtube channel FTW!
  • PeepCode (https://peepcode.com/screencasts/ruby-on-rails)
    • I haven’t started this one yet. But I’ve been told it’s pretty good. Definitely something worth checking out.

Having acquired some rogue skills in RoR from these screencasts, I decided to get a book to discipline myself. So I bought this one (which had pretty good reviews) – Ruby on Rails 3: Learn Rails by Example by Michael Hartl. It’s a very nice book where the author takes you through an example of creating a Twitter like site from the scratch. He does it with TDD (Test Driven Development), so that’s a plus (as other resources I’ve looked into didn’t go deep into TDD as this one did).

Having spent almost a month learning and playing with Rails. I decided it’s time to do some code. So I formatted my Windows 8 gaming machine (Alienware M15X) and installed Ubuntu 12.04 (No regrets!).

I got these installed to start with -

  • I followed this article in Smashing Magazine (step by step) and got rails working almost perfectly.
  • Next stop IDE – I’ve used Netbeans before and it looked like Netbeans had some good Rails plugins, so I went straight ahead and grabbed Netbeans with its plugins.
    • I was told Aptana Studio, Eclipse etc are also good IDE’s for Rails
    • While we’re talking about IDE’s – as I explored Rails, I found that IDE’s hardly play a major role. You can almost do everything from the terminal / console. And it’s a lot simpler too.
    • I used a Mac machine for Rails development too. I loved the Sublime text editor – way more than TextMate and other text editors I’ve used in Mac.
  • Having covered the front-end, I wanted to get a good DB environment with a decent toolset (as I will always feel nostalgic without SQL Server). PostGreSQL looked like a pretty good option. I configured it as mentioned in the article and it worked like a charm.
    • Rails comes with SQLite which isn’t too bad too.
  • Having gotten the development environment ready. It was time for source control and code hosting. I went nowhere but GitHub. I followed this article and got my repository setup in seconds.
    • There is a similar hosting application like GitHub called BitBucket – It is really sweet especially if you’re working as a team. Definitely something to checkout.
  • To get fancy – I found that there was a free CI (Continuous Integration) environment for Rails which plugged into GitHub’s public repository for free! Yes – TravisCI
    • Another good CI alternative – CircleCI which helps you plug into private repositories of GitHub
  • Deployment == Heroku == Cloud (9)
    • Heroku is a sweet place to park your app no matter if it’s Camry or a Lamborghini.

Next stop – App structure and writing some code (which I hope to cover in the next post – God knows when) :)

Simple Isolated Storage Exploitation

Isolated Storage is nothing but a storage location in a user’s local filesystem where an application can store data. The Isolated Storage is generally exploited by web applications to store information of any kind (say application data, user data, session state etc) . The initial quota for an application is 1MB, which could be modified later by the application. The maximum limit depends on the operating system and the hard disk space.

The Isolated Storage data in Windows 7 is located in:

C:\Users\<User Profile>\AppData\Local\IsolatedStorage

 In order to use Isolated Storage in a simple Silverlight Application, consider the following steps.

  • Add the Isolated Storage library,

using System.IO.IsolatedStorage;

  • Now, we need to create a file in the Isolated Storage for storing the data, so we need to instantiate IsolatedStorageFile class and inform the application to store data in the next available memory compartment.
  • Having done that, we will need to write data into that file, so we need to instantiate IsolatedStorageFileStream class with the filename, file mode and and the IsolatedStorageFile instantiation.

Consider the following code as an example:

using System.IO.IsolatedStorage;                    // Step 1

private void SaveUserData(string UserName, string Pwd, int UserNumber)

{

var file = new XDocument(

new XElement("UserNum", UserNumber,

new XElement("UserName", UserName),

new XElement("Password", Pwd))

);

using(IsolatedStorageFile isf = new IsolatedStorageFile.GetUSerStoreForApplication())            // Step2

{

IsolatedStorageFileStream isfs=new IsolatedStorageFileStream("File1", FileMode.Append, isf);          // Step 3

file.Save(isfs);

}

}

In the above code, the GetUserStoreForApplication() method gets the next available storage location available for the application. In order to store data for the entire site, the GetUserStoreForSite() method can be used.  

The above code stores the following as a file in the isolated storage.

<UserNum>1</UserNum>

<UserName>Sample User</UserName>

<Pwd>Sample Pwd</Pwd>

Though the quota is fixed for an application initailly, it can be changed by the developer. To do that the following method is used.


long a = 2048000;

isf.IncreaseQuotaTo(a);

This increases the quota for the application to 2MB.

In order to view the quotas of different silverlight applications do the following:

  • Right click the Silverlight Application and select “Silverlight”.
  • Go to “Application Storage” and you would see somthing like this.

Advantage

  • By using the isolated storage, the application can store more data and have a better control of the stored data.
  • The data stored in localized to the user’s system.
  • 

Disadvantage

  • It gets difficult to use in applications which needs to run with lower privileges.

Nested Data Binding – Silverlight

One of the major features of Silverlight, which saves the developer a lot of coding time is DataBinding, where you can bind a UserControl to data or a collection of data. If you are still wondering how DataBinding saves time, here is an example. Consider a tree of depth say 1000. Instead of adding 1000 TreeViewItems manually, you can write few lines of code to bind your TreeView to a Collection.
I would like to add this basic example for binding a TreeView to a data source. I will also be using nested binding, wherein a DataTemplate uses another DataTemplate as ItemTemplate.
Its a best practice to add the Template (DataTemplate or HierarchicalDataTemplate) to any UserControl’s Resource which is at a higher level and at a scope of visibility to the desired control. This facilitates code re-usability by the child controls.
As an example I created this sample application, where a HierarchicalDataTemplate uses another HierarchicalDataTemplate as ItemTemplate. The simplest example I could think of was a collection of Files and Folders.

Though the idea was something like an Folder Explorer. I used a simple File and Folder collection just to show the nested binding. To make the application look like a Folder Explorer, I created a Grid with two columns containing a TreeView on the left pane and a ListBox on the right pane.

Having created controls which can contain Items, I create two HierarchicalDataTemplates; one for files and the other for the folders. To keep it simple, I use a StackPanel which holds an Image and a TextBlock which has the File / Folder’s name as its Text.

Something like this.


<common:HierarchicalDataTemplate x:Name="template2">
<StackPanel Orientation="Horizontal">
<Image x:Name="imgTemplate2" Source="Images/file-icon.png" Height="15" Width="15"></Image>
<TextBlock x:Name="txtTemplate2" Text="{Binding FileName}"></TextBlock>
</StackPanel>
</common:HierarchicalDataTemplate>
<common:HierarchicalDataTemplate x:Name="template1" ItemTemplate="{StaticResource template2}"
ItemsSource="{Binding Files}">
<StackPanel Orientation="Horizontal">
<Image x:Name="imgTemplate1" Source="Images/Open-Folder-icon.png" Height="15" Width="15">
</Image>
<TextBlock x:Name="txtTemplate1" Text="{Binding FolderName}"></TextBlock>
</StackPanel>
</common:HierarchicalDataTemplate>

Having created the HierarchicalDataTemplates for the Files and Folders which can be used as ItemsSource for TreeView, we create a HierarchicalDataTemplate for the ListBox.


<common:HierarchicalDataTemplate x:Name="template3">
<StackPanel Orientation="Horizontal">
<Image x:Name="imgTemplate3" Source="Images/file-icon.png" Height="25" Width="25"></Image>
<Text
Block x:Name="txtTemplate3" Text="{Binding FileName}"></TextBlock>
</StackPanel>
</common:HierarchicalDataTemplate>

After creating all the HierarchicalDataTemplates, we can now createthe  TreeView and ListBox and ItemsSource them to their respective HierarchicalDataTemplates

<controls:TreeView x:Name="TreeBind" ItemTemplate="{StaticResource template1}"
ItemsSource="{Binding Folders}"
SelectedItemChanged="TreeBind_SelectedItemChanged">
</controls:TreeView>
<ListBox x:Name="lstRight" Grid.Column="1" ItemTemplate="{StaticResource template3}"
ItemsSource="{Binding Folders}"
SelectionChanged="lstRight_SelectionChanged"></ListBox>

One which holds the File information and the other which holds Folder information.

public class FileInfo
{
/// <summary>
/// File Name
/// </summary>
private string _fileName;

public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
_fileName = value;
}
}
}
public class FolderInfo
{
/// <summary>
/// FolderName
/// </summary>
private string _folderName;

public string FolderName
{
get { return _folderName; }
set
{
if (_folderName != value)
_folderName = value;
}
}

/// <summary>
/// Collection of Files inside a Folder
/// </summary>
public ObservableCollection<FileInfo> Files { get; set; }

}  After this, I create a simple method to populate the TreeView on the left pane.
/// <summary>
/// A method to populate the TreeView
/// </summary>
private void PopulateTreeView()
{
for (int i = 0; i < 10; i++)
files.Add(new FileInfo() { FileName = "File" + i });

for (int i = 0; i < 10; i++)
{
Folders.Add(new FolderInfo()
{
FolderName = "Folder" + i,
Files = files
});
}

TreeBind.ItemsSource = Folders;
}

I also create the SelectedItemChanged event for the TreeView and ListBox to make the application look like a simple Folder Explorer.


/// <summary>
/// LstRight SelectionChanged Event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstRight_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FileInfo file = (FileInfo)lstRight.SelectedItem;
MessageBox.Show("You selected " + file.FileName, "Sample MessageBox", MessageBoxButton.OK);
}

/// <summary>
/// TreeBind SelectedItemChanged Event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TreeBind_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Type tSelectedItem = TreeBind.SelectedItem.GetType();
Type tFolders = typeof(FolderInfo);
Type tFiles = typeof(FileInfo);

if (tSelectedItem == tFolders)
{
FolderInfo folder = (FolderInfo)TreeBind.SelectedItem;

lstRight.ItemsSource = folder.Files;
}

if (tSelectedItem == tFiles)
{
FileInfo file = (FileInfo) TreeBind.SelectedItem;
MessageBox.Show("You selected " + file.FileName,"Sample MessageBox",MessageBoxButton.OK);
}
}

Hope this application gives a flavor of Folder Explorer which can be used in different scenarios.   Here are few screenshots of the application.

- Aswin Ramakrishnan

A Simple WCF with Silverlight

I would like to add this basic introduction to WCF where I create a Silverlight Application hosted in a ASP.NET Web Application and a WCF Service to it.

I explain it here using Visual Studio 2008, but you may also use Visual Studio 2010.

If you don’t have Silverlight development toolkit, I would recommend the following download:

Silverlight 3 tools for Visual Studio 2008 SP1

http://www.microsoft.com/downloads/details.aspx?familyid=9442b0f2-7465-417a-88f3-5e7b5409e9dd&displaylang=en

Also, Silverlight Web Platform installer in case you haven’t done this previously.

http://www.microsoft.com/web/gallery/install.aspx?appid=silverlight4tools;silverlight4toolkit;riaservicestoolkit

Don’t forget to install the Silverlight Toolkit. You can find it here.

http://silverlight.codeplex.com/

I installed Silverlight 3 November 2009 tools for VS 2008 and think its pretty stable.

In case you find debugging errors saying you will need Silverlight Managed debugging package (I mean after installing the toolkit and the web platform installer).

Something like this.

Silverlight Managed Debugging Package Error

Try reinstalling the Silverlight Package (Visual Studio tools, SDK and Web Platform Installer or Silverlight Developer Runtime ).

Though reinstalling the Silverlight 3 stuff will provide a straight forward solution, if you find the errors coming up again. Do the following:

Download the chainer package. Go to command line and then to the directory where you downloaded the chainer.

Execute this command: silverlight_chainer.exe /x:SLChainer \Folder

The package gets extracted in the <currentDirectory>\SLChainer\Folder location.

Run the Silverlight 2.0 executable in case you have Silverlight 2.0 or less or the Silverlight SDK if you have Silverlight 2.0 installed.

Try giving a restart to the system. You should be fine.

Alright now. After the above steps, you should be good to start a Silverlight Application hosted in ASP.NET website.

Open a new project as usual.

Select Silverlight and choose Silverlight Application in the right pane

Note: If you have Silverlight 2.0, you will be able to create Silverlight Navigation Application only.

Select Host the project in a new web site. (You can also uncheck the checkbox, but you will need to run your Silverlight (SL)  Application out-of-browser in order to make the WCF service run and to avoid any Communication Exceptions.

So to keep it simple, lets start by hosting the SL Applicatoin in a new website.

Alright now. We are all set to rock and roll. :)

Now open the MainPage.xaml and create a textblock and a button inside a StackPanel.

Note: though VS2010 shows us the designer view of the SL Page, as a best practice we will write the MainPage.xaml without looking at the Designer view.

Now. This is my MainPage.xaml

<UserControl x:Class="WCFIntroduction.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot">
<Grid.Background>
<LinearGradientBrush>
<GradientStop Color="Azure" Offset="0.5" />
<GradientStop Color="White" Offset="0.2" />
</LinearGradientBrush>
</Grid.Background>
<StackPanel x:Name="StackPanel">
<TextBlock x:Name="txtblock"  Text="Text" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button Content="Click Me!" Click="btn1_Click"></Button>
</StackPanel>
</Grid>
</UserControl>

I just created a textblock control and a button control giving them appropriate names and declaring an event handler for the button’s Click event.

Now, add the WCF service to the ASP.NET Web Site by right-clicking the project and Add-> Add New Item-> Silverlight Enabled WCF Service

You can also add the regular WCF Service. It works too.

Having added the Service, I add the following code.


using System;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Activation;

using System.Collections.Generic;

using System.Text;

namespace WCFIntroduction.Web

{

[ServiceContract]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class WCFService

{

[OperationContract]

public string PrintTime(string txt)

{

return string.Format("The Time now is: {0}", DateTime.Now);

}

// Add more operations here and mark them with [OperationContract]

}

}

This code returns a string with a Time Stamp on it. Having created the Service, Build the solution and check for errors. When the service is error-free,  right click the service and select View in Browser. This is essential because, if you miss this step, the port for the service will not be opened and you will encounter errors while adding the service to the Silverlight Application.

If your service is good, it should look something like this when you view it in a browser.

You can click the link, and view the WSDL code for the service you added.

Now its time to add the service to the Silverlight Application. In order to do that, right-click the SL Project or the Service Reference folder and select Add Service Reference.

You should see the following dialog box.

Now click the Discover button to discover the services inside the Solution.

Note: The address in the address combo-box will be detected automatically if you view the Service in a web browser. If you find errors while discovering the solution, it means the port has not been opened for the web service. It will be resolved if you view the web service in the browser.

Having added the service, add a reference to your MainPage.xaml.cs code, and write the code to wire up the Service to the SL Application.

The basic steps to add a service to any project is :

- To instantiate the Service client you just created.

- Declare Event Handler(s) to the methods (or) Operational Contracts you created in the Service.

- Call the Async method for the event you just added.

- Define the event handler you declared previously.

The following code shows how you can wire up a service to an application (the SL Application in our case).


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using WCFIntroduction.ServiceReference1;

namespace WCFIntroduction

{

public partial class MainPage : UserControl

{

public MainPage()

{

InitializeComponent();

}

private void btn1_Click(object sender, EventArgs e)

{

WCFServiceClient client = new WCFServiceClient();

client.PrintTimeCompleted+=new EventHandler<PrintTimeCompletedEventArgs>(client_PrintTimeCompleted);

client.PrintTimeAsync(txtblock.Text);

}

private void client_PrintTimeCompleted(object sender, PrintTimeCompletedEventArgs e)

{

txtblock.Text = e.Result;

}

}

}

Having done this, we are all set to debug our project. After building and knowing that the code is error-free, its F5 time.
Debug and you should see something like this.
When you click the button, you should see this
You might encounter Communication Exception while debugging if you have your Silverlight Application as your Start-up project and not having it to Out-of-Browser.
In order to resolve this, set the ASP.NET Application as the Startup Project or set the Silverlight Application to work out-of-browser.
To make the SL Application work out-of-browser, right click the project, Select Properties and in the Silverlight tab, check the Enable running application out of browser.
This is the introduction to create a basic WCF Service and adding it to a Silverlight Project. Hope this post was useful.