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) :)

Ext JS hack to use Font Awesome as Icon Class

Recently, I created a hack to use the awesome Font Awesome library alongside Ext JS (3.4). The hack I did allows font awesome icons to be served as good Ext JS icons for Tree Panels.

The following is the code -

Ext.sequence(Ext.tree.TreeNode.prototype, 'render', function (treenode) {        
    $('.x-tree-node-icon').removeClass('x-tree-node-icon').replaceWith(function () {
        if (typeof($(this).attr('class')) != 'undefined')
            return '<i class="' + $(this).attr('class') + '"/>';
        else
            $(this).addClass('.x-tree-node-icon');
    });
});    

Ext.intercept(Ext.tree.TreeNode.prototype, 'setIconCls', function (cls) {               
    $($(this)[0].ui.elNode).find('i').removeClass().addClass(cls);
});

After including this javascript at the top level, you can use Font Awesome (3.4) icons by just referencing them in the iconCls. This hack can also be extended for button icons etc.

Here is the link to the github repository – https://github.com/aswinramakrish/ext-js_font-awesome

 

Sharepoint Document Library for Document Management

Document Management could get painful, especially when you are saving documents in your server. Even though storage is cheap, managing documents via Sharepoint could be a neat solution if you are using Sharepoint as some kind of a back end CMS. I did some document management using Sharepoint for one of my projects that I’d like to share. So let’s jump right in.

In order to manage documents, you will have to do these:

  • Have a DTO (a Data Transfer Object –  if necessary) to send the document information (if you are doing AJAX using jQuery or whatever)
  • Document Upload – In order to upload documents, you will need the following methods
    • Check if the folder exists – A method to check if the folder exists
    • Create Folder – Create a folder in the document library (to store documents by an Entity ID)
    • Upload File – Upload documents to a specific folder
  • Document Download – Download the specified document
  • Delete documents

DTO Definition

This is how my DTO looks -

public class MyDTO
{
public string Id { get; set; }            // ID of the document
public string Index { get; set; }         // Index of the document
public string FileName { get; set; }      // File Name
public string FileTypeIcon { get; set; }  // File Type Icon
public string CreatedOn { get; set; }     // Created On
public string FileRef { get; set; }       // Sharepoint File Reference
}

Document Upload

To upload documents, the first method we’ll look at is the CheckIfFileExists method -


/// <summary></pre>
 /// Check if a file / folder exists
 /// </summary>
 /// <param name="FilePath">File Path</param>
 /// <returns></returns>
 public bool CheckFileExists(string FilePath)
 {
 Lists lists = new Lists();
 lists.Url = ConstructServiceUrl("Lists.asmx");  // A custom method to construct Sharepoint URL eg. https://yoursharepointsite.com/_vti_bin/lists.asmx
 lists.Credentials = new System.Net.NetworkCredential("Username", "Password"); // Your Sharepoint credentials

XmlNode nodes;

 // Instantiate an XmlDocument object
 System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
 System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
 System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
 System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");

query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" +
 "<Value Type=\"Counter\">0</Value></Gt></Where>";
 viewFields.InnerXml = "<FieldRef Name=\"Title\" /><FieldRef Name=\"Description\" />";
 queryOptions.InnerXml = "<ViewAttributes Scope=\"RecursiveAll\"/>";

nodes = lists.GetListItems("UploadList", null, query, viewFields, "5", queryOptions, null); // Get List Items from the Sharepoint List Library "UploadList"

foreach (System.Xml.XmlNode node in nodes)
 {
 if (node.Name == "rs:data")
 {
 int index = 1;
 for (int i = 0; i < node.ChildNodes.Count; i++)
 {
 if (node.ChildNodes[i].Name == "z:row")
 {
 if (node.ChildNodes[i].Attributes["ows_FileRef"].Value.Split('#')[1] == FilePath)
 {
 return true;
 }
 }
 }
 }
 }
 return false;
 }
<pre>

Next, we want to create a folder to save all the documents.

</pre>
/// <summary>
 /// Creates Folder
 /// </summary>
 /// <param name="FolderPath">Folder Path</param>
 /// <returns></returns>
 public bool CreateFolder(string FolderPath)
 {
 Dws dws = new Dws();
 dws.Url = ConstructServiceUrl("Dws.asmx");  // Custom method to construct the web service URL eg: https://yoursharepointsite.com/_vti_bin/dws.asmx
 dws.Credentials = new System.Net.NetworkCredential("Username", "Password");

if (!CheckFileExists(FolderPath))
 {
 dws.CreateFolder(FolderPath);
 return true;
 }
 else
 {
 return false;
 }
 }
<pre>

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